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
     
     
     
     
  • 相关阅读:
    20170225-ALV tree 显示
    20170225-第一件事:SAP模块清单
    20170225 ABAP获取字符串长度/字节长度
    记录001:AS11 BAPI
    Ghost wenjian目录
    20170223-问题001,增强中的E消息 显示为 S模式消息,
    孩子教育分析
    笔记:智能分类
    从市电接信号串联电阻聊到电阻的耐压
    锂聚合物电池和液态锂电池
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/11607455.html
Copyright © 2011-2022 走看看