zoukankan      html  css  js  c++  java
  • spring cache

    参考资料:
    https://docs.spring.io/spring/docs/5.1.5.RELEASE/spring-framework-reference/integration.html#cache
     
    spring cache 提供了缓存的一些注解:
    1、@Cacheable
    (1)condition属性:可以为spEL表达式,只要满足表达式时才进行缓存。
    (2)unless属性:和condition不同的是,在方法执行之后才对条件进行判断,满足条件才进行缓存。所以unless可以对result做判断。示例:只有result为true时才进行缓存
    @Cacheable(value = "aa", key = "#param", unless = "#result")
        public boolean isTrue(String param) {
            if (param.equals("aaa")) {
                return true;
            }
            else {
                return false;
            }
        }
    2、@CachePut
    3、@CacheEvict
     
     
    spring cacheable和redis集成
    1、配置redis集群
    2、实现在注解上增加缓存的过期时间
    需要实现RedisCacheWriter接口,重写put方法(RedisCacheWriter的默认实现类为DefaultRedisCacheWriter,但该类没有被访问修饰符修饰,默认为default,所以不能跨包访问,需要自己实现RedisCacheWriter接口)
    @Override
    public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
    
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        Assert.notNull(value, "Value must not be null!");
    
        execute(name, connection -> {
    
            //判断name里面是否设置了过期时间,如果设置了则对key进行缓存,并设置过期时间
            int index = name.lastIndexOf(RedisKeys.REDIS_EXPIRE_TIME_KEY);
            if (index > 0) {
                //取出对应的时间
                String expireString = name.substring(index + 1 + RedisKeys.REDIS_EXPIRE_TIME_KEY.length());
                long expireTime = Long.parseLong(expireString);
                connection.set(key, value, Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.upsert());
            } else if (shouldExpireWithin(ttl)) {
                connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
            } else {
                connection.set(key, value);
            }
            return "OK";
        });
    }

    3、配置CacheManager

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        return new RedisCacheManager(new RedisCacheWriterCustomer(factory),cacheConfig());
    }

    其中RedisCacheWriterCustomer为RedisCacheWriter接口的实现类

    spring cache + 服务器缓存(encache)
    1、配置ehcache.xml文件
    2、配置CacheManager
     
     
     
     
  • 相关阅读:
    Cocos2d-x 3.0 lua规划 真正的现在Android在响应Home密钥和Back纽带
    SICP 练习 (2.9)解决摘要:宽度和区间运算的关系间隔
    编tuxedo遇到服务问题
    数据库关闭
    三维CAD塑造——基于所述基本数据结构一半欧拉操作模型
    采用proguard困惑android代码
    a中国天气网pi(json格式)
    android 内存优化
    如何获得最近的餐馆谁
    采购入库单已暂估生成凭证,当月后来又收到采购发票,结算后如何处理?
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/11607455.html
Copyright © 2011-2022 走看看