首页 > 编程语言 > 详细

Springboot~@Cacheable非侵入式缓存

时间:2021-06-04 18:05:39      阅读:37      评论:0      收藏:0      [点我收藏+]

早在很多年前,我曾经封装过关于.net unity aop的缓存[https://www.cnblogs.com/lori/p/5169420.html],面向方法的缓存,而如今,spring早已经集成了这个技术,并且得到了广大的应用。

开启缓存功能

@SpringBootApplication
@EnableCaching
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

添加缓存

 /**
     * 不参数的
     * redis key list::SimpleKey []
     * @return
     */
    @Cacheable(value = "list", key = "")
    @GetMapping("list")
    public ResponseEntity list() {
        return ResponseEntity.ok(
                new Info("zzl", "lind",new Date())
        );
    }

    /**
     * 带参数的,支持实体类型
     * redis key list::name,instance of list::zhansan
     * @param name
     * @return
     */
    @GetMapping("detail")
    @Cacheable(value = "list", key = "#p0")
    public ResponseEntity listOne(@RequestParam String name) {
        return ResponseEntity.ok(new Info("zzl", "lind", new Date())
        );
    }

清除缓存

/**
     * del redis key for list::SimpleKey []
     * @return
     */
    @GetMapping("del")
    @CacheEvict(value = "list")
    public String delAll() {
        return "ok";
    }

    /**
     *  del redis key for list::name
     * @param name
     * @return
     */
    @GetMapping("del/{name}")
    @CacheEvict(value = "list", key = "#p0")
    public String del(@PathVariable String name) {
        return "ok";
    }

定义redis缓存策略

/**
     * spring cache配置,以json的方式存储到redis.
     *
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofMinutes(30));

        return redisCacheConfiguration;
    }

Springboot~@Cacheable非侵入式缓存

原文:https://www.cnblogs.com/lori/p/14849333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!