springboot加入cache缓存数据存入到(redis/本地)

1.将cache缓存存入到redis中:
redisconfigure配置代码如下:
(1).注意这里使用得是redisson。
(2).配置类需要继承CacheingConfigurersupport
(3).此处没有重写缓存异常触发类,写项目时注意重写。
(4)使用:配置好后就可以使用cacherable,cacheevit,等注释。
例如:cacheable(value=“缓存到redis时的外层地址路径名称”,
id="#对应的参数名",cachemanage=“cachemanagetwo”)
注意:cachemanage不写的话默认使用@primary注释的cachemanage

/**
     * 设置redisson缓存工厂,由于下面的工厂都是用的是redisson所以注意配置redissonclient
     * @param client
     * @return
     */
    @Bean(name = "redissonconnectionfactory")
    public RedissonConnectionFactory getfactory(RedissonClient client){
        return new RedissonConnectionFactory(client);
    }

    /**
     * redis单机配置
     * @return
     */
    @Bean
    public RedissonClient getclient(){
        Config config=new Config();

        config.useSingleServer().setAddress("redis://地址")
                .setTimeout(1000)
                .setRetryAttempts(3)
                .setRetryInterval(1000)
                .setPingConnectionInterval(1000)//此项务必设置为redisson解决之前bug的timeout问题关键***
                .setDatabase(3);
        return Redisson.create(config);
    }


    /**
     * 缓存开始时或寻找缓存时
     * 自动生成redis的键肉厚存到数据库或到库内查找
     * @return
     */
    public KeyGenerator keyGenerator(){
        return (target,method,param)->{
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append(target.getClass().getName());
            stringBuilder.append(":");
            stringBuilder.append(method.getName());
            for (Object obj:param
                 ) {
                stringBuilder.append(":"+String.valueOf(obj));
            }
            String s=String.valueOf(stringBuilder);
            return s;
        };
    }

    /**
     * 配置redistemplate
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(@Qualifier("redissonconnectionfactory") RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        // 配置连接工厂
        template.setConnectionFactory(redisConnectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 设置缓存管理这里可以设置时间。格式等
     * primary关键字是为了写多个缓存条件时没写cachemanage使用的默认缓存配置
     * @param redisConnectionFactory
     * @return
     */
    @Primary
    @Bean
    public CacheManager cacheManager(@Qualifier("redissonconnectionfactory")RedisConnectionFactory redisConnectionFactory){
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(7)))
                .transactionAware().build();
    }

    @Bean(name = "cachemanagetwo")
    public CacheManager cacheManager2(@Qualifier("redissonconnectionfactory")RedisConnectionFactory redisConnectionFactory){
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(15)))
                .transactionAware().build();
    }

2.使用spring自带缓存将数据存到本地内存:
(1)本地缓存较为简洁
(2)使用方法和redis缓存类似如下:
cacheable(value=“缓存到redis时的外层地址路径名称”,
id="#对应的参数名",cachemanage=“cachemanagetwo”)
注意:cachemanage不写的话默认使用@primary注释的cachemanage同上两个均可同时配置

@Bean("localcachemanage")
    public CacheManager localcachemange(){
        final SimpleCacheManager simpleCacheManager=new SimpleCacheManager();
        List<CaffeineCache> caffeineList=new LinkedList<>();
        for (cacheDate cac:cacheDate.values()
             ) {
            caffeineList.add(new CaffeineCache(
                    cac.name(), Caffeine.newBuilder()
                    .expireAfterWrite(cac.getTtl(),cac.getDateStyle())
                    .maximumSize(cac.getSizes())
                    .build()
            ));
        }
        simpleCacheManager.setCaches(caffeineList);
        return simpleCacheManager;
    }


    public enum cacheDate{
        //缓存信息
        LOCAL_CACHE_MANAGE(24,TimeUnit.HOURS,10);
        private long ttl;//过期时间
        private TimeUnit dateStyle;//过期时间格式
        private long sizes;//数量大小

        cacheDate(long ttl, TimeUnit dateStyle, long sizes) {
            this.ttl = ttl;
            this.dateStyle = dateStyle;
            this.sizes = sizes;
        }

        public long getTtl() {
            return ttl;
        }

        public TimeUnit getDateStyle() {
            return dateStyle;
        }

        public long getSizes() {
            return sizes;
        }

        public void setTtl(long ttl) {
            this.ttl = ttl;
        }

        public void setDateStyle(TimeUnit dateStyle) {
            this.dateStyle = dateStyle;
        }

        public void setSizes(long sizes) {
            this.sizes = sizes;
        }
    }

你可能感兴趣的:(redis,redis,java)