缓存
- 描述
- 配置
- 使用
- EhCache
- Redis
- EhRedis
- J2Cache
- NoneCache
- ehcache
- redis
- ehredis
- j2cache
默认情况下,用户无需做任何配置就可以使用 Jboot 的缓存功能,默认情况下 Jboot 是使用 作为 Jboot 的缓存方案。
如果需要修改把 Ehcahce
方案修改为使用 redis
,则可以添加如下的配置:
jboot.cache.redis.host = 127.0.0.1
jboot.cache.redis.port = 3306
jboot.cache.redis.password
jboot.cache.redis.database
jboot.cache.redis.timeout
jboot.cache.redis.clientName
jboot.cache.redis.testOnBorrow
jboot.cache.redis.testOnReturn
jboot.cache.redis.testWhileIdle
jboot.cache.redis.minEvictableIdleTimeMillis
jboot.cache.redis.timeBetweenEvictionRunsMillis
jboot.cache.redis.numTestsPerEvictionRun
jboot.cache.redis.maxAttempts
jboot.cache.redis.maxTotal
jboot.cache.redis.maxIdle
jboot.cache.redis.serializer
当,以上未配置的时候,Jboot 自动会去寻找 redis
模块来使用,redis
的配置为:
以下是 JbootRedisCacheImpl
的部分代码:
public class JbootRedisCacheImpl extends JbootCacheBase {
private JbootRedis redis;
public JbootRedisCacheImpl() {
JbootRedisCacheConfig redisConfig = Jboot.config(JbootRedisCacheConfig.class);
//优先使用 jboot.cache.redis 的配置
if (redisConfig.isConfigOk()) {
redis = JbootRedisManager.me().getRedis(redisConfig);
}
// 当 jboot.cache.redis 配置不存在时,
else {
redis = Jboot.getRedis();
if (redis == null) {
throw new JbootIllegalConfigException("can not get redis, please check your jboot.properties , please correct config jboot.cache.redis.host or jboot.redis.host ");
}
}
//....
}
显式代码调用
当一个系统有多个缓存组件的时候,可能有 redis 或者 ehcache 等,则可以使用如下use(“type”) 进行操作。
CacheUtil.use("redis").put("cacheName","key","value")
CacheUtil.use("ehcache").put("cacheName","key","value")
通过注解使用缓存
- @Cacheable
- @CacheEvict
- @CachesEvict
- @CachePut
在 service 中,Jboot 提供了以上的 4 个组件,方便我们进行缓存操作,而无需使用 CacheUtil 来显示调用。
getCommentById
方法没有使用任何注解,每次调用的时候,data后面的都是一个新的随机数。getCommentByIdWithCache
使用@Cacheable
注解,缓存的 key 是传入进来的 id,因此只要是同一个 id 值,每次返回的随机数都是一样的,因为随机数已经被缓存起来了。getCommentByIdWithCacheTime
使用@Cacheable
注解,但是添加了5秒
的时间限制,因此,在 5秒钟内,无论调用多少次,返回的随机数都是一样的,5秒之后缓存被删除,再次调用之后会是一个新的随机数,新的随机数会继续缓存 5秒钟。updateCache
使用了注解@CachePut
,每次调用此方法之后,会更新掉该 id 值的缓存- 使用了
@CacheEvict
注解,每次调用会删除该 id 值的缓存