Home > Database > Redis > body text

About spring redis annotation to implement caching mechanism

藏色散人
Release: 2020-11-02 14:08:19
forward
2139 people have browsed it

The following column Redis Tutorial will introduce to you the caching mechanism implemented by spring redis annotations. I hope it will be helpful to friends in need!

1. xml configuration

 <bean id="poolConfigTax" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="${redis_tax.maxIdle}" />  
        <property name="minIdle" value="${redis_tax.minIdle}" />  
        <property name="maxTotal" value="${redis_tax.maxTotal}" />
        <property name="testOnBorrow" value="${redis_tax.testOnBorrow}" />  
    </bean>  
    <!-- Tax redis 数据库  -->
    <bean id="connectionFactoryTax" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"   
        p:host-name="${redis_tax.host}" p:port="${redis_tax.port}" p:password="${redis_tax.pass}"  p:pool-config-ref="poolConfigTax"
        p:database="0"/>  
    <!--redis操作模版,使用该对象可以操作redis  -->  
    <bean id="redisTemplateTax" class="org.springframework.data.redis.core.RedisTemplate" >    
        <property name="connectionFactory" ref="connectionFactoryTax" />    
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can&#39;t cast to String!!  -->    
        <property name="keySerializer" >    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    
        </property>    
        <property name="valueSerializer" >    
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />    
        </property>    
        <property name="hashKeySerializer">    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>    
        </property>    
        <property name="hashValueSerializer">    
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>    
        </property>    
        <!--开启事务  -->  
        <property name="enableTransactionSupport" value="false"></property>  
    </bean>   
    <!-- 配置RedisCacheManager -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplateTax" />
    </bean>
    <cache:annotation-driven cache-manager="redisCacheManager"/>
Copy after login

2. Detailed explanation of cache annotations @Cacheable, @CacheEvict, @CachePut
1. Detailed explanation of @Cacheable usage
1. Where is it used? Used on methods or classes.
2. What is the difference between these two usages?
Used on a method to indicate: the return value of the method will be cached
Used on a class to indicate: all methods of the class support this annotation
3. What is the result after use? The next time this method is called with the same method and the same parameters, the value will be obtained directly from the cache without the need to execute the method again.
4. How is the return value stored in the cache? Stored in the cache in the form of key-value pairs, value is the return value, and key is generated by two strategies: default strategy and custom strategy
5. How to use the default strategy and the default strategy?
Default strategy: double "::" splicing after the value value, formal parameter list, when the formal parameter is an object, use json format:

@CacheConfig(cacheNames="enterprise")//<!-- 声明缓存使用的缓存名称 -->
public interface EnterpriseRepo extends JpaRepository<Enterprise, Integer>,JpaSpecificationExecutor<Enterprise>{
    @Cacheable(value="cash1")
    Enterprise findByid(Integer id);

    @CachePut(value="cash1")
    Enterprise save(Enterprise enterprise);

}
Copy after login

Custom strategy: key attribute is used to specify Spring The return result of the cache method is the corresponding key. This property supports SpringEL expressions. When we do not specify this attribute, Spring will use the default strategy to generate keys.

Custom strategy means that we can specify our key through Spring's EL expression. EL expressions here can use method parameters and their corresponding properties. When using method parameters, we can directly use "#parameter name" or "#pparameter index". Here are a few examples of using parameters as keys.

@Cacheable(value="users", key="#id")

   public User find(Integer id) {
      return null;
   }

   @Cacheable(value="users", key="#p0")
   public User find(Integer id) {
      return null;
   }

   @Cacheable(value="users", key="#user.id")
   public User find(User user) {
      return null;
   }

   @Cacheable(value="users", key="#p0.id")
   public User find(User user) {
      return null;
   }
Copy after login

In addition to the above method parameters as keys, Spring also provides us with a root object that can be used to generate keys. Through this root object we can obtain the following information.

When we want to use the properties of the root object as the key, we can also omit "#root", because Spring uses the properties of the root object by default. For example:

@Cacheable(value={"users", "xxx"}, key="caches[1].name")

public User find(User user) {
   return null;
}
Copy after login

6. The condition attribute specifies the conditions for occurrence

Sometimes we may not want to cache all the return results of a method. This function can be achieved through the condition attribute. The condition attribute is empty by default, which means that all call situations will be cached. Its value is specified through a SpringEL expression. When it is true, it means caching; when it is false, it means no caching, that is, the method will be executed every time the method is called. The following example indicates that caching will only occur when the user's id is an even number.

@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
public User find(User user) {
   System.out.println("find user by user " + user);
   return user;
}
Copy after login

2. @CachePut

In an environment that supports Spring Cache, for methods annotated with @Cacheable, Spring will check whether there is a cache element with the same key in the Cache before each execution. , if it exists, the method will no longer be executed, but the result will be obtained directly from the cache and returned. Otherwise, it will be executed and the returned result will be stored in the specified cache. @CachePut can also declare a method to support caching functionality. The difference from @Cacheable is that the method annotated with @CachePut will not check whether there are previously executed results in the cache before execution. Instead, the method will be executed every time and the execution results will be stored in the form of key-value pairs. in the specified cache.
Generally used in save and update methods.

@CachePut can also be annotated on classes and methods. The attributes we can specify when using @CachePut are the same as @Cacheable.

@CachePut(“users”)//The method will be executed every time and the result will be stored in the specified cache

public User find(Integer id) {
      return null;
}
Copy after login

3. @CacheEvict

@CacheEvict is used to annotate methods or classes that need to clear cache elements. When marked on a class, it means that the execution of all methods in it will trigger the cache clearing operation. The attributes that can be specified by @CacheEvict include value, key, condition, allEntries and beforeInvocation. The semantics of value, key and condition are similar to the corresponding attributes of @Cacheable. That is, value indicates which Cache the clearing operation occurs on (corresponding to the name of the Cache); key indicates which key needs to be cleared. If not specified, the key generated by the default policy will be used; condition indicates the conditions under which the clearing operation occurs. Let's introduce the two new attributes allEntries and beforeInvocation.
1. allEntries attribute
allEntries is a boolean type, indicating whether all elements in the cache need to be cleared. The default is false, which means it is not needed. When allEntries is specified as true, Spring Cache will ignore the specified key. Sometimes we need to clear all elements from Cache at once, which is more efficient than clearing elements one by one.

@CacheEvict(value="users", allEntries=true)
public void delete(Integer id) {
   System.out.println("delete user by id: " + id);
}
Copy after login

2. beforeInvocation attribute
The clearing operation is triggered by default after the corresponding method is successfully executed, that is, the clearing operation will not be triggered if the method fails to return successfully because it throws an exception. You can use beforeInvocation to change the time when the clearing operation is triggered. When we specify the value of this property to be true, Spring will clear the specified element in the cache before calling this method.

@CacheEvict(value="users", beforeInvocation=true)
public void delete(Integer id) {
   System.out.println("delete user by id: " + id);
}
Copy after login

The above is the detailed content of About spring redis annotation to implement caching mechanism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!