spring integrates redis cache and USES of @Cacheable @CachePut @CacheEvict annotations

  • 2020-07-21 08:02:02
  • OfStack

maven project relies on 2 jar packages in ES2en.xml, the jar packages of the other spring are omitted:


<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. Contents of 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" />  
 
  <!--  Enable cache annotations, this is necessary, otherwise the annotations will not take effect, in addition, the annotations 1 Be sure to declare in spring In the master configuration file  -->  
  <cache:annotation-driven cache-manager="cacheManager" />  
   
   <!-- redis  The related configuration  -->  
   <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 Its own cache manager, where the cache location name is defined   In the annotations value -->  
   <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
     <property name="caches">  
      <set>  
        <!--  Multiple configurations can be configured here 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 The name is used in the annotation of the class or method  --> 
        </bean> 
      </set>  
     </property>  
   </bean>  
   
</beans>  

redis-config. Contents of 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 
#  control 1 a pool How many states can I have at most idle( free ) the jedis The instance  
redis.maxIdle=300 
#  Said when borrow( The introduction of )1 a jedis Instance, the maximum wait time if the wait time exceeds ( ms ) , then simply throw JedisConnectionException ;   
redis.maxWait=3000 
#  in borrow1 a jedis Instance, whether to proceed ahead of time validate Operation; If it is true , you get jedis Examples are available   
redis.testOnBorrow=true 

com. cn. util. RedisCache the contents of the class:


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; 
    } 
 
} 

At this stage, most people would like to add spring-ES34en.xml to the startup profile of ES29en.xml (ES31en-ES32en) and have the profile load when the project starts, but the annotation doesn't take effect.

The correct approach is: ES39en. xml with servlet controller:


<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> 

During the initialization of DispatcherServlet, the framework looks for a configuration file named spring-ES50en.xml in the ES47en-ES48en folder of web application. If not specified, the default is ES52en.xml

Simply introduce the ES60en-ES61en profile in the ES57en-ES58en.xml file, as stated in the enabling annotation in ES62en-ES63en.xml: < cache:annotation-driven cache-manager="cacheManager" / > Note 1 must be declared in the spring master configuration file to take effect.

spring-mvc.xml content, omit the part integrating spring and 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"> 
  <!--  Automatically scan the package to make SpringMVC I think it's in the bag @controller The annotated class is the controller  -->  
  <context:component-scan base-package="com.cn" />  
   
  <!--  Bring in the same folder redis Property profile  --> 
  <import resource="spring-redis.xml"/> 
   
</beans>  

In the service implementation class:


@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); 
  } 
}

Related articles: