背景
接上篇《spring-boot-cache应用小结(Redis篇)》
由于有的项目用到了redisson,想着为了项目的简洁,决定用redisson客户端进行缓存,没想到居然发现了很大的诧异
同样的配置和代码
spring:
cache:
type: redis
cache-names: test
redis:
key-prefix: TEST_
time-to-live: 10m
@Service
@CacheConfig(cacheNames = ["SYS_CONFIG"])
class SysConfigService(val configRepository: SysConfigRepository) {
val log = logger<SysConfigService>()
@Cacheable("SYS_CONFIG_DETAIL", key = "#name + '_' + #i")
fun findByName(name: String, i: Int): SysConfig? {
log.info("load from db {} {}", name, i)
return configRepository.findByKey(name)
}
@Cacheable("SYS_CONFIG_ALL")
fun all(): List<SysConfig> {
log.info("load from db")
return configRepository.findAll()
}
}
lettuce
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
根据刚才的配置查看redis中的缓存
image.png可以看出自定义key和自动生成的key都带上了TEST_前缀,这是因为配置了spring.cache.redis.key-prefix。对应的值类型都是 string
去掉key-prefix进行尝试后,再次查看
image.png发现key的生成规则是 <cacheName>::<key>。对应的值类型未改变
redisson
去掉lettuce依赖,加入redisson
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.10.4</version>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
import org.redisson.api.RedissonClient
import org.redisson.codec.JsonJacksonCodec
import org.redisson.spring.cache.CacheConfig
import org.redisson.spring.cache.RedissonSpringCacheManager
import org.redisson.spring.starter.RedissonAutoConfiguration
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@AutoConfigureAfter(RedissonAutoConfiguration::class)
class CacheConfiguration {
@Bean
fun cacheManager(client: RedissonClient): RedissonSpringCacheManager {
val config = java.util.HashMap<String, CacheConfig>()
config["METHOD_CONFIG_DETAIL"] = CacheConfig((30 * 60 * 1000).toLong(), (15 * 60 * 1000).toLong())
return RedissonSpringCacheManager(client, config, JsonJacksonCodec())
}
}
此时查看缓存
image.png
会发现设置的key-prefix失效了,并且类型也变为了hash
总结
如果想用hash缓存的话,redisson是个好选择,这样还可以取出所有想要的数据。如果只是普通缓存,lettuce足够使用了。
网友评论