欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

程序员文章站 2024-02-29 19:23:34
maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略:

maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略:

<dependency> 
  <groupid>redis.clients</groupid> 
  <artifactid>jedis</artifactid> 
  <version>2.8.1</version> 
</dependency> 
<dependency> 
  <groupid>org.springframework.data</groupid> 
  <artifactid>spring-data-redis</artifactid> 
  <version>1.7.2.release</version> 
</dependency> 

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">  
   
  <context:property-placeholder location="classpath:redis-config.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="${redis.testonborrow}" />  
   </bean>  
 
   <bean id="jedisconnectionfactory" class="org.springframework.data.redis.connection.jedis.jedisconnectionfactory"  
    p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" 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.cn.util.rediscache">  
           <property name="redistemplate" ref="redistemplate" />  
           <property name="name" value="common"/>  
           <!-- common名称要在类或方法的注解中使用 --> 
        </bean> 
      </set>  
     </property>  
   </bean>  
   
</beans>  

redis-config.properties中的内容:

# redis settings 
# server ip 
redis.host=127.0.0.1 
# server port 
redis.port=6379 
# server pass 
redis.pass= 
# use dbindex 
redis.database=0 
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 
redis.maxidle=300 
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出jedisconnectionexception;  
redis.maxwait=3000 
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的  
redis.testonborrow=true 

com.cn.util.rediscache类中的内容:

package com.cn.util;  
import java.io.bytearrayinputstream; 
import java.io.bytearrayoutputstream; 
import java.io.ioexception; 
import java.io.objectinputstream; 
import java.io.objectoutputstream; 
 
import org.springframework.cache.cache; 
import org.springframework.cache.support.simplevaluewrapper; 
import org.springframework.dao.dataaccessexception; 
import org.springframework.data.redis.connection.redisconnection; 
import org.springframework.data.redis.core.rediscallback; 
import org.springframework.data.redis.core.redistemplate; 
 
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; 
    } 
 
} 

到了这一步,大部分人会想在web.xml的启动配置文件地方(context-param)加入了spring-redis.xml,让项目启动时加载这个配置文件吧,但是这样启动后注解不生效。

正确的做法是:web.xml中配置了servlet控制器:

<servlet> 
 <servlet-name>springmvc</servlet-name> 
 <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 
 <init-param> 
  <param-name>contextconfiglocation</param-name> 
  <param-value>/web-inf/spring-mvc.xml</param-value> 
 </init-param> 
 <load-on-startup>1</load-on-startup> 
 <async-supported>true</async-supported> 
</servlet> 

在dispatcherservlet的初始化过程中,框架会在web应用的 web-inf文件夹下寻找名为spring-mvc.xml的配置文件,如果不指定的话,默认是applicationcontext.xml

只需要在spring-mvc.xml文件中引入spring-redis配置文件即可,正如spring-redis.xml中的启用注解说的:<cache:annotation-driven cache-manager="cachemanager" />注解一定要声明在spring主配置文件中才会生效。

spring-mvc.xml内容,省略了spring与spring mvc整合的那部分:

<?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"  
  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"> 
  <!-- 自动扫描该包,使springmvc认为包下用了@controller注解的类是控制器 -->  
  <context:component-scan base-package="com.cn" />  
   
  <!-- 引入同文件夹下的redis属性配置文件 --> 
  <import resource="spring-redis.xml"/> 
   
</beans>  

在service的实现类中:

@service 
public class userserviceimpl implements userservice{ 
 
  @autowired 
  private userbo userbo; 
 
  @cacheable(value="common",key="'id_'+#id") 
  public user selectbyprimarykey(integer id) { 
    return userbo.selectbyprimarykey(id); 
  } 
   
  @cacheput(value="common",key="#user.getusername()") 
  public void insertselective(user user) { 
    userbo.insertselective(user); 
  } 
 
  @cacheevict(value="common",key="'id_'+#id") 
  public void deletebyprimarykey(integer id) { 
    userbo.deletebyprimarykey(id); 
  } 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。