日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Spring @Cacheable緩存注解

作者:浪子塵晨 更新時(shí)間: 2023-12-25 編程語(yǔ)言

一、簡(jiǎn)介

緩存介紹

緩存,在我們的日常開(kāi)發(fā)中用的非常多,是我們應(yīng)對(duì)各種性能問(wèn)題支持高并發(fā)的一大利器。

  • Spring 從?3.1?開(kāi)始就引入了緩存的支持。定義了如下兩個(gè)接口來(lái)統(tǒng)一支持不同的緩存技術(shù)。

    • org.springframework.cache.Cache
    • org.springframework.cache.CacheManager
  • 我們熟知的緩存有:堆緩存(Ehcache3.x、Guava Cache、Caffeine等)、堆外緩存(Ehcache3.xMapDB等)、分布式緩存(RedisMemcached等)等等。

  • 常用的緩存注解:@EnableCaching@Cacheable@CachePut@CacheEvict、

Cache 和 CacheManager 接口說(shuō)明

  • Cache 接口包含緩存的各種操作集合,你操作緩存就是通過(guò)這個(gè)接口來(lái)操作的。
  • Cache 接口下 Spring 提供了各種 xxxCache 的實(shí)現(xiàn),比如:RedisCache、EhCache、ConcurrentMapCache等。
  • CacheManager 定義了創(chuàng)建、配置、獲取、管理和控制多個(gè)唯一命名的 Cache。這些 Cache 存在于 CacheManager 的上下文中。

二、緩存實(shí)戰(zhàn)

1.開(kāi)啟緩存

在 SpringBoot 的啟動(dòng)類上添加注解@EnableCaching。

2.@Cacheable

@Cacheable?的作用 主要針對(duì)方法配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存。

常用屬性:

  • cacheNamesvalue:用來(lái)指定緩存組件名稱。

    @Cacheable(cacheNames = "users", key="#id")
    public User getUser(Integer id) {}
    
  • key:緩存數(shù)據(jù)的 key,可以用它來(lái)指定。默認(rèn)使用所有參數(shù)的值進(jìn)行組合。(key可以使用 spEL 表達(dá)式來(lái)編寫)。

    @Cacheable(cacheNames = "usersBySpEL", key="#root.methodName + '[' + #id + ']'")
    public User getUserBySpEL(Integer id) {}
    
  • keyGenerator:key 的生成器。key 和 keyGenerator 二選一使用。

    @Cacheable(cacheNames = "userByKeyGenerator", keyGenerator = "myKeyGenerator")
    public User getUserByKeyGenerator(Integer id) {}
    
  • condition:指定符合條件的情況下才緩存。

    @Cacheable(cacheNames = "userByCondition", condition = "#id > 1")
    public User getUserByCondition(Integer id) {}
    
  • unless:指定不符合條件的情況下才緩存。(可以獲取到結(jié)果進(jìn)行判斷,通過(guò) #result 獲取方法結(jié)果,unless,漢語(yǔ)意思,除非,指會(huì)緩存,除了。。。之外)。

    @Cacheable(cacheNames = "userByUnless", unless = "#id > 1")
    public User getUserByUnless(Integer id) {}
    
  • sync:是否使用異步模式。

3.@CachePut

@CachePut?的作用 主要針對(duì)配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存。

  • 區(qū)別于?@Cacheable,它每次都會(huì)觸發(fā)真實(shí)方法的調(diào)用,可以保證緩存的一致性。
  • 屬性與?@Cacheable?類同。
@CachePut(cacheNames = "users" , key = "#user.id")
public User addUser(User user) {}
4.@CacheEvict

@CacheEvict?的作用 主要針對(duì)方法配置,能夠根據(jù)一定的條件對(duì)緩存進(jìn)行清空。

常用屬性

  • cacheNames、value:用來(lái)指定緩存組件名稱。
  • key:緩存數(shù)據(jù)的 key,可以用它來(lái)指定。默認(rèn)使用所有參數(shù)的值進(jìn)行組合。(key可以使用 spEL 表達(dá)式來(lái)編寫)。
  • condition:指定符合條件的情況下的緩存。
  • allEntries:是否清空所有緩存,缺省為false。
  • beforeInvocation:是否在方法執(zhí)行前就清空,缺省為false,缺省情況下,如果方法執(zhí)行拋異常,則不會(huì)清空緩存。
@CacheEvict(cacheNames = "users", key = "#id")
public void delUserCache(Integer id) {}
5.@CacheConfig

@CacheConfig?的作用 主要針對(duì)類配置,能夠設(shè)置當(dāng)前類中 @Cacheable 的 value 屬性默認(rèn)值。當(dāng)然如果?@Cacheable?設(shè)置了 value,還是以設(shè)置的值為準(zhǔn)。

常用屬性

  • cacheNames: 指定緩存名稱默認(rèn)值。
6.@Caching

@Caching?的作用 主要針對(duì)方法配置,能夠組合多個(gè)Cache注解。比如用戶新增成功后,我們可能需要添加 id -> user、username -> user、email -> user 的緩存,此時(shí)就需要?@Caching?組合多個(gè)注解標(biāo)簽了。

常用屬性

  • cacheable:組合多個(gè)?@Cacheable?注解
  • put:組合多個(gè)?@CachePut?注解
  • evict:組合多個(gè)?@CacheEvict?注解
@CacheConfig(cacheNames = "users")
public class CacheTestServiceImpl implements CacheTestService {
    /**
     * @Cacheable 的 cacheNames 默認(rèn)為 "users"
     */
    @Cacheable(key="#id")
    public User getUser(Integer id) {...}
}
7.自定義緩存過(guò)期時(shí)間

7.1 設(shè)置全局默認(rèn)緩存過(guò)期時(shí)間:

    // 提供默認(rèn)的cacheManager,應(yīng)用于全局,實(shí)現(xiàn)存活2天
    @Bean
    @Primary
    public CacheManager defaultCacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2));
        return new RedisCacheManager(writer, config);
    }

7.2 定制部分緩存過(guò)期時(shí)間

  • 定制緩存過(guò)期時(shí)間,需要自定義RedisCacheManager來(lái)實(shí)現(xiàn)ttl設(shè)置。
  • 注意:項(xiàng)目中如已配置了RedisCacheManager需要在原配置的bean上添加注解?@Primary,以免造成干擾
	/**
		自定義RedisCacheManager,用于在使用@Cacheable時(shí)設(shè)置ttl
	 */
	@Bean
	public RedisCacheManager selfCacheManager(RedisTemplate<String, Object> redisTemplate) {
		RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
		RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
		return new SelfRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
	}

SelfRedisCacheManager.java

public class SelfRedisCacheManager extends RedisCacheManager {
    public SelfRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] cells = StringUtils.delimitedListToStringArray(name, "=");
        name = cells[0];
        if (cells.length > 1) {
            long ttl = Long.parseLong(cells[1]);
            // 根據(jù)傳參設(shè)置緩存失效時(shí)間,默認(rèn)單位是秒
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
        }
        return super.createRedisCache(name, cacheConfig);
    }
}

使用:

// value、cacheNames是等效的,ttl=600s,unless是不緩存的結(jié)果(為null時(shí)不緩存)
@Cacheable(value = "p_user=600",key = "#menu+'_'+#type+'_'+#userId",cacheManager = "selfCacheManager", unless = "#result == null")
public User getUser(...){
    xxx
}

// 當(dāng)前方法執(zhí)行時(shí)對(duì)應(yīng)的key失效,也可以用@CachePut在當(dāng)前方法執(zhí)行時(shí)更新key
@CacheEvict(cacheNames = "p_user",key = "#p.menu+'_'+#p.type+'_'+#p.user")
public boolean setUser(User p){
    xxx
}


三、spEL表達(dá)式

spEL表達(dá)式

參考地址:
1.@Cacheable設(shè)置過(guò)期時(shí)間:https://blog.csdn.net/weixin_41860719/article/details/125226096

原文鏈接:https://blog.csdn.net/fygkchina/article/details/134726030

  • 上一篇:沒(méi)有了
  • 下一篇:沒(méi)有了
欄目分類
最近更新