spring 如何在同一个项目中使用内存和redis缓存?

oewdyzsn  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(92)

有两个类,都用@Cacheableorg.springframework.cache.annotation.Cacheable)注解,要么是方法,要么是类。我想这对这个问题来说没有关系。
范例:

@Cacheable(value = STATE_CACHE_NAME, key = "#root.methodName + '-' + #country?.id ?: \"null\" + '-' + #stateName ?: \"null\"")
public Long getStateId(CountryEntity country, String stateName) {...}

字符串
在某些类中,我想使用简单的内存缓存,而其他类则使用Redis缓存。两者都在Sping Boot auto-configure CacheConfigurations中配置。我如何声明此意图并使用不同的配置?

xytpbqjk

xytpbqjk1#

@Cacheable接受一个参数“cacheManager”,它允许您指定它引用CacheManager的哪个bean。
因此,您可以将其与所需CacheManager的bean的名称一起添加。

@Cacheable(cacheManager = "inMemoryCache", value = STATE_CACHE_NAME, key = "#root.methodName + '-' + #country?.id ?: \"null\" + '-' + #stateName ?: \"null\"")
public Long getStateId(CountryEntity country, String

字符串
您可以使用bean方法的名称,也可以通过@Bean的“name”参数提供名称。
例如

@Bean(name = "inMemoryCache")
CacheManager cacheManager() {
}

相关问题