redis我爱编程

ssm集成redis

2018-06-27  本文已影响31人  陌生哦哦

集成

首先要安装redis
maven

<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.0.RELEASE</version>
        </dependency>


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.1</version>
        </dependency>

redis.properties

# Redis 参数配置

redis.host:127.0.0.1
redis.port:6379
redis.password:


redis.maxIdle=300
redis.maxWaitMillis=1000
redis.maxTotal=600
redis.testOnBorrow=true
redis.testOnReturn=true

redis.projectNam=ssm_redis

ApplicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!--扫描redis配置文件-->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties"/>
    <!--设置连接池-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        <property name="testOnReturn" value="${redis.testOnReturn}" />
    </bean>
    <!--设置链接属性-->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}"
          p:port="${redis.port}"
          p:password="${redis.password}"
          p:pool-config-ref="poolConfig"
          p:timeout="100000"/>
    <!-- Jedis模板配置  -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory"   ref="connectionFactory" />
    </bean>

</beans>

web.xml

classpath:spring/ApplicationContext-redis.xml

测试
controller中注入

@Resource
    private RedisTemplate redisTemplate;

然后就能使用了

redisTemplate存储对象方法

原文https://my.oschina.net/u/555061/blog/504658
一共3个工具类SpringRedisUtil ApplicationContextUtil SerializeUtil

public class SpringRedisUtil {

   @SuppressWarnings("unchecked")
   private static RedisTemplate<Serializable, Serializable> redisTemplate = 
               (RedisTemplate<Serializable, Serializable>) ApplicationContextUtil
                       .getBean("redisTemplate");
   
   public static void save(final String key, Object value) {

       final byte[] vbytes = SerializeUtil.serialize(value);
       redisTemplate.execute(new RedisCallback<Object>() {
           @Override
           public Object doInRedis(RedisConnection connection)
                   throws DataAccessException {
               connection.set(redisTemplate.getStringSerializer().serialize(key), vbytes);
               return null;
           }
       });
   }

   public static <T> T get(final String key, Class<T> elementType) {
       return redisTemplate.execute(new RedisCallback<T>() {
           @Override
           public T doInRedis(RedisConnection connection)
                   throws DataAccessException {
               byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
               if (connection.exists(keybytes)) {
                   byte[] valuebytes = connection.get(keybytes);
                   @SuppressWarnings("unchecked")
                   T value = (T) SerializeUtil.unserialize(valuebytes);
                   return value;
               }
               return null;
           }
       });
   }
}
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextUtil.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

}
public class SerializeUtil {

    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}

测试
存取对象

MerchantNearby merchantNearbys =new MerchantNearby ();
SpringRedisUtil.save("test", merchantNearbys );
merchantNearbys = SpringRedisUtil.get("mystr", TESTREDIS.class);

存取对象集合

List<MerchantNearby> merchantNearbys = (List<MerchantNearby>) dao.findForList("MerchantNearbyMapper.getMerchantNearbysByQo",merchantQo);
SpringRedisUtil.save("mystr", merchantNearbys);
merchantNearbys = (List<MerchantNearby>)SpringRedisUtil.get("mystr",MerchantNearby.class);
上一篇 下一篇

猜你喜欢

热点阅读