springboot注解方式使用redis緩存


引入依賴庫

在pom中引入依賴庫,如下

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

 

注解使用

@Cacheable

@Cacheable("product")
@Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id")
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
自定義cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id” cacheManager="cacheManager")
@CachePut
應用到寫數據的方法上,如新增/修改方法
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")
@CacheEvict 
即應用到移除數據的方法上,如刪除方法
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")
提供的SpEL上下文數據

 

Spring Cache提供了一些供我們使用的SpEL上下文數據,下表直接摘自Spring官方文檔:

名字 位置 描述 示例
methodName root對象 當前被調用的方法名 #root.methodName
method root對象 當前被調用的方法 #root.method.name
target root對象 當前被調用的目標對象 #root.target
targetClass root對象 當前被調用的目標對象類 #root.targetClass
args root對象 當前被調用的方法的參數列表 #root.args[0]
caches root對象 當前方法調用使用的緩存列表(如@Cacheable(value={"cache1", "cache2"})),則有兩個cache #root.caches[0].name
argument name 執行上下文 當前被調用的方法的參數,如findById(Long id),我們可以通過#id拿到參數 #user.id
result 執行上下文 方法執行后的返回值(僅當方法執行之后的判斷有效,如‘unless’,'cache evict'的beforeInvocation=false) #result

自定義Cache配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
    * 自定義redis key值生成策略
    */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }
    
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(Object

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM