spring集成redis缓存的注解实现

1.增加spring-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"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans      
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd      
                        http://www.springframework.org/schema/context      
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd      
                        http://www.springframework.org/schema/mvc      
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd  
                        http://www.springframework.org/schema/cache   
                        http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">   
      
    <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->    
    <cache:annotation-driven cache-manager="cacheManager" />    
      
     <!-- redis 相关配置 -->    
     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">    
         <property name="maxIdle" value="300" />     
         <property name="maxWaitMillis" value="3000" />    
         <property name="testOnBorrow" value="true" />    
     </bean>    
  
     <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"    
       p:host-name="192.168.1.***" p:port="6379" p:password="123456" p:pool-config-ref="poolConfig"/>    
    
     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">    
         <property name="connectionFactory" ref="JedisConnectionFactory" />    
     </bean>    
      
     <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->    
     <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    
         <property name="caches">    
            <set>    
                <!-- 这里可以配置多个redis -->  
                <!-- <bean class="com.cn.util.RedisCache">    
                     <property name="redisTemplate" ref="redisTemplate" />    
                     <property name="name" value="default"/>    
                </bean> -->    
                <bean class="com.power.rediscache.RedisCache">    
                     <property name="redisTemplate" ref="redisTemplate" />    
                     <property name="name" value="common"/>    
                     <!-- common名称要在类或方法的注解中使用 -->  
                </bean>  
            </set>    
         </property>    
     </bean>    
      
</beans>


2.springMVC.xml文件增加

<import resource="spring-redis.xml"/>


3.增加Redis缓存类

public class RedisCache implements Cache{  
  
    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() {  
       // TODO Auto-generated method stub    
        return this.name;    
    }  
  
    @Override    
    public Object getNativeCache() {  
      // TODO Auto-generated method stub    
        return this.redisTemplate;    
    }  
   
    @Override    
    public ValueWrapper get(Object key) {  
      // TODO Auto-generated method stub  
      System.out.println("get 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) {  
       // TODO Auto-generated method stub  
       System.out.println("put key");  
       final String keyf = key.toString();    
       final Object valuef = value;    
       final long liveTime = 86400;    
       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) {    
         // TODO Auto-generated method stub    
         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;  
        }  
  
}  


5.项目中加入commons-pool2-2.0.jarjedis-2.4.2.jarspring-data-redis-1.6.0.RELEASE.jar 


6.最后在service实现类方法上标注相应注解@Cacheable(value="common",key="'id_'#id")



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

计算机老哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值