zoukankan      html  css  js  c++  java
  • 升级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;
    }
    

      

  • 相关阅读:
    pat 1123 Is It a Complete AVL Tree
    pat 1098 Insertion or Heap Sort
    pat 1147 Heaps
    Python中的Dict底层 | 字典类型删除数据为什么不直接删除?
    MySQL | 重置root密码
    MySQL | 安装后初次使用
    安装MySQL | 报缺失文件的错误
    IDEA | 不使用骨架创建Maven项目
    python | list.sort()和sorted(list)的区别
    python | 字符串不可修改
  • 原文地址:https://www.cnblogs.com/brant/p/12496752.html
Copyright © 2011-2022 走看看