缓存

    • 描述
    • 配置
    • 使用
    • EhCache
    • Redis
    • EhRedis
    • J2Cache
    • NoneCache
    • ehcache
    • redis
    • ehredis
    • j2cache

    默认情况下,用户无需做任何配置就可以使用 Jboot 的缓存功能,默认情况下 Jboot 是使用  作为 Jboot 的缓存方案。

    如果需要修改把 Ehcahce 方案修改为使用 redis ,则可以添加如下的配置:

    1. jboot.cache.redis.host = 127.0.0.1
    2. jboot.cache.redis.port = 3306
    3. jboot.cache.redis.password
    4. jboot.cache.redis.database
    5. jboot.cache.redis.timeout
    6. jboot.cache.redis.clientName
    7. jboot.cache.redis.testOnBorrow
    8. jboot.cache.redis.testOnReturn
    9. jboot.cache.redis.testWhileIdle
    10. jboot.cache.redis.minEvictableIdleTimeMillis
    11. jboot.cache.redis.timeBetweenEvictionRunsMillis
    12. jboot.cache.redis.numTestsPerEvictionRun
    13. jboot.cache.redis.maxAttempts
    14. jboot.cache.redis.maxTotal
    15. jboot.cache.redis.maxIdle
    16. jboot.cache.redis.serializer

    当,以上未配置的时候,Jboot 自动会去寻找 redis 模块来使用,redis 的配置为:

    以下是 JbootRedisCacheImpl 的部分代码:

    1. public class JbootRedisCacheImpl extends JbootCacheBase {
    2. private JbootRedis redis;
    3. public JbootRedisCacheImpl() {
    4. JbootRedisCacheConfig redisConfig = Jboot.config(JbootRedisCacheConfig.class);
    5. //优先使用 jboot.cache.redis 的配置
    6. if (redisConfig.isConfigOk()) {
    7. redis = JbootRedisManager.me().getRedis(redisConfig);
    8. }
    9. // 当 jboot.cache.redis 配置不存在时,
    10. else {
    11. redis = Jboot.getRedis();
    12. if (redis == null) {
    13. throw new JbootIllegalConfigException("can not get redis, please check your jboot.properties , please correct config jboot.cache.redis.host or jboot.redis.host ");
    14. }
    15. }
    16. //....
    17. }

    显式代码调用

    当一个系统有多个缓存组件的时候,可能有 redis 或者 ehcache 等,则可以使用如下use(“type”) 进行操作。

    1. CacheUtil.use("redis").put("cacheName","key","value")
    2. 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 值的缓存