升级spring&集成Redis 二: spring4集成redis

Posted 陈小兵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了升级spring&集成Redis 二: spring4集成redis相关的知识,希望对你有一定的参考价值。

1 添加Redis依赖

引入需要集成的redis版本

<!--spring redis 2.8.2 start-->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
   <version>2.4.2</version>
</dependency>
<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-redis</artifactId>
   <version>1.7.10.RELEASE</version>
</dependency>
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.8.1</version>
</dependency>
<!--spring redis 2.8.2 end-->

  

2 添加redis相关配置

redis-config.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:cache="http://www.springframework.org/schema/cache"
       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/cache http://www.springframework.org/schema/cache/spring-cache.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">

   <context:property-placeholder location="classpath*:config/redis.properties" />

    <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
    <cache:annotation-driven cache-manager="cacheManager" />

    <!-- redis 相关配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="true" />
    </bean>

    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
        <property name="poolConfig" ref="poolConfig" />
    </bean>

    <bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
        <property name="keySerializer" ref="stringRedisSerializer" />
        <property name="hashKeySerializer" ref="stringRedisSerializer" />
        <property name="valueSerializer" ref="jacksonJsonRedisSerializer" />
        <property name="hashValueSerializer" ref="jacksonJsonRedisSerializer" />
    </bean>

    <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <!-- 这里可以配置多个redis -->
                <bean class="com.test.common.redis.RedisCacheUtil">
                    <property name="redisTemplate" ref="redisTemplate" />
                    <property name="name" value="common" />
                    <!-- common名称要在类或方法的注解中使用 -->
                </bean>
            </set>
        </property>
    </bean>
</beans>

  

3 导入配置文件

<import resource="classpath:redis-config.xml" />

4 添加redis数据库参数配置

redis.properties

###redis的配置
redis.host=192.168.1.59
redis.port=7000
redis.password=2131232
#一个pool最多可有多少个状态为idle(空闲)的jedis实例
redis.maxIdle=50
redis.minIdle=10
redis.maxWait=3000
#一个pool可分配多少个jedis实例
redis.maxTotal=200
redis.expiration=30000

  

 

5.添加redis工具类

/**
 * Redis缓存工具类: 实现Cache,支撑spring cache的使用
 */
@Component
public class RedisCacheUtil implements Cache{

   @Autowired
   private RedisTemplate<String, Object> redisTemplate;
   private String name;
   public RedisTemplate<String, Object> getRedisTemplate() {
      return redisTemplate;
   }

   public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
      this.redisTemplate = redisTemplate;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Override
   public String getName() {
      return this.name;
   }

   @Override
   public Object getNativeCache() {
      return this.redisTemplate;
   }

   @Override
   public ValueWrapper get(Object key) {
      final String keyf =  key.toString();
      Object object = null;
      object = redisTemplate.execute(new RedisCallback<Object>() {
         public Object doInRedis(RedisConnection connection)
               throws DataAccessException {
            byte[] key = keyf.getBytes();
            byte[] value = connection.get(key);
            if (value == null) {
               return null;
            }
            return toObject(value);
         }
      });
      return (object != null ? new SimpleValueWrapper(object) : null);
   }

   @Override
   public void put(Object key, Object value) {
      final String keyf = key.toString();
      final Object valuef = value;
      final long liveTime = 86400;//默认实现时间1天
      redisTemplate.execute(new RedisCallback<Long>() {
         public Long doInRedis(RedisConnection connection)
               throws DataAccessException {
            byte[] keyb = keyf.getBytes();
            byte[] valueb = toByteArray(valuef);
            connection.set(keyb, valueb);
            if (liveTime > 0) {
               connection.expire(keyb, liveTime);
            }
            return 1L;
         }
      });
   }

   private byte[] toByteArray(Object obj) {
      byte[] bytes = null;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try {
         ObjectOutputStream oos = new ObjectOutputStream(bos);
         oos.writeObject(obj);
         oos.flush();
         bytes = bos.toByteArray();
         oos.close();
         bos.close();
      }catch (IOException ex) {
         ex.printStackTrace();
      }
      return bytes;
   }

   private Object toObject(byte[] bytes) {
      Object obj = null;
      try {
         ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInputStream ois = new ObjectInputStream(bis);
         obj = ois.readObject();
         ois.close();
         bis.close();
      } catch (IOException ex) {
         ex.printStackTrace();
      } catch (ClassNotFoundException ex) {
         ex.printStackTrace();
      }
      return obj;
   }

   @Override
   public void evict(Object key) {
      System.out.println("del key");
      final String keyf = key.toString();
      redisTemplate.execute(new RedisCallback<Long>() {
         public Long doInRedis(RedisConnection connection)
               throws DataAccessException {
            return connection.del(keyf.getBytes());
         }
      });
   }

   @Override
   public void clear() {
      // TODO Auto-generated method stub
      System.out.println("clear key");
      redisTemplate.execute(new RedisCallback<String>() {
         public String doInRedis(RedisConnection connection)
               throws DataAccessException {
            connection.flushDb();
            return "ok";
         }
      });
   }

   @Override
   public <T> T get(Object key, Class<T> type) {
      // TODO Auto-generated method stub
      return null;
   }

   @Override
   public ValueWrapper putIfAbsent(Object key, Object value) {
      // TODO Auto-generated method stub
      return null;
   }

   @Override
   public <T> T get(Object arg0, Callable<T> arg1) {
      // TODO Auto-generated method stub
      return null;
   }

}

6 业务代码中cache配置使用

/** Redis cached 测试
 * value值:对应redis-config.xml中cacheManager中配置的name。
 key值:redis的key值,请保证唯一,否则会被覆盖。可以通过#参数的方式获取传入的参数作为key值
 * @return
 */
@Cacheable(value="common",key="‘test1‘")
public int getTest1() {
    int i=new Random().nextInt();
    return i;
}


@Cacheable(value="common",key="‘test2_id_‘+#userId")
public Map getTest2(String userId){
    Map map = new HashMap();
    List<TestModel> testModels=test();
    map.put("total", testModels);
    return map;
}

  

以上是关于升级spring&集成Redis 二: spring4集成redis的主要内容,如果未能解决你的问题,请参考以下文章

spring 集成 mybatis 和 redis 的配置文件

spring 集成 mybatis 和 redis 的配置文件

spring 集成 mybatis 和 redis 的配置文件

spring 集成 mybatis 和 redis 的配置文件

Spring Boot 集成 Redis 配置 MyBatis 二级缓存

Spring BootRedis集成从Docker安装到分布式Session共享