• SpringBoot整合Caffeine实现缓存


    Caffeine

    Caffeine是一种基于Java的高性能缓存库,它提供了可配置、快速、灵活的缓存实现。Caffeine具有以下特点:

    • 高性能:Caffeine使用了一些优化技术,如基于链表的并发哈希表和无锁算法,以提供卓越的读写性能。
    • 容量控制:Caffeine支持多种容量控制策略,如基于大小、基于权重和基于时间等,可以根据需求设置缓存的最大大小或最大权重,并在缓存达到限制时进行逐出策略。
    • 过期策略:Caffeine提供了各种内置的过期策略,如基于访问时间、基于写入时间和定时过期等,在缓存中存储的对象可以根据这些策略进行自动过期。
    • 异步加载:Caffeine支持异步加载数据,当缓存中不存在某个键对应的值时,可以通过自定义的Loader接口来异步加载数据。
    • 统计和监听:Caffeine提供了缓存统计功能,可以获取缓存的命中率、缓存项数量等信息,还支持注册缓存监听器,在缓存发生变化时触发相应的事件。

    序列化

    Caffeine缓存不涉及任何序列化,因此目标缓存对象不需要实现Serializable接口。若涉及多级缓存或者多种缓存共用,其它需要网络传输或者持久化的缓存需要序列化,Caffeine尽管也使用实现序列化的实体类,但是不做序列化操作。

    不需要序列化,降低了缓存使用难度。

    引入依赖

    1. <dependency>
    2. <groupId>com.github.ben-manes.caffeine</groupId>
    3. <artifactId>caffeine</artifactId>
    4. </dependency>

    全局配置

    1. spring:
    2. cache:
    3. type: caffeine

    缓存配置

    配置缓存管理器:多CacheName配置。

    1. public interface CacheNameTimeConstant {
    2. String CACHE_DEFAULT = "CACHE_DEFAULT";
    3. String CACHE_10SECS = "CACHE_10SECS";
    4. String CACHE_60SECS = "CACHE_60SECS";
    5. }

    同一个CacheManager配置多个CacheName,此处仅配置过期时间的差异,其余配置可自由增加。

    1. import com.example.demo.util.CacheNameTimeConstant;
    2. import com.github.benmanes.caffeine.cache.Caffeine;
    3. import org.springframework.cache.CacheManager;
    4. import org.springframework.cache.caffeine.CaffeineCache;
    5. import org.springframework.cache.support.SimpleCacheManager;
    6. import org.springframework.context.annotation.Bean;
    7. import org.springframework.context.annotation.Configuration;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. import java.util.concurrent.TimeUnit;
    11. @Configuration
    12. public class CaffeineConfig{
    13. @Bean
    14. public CacheManager caffeineCacheManager() {
    15. SimpleCacheManager cacheManager = new SimpleCacheManager();
    16. List caches = new ArrayList<>();
    17. caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_5SECS,
    18. Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build()));
    19. caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_10SECS,
    20. Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build()));
    21. caches.add(new CaffeineCache(CacheNameTimeConstant.CACHE_30SECS,
    22. Caffeine.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build()));
    23. cacheManager.setCaches(caches);
    24. return cacheManager;
    25. }
    26. }

    controller

    1. @RestController
    2. @RequestMapping("/test")
    3. public class TestController {
    4. @Resource
    5. private StuMapper stuMapper;
    6. /**
    7. * 添加缓存
    8. */
    9. @GetMapping("/selectStu/{id}")
    10. @Cacheable(value = CacheNameTimeConstant.CACHE_30SECS,key="#id")
    11. public Student selectStu(@PathVariable Integer id){
    12. return stuMapper.selectById(id);
    13. }
    14. /**
    15. * 更新缓存
    16. */
    17. @PostMapping("/updateStu")
    18. @CachePut(value = CacheNameTimeConstant.CACHE_30SECS,key = "#student.id")
    19. public Student updateStu(Student student){
    20. if (stuMapper.updateById(student) > 0) {
    21. return stuMapper.selectById(student.getId());
    22. }
    23. return null;
    24. }
    25. /**
    26. * 删除缓存
    27. */
    28. @PostMapping("/deleteStu/{id}")
    29. @CacheEvict(value = CacheNameTimeConstant.CACHE_30SECS,key = "#id")
    30. public String deleteStu(@PathVariable Integer id){
    31. return stuMapper.deleteById(id) > 0 ? "删除成功" : "删除失败";
    32. }
    33. }

    启动类

    添加@EnableCaching注解

    1. @SpringBootApplication
    2. @EnableTransactionManagement
    3. @EnableCaching
    4. public class DemoApplication {
    5. public static void main(String[] args) {
    6. SpringApplication.run(DemoApplication.class, args);
    7. System.out.println("启动成功");
    8. }
    9. @Bean
    10. public MessageConverter jsonMessageConverter(){
    11. return new Jackson2JsonMessageConverter();
    12. }
    13. }

    测试

    第一次查询,是走数据库的

    第二次查询不走数据库,直接返回缓存,但是30s后过期

     更新缓存

    再次查询数据时,从更新的缓存获取

  • 相关阅读:
    重构项目 vue2 => vue3 & nuxt2 => nuxt3 遇到的问题
    Nginx优化方案
    arm64架构安装kubeedge报错:Unit kubepods.slice already exists
    深度学习入门(第二天)——走进深度学习的世界 神经网络模型
    Vue3管理后台项目使用高德地图选点
    向日葵远程控制引起惠普战笔记本亮度无法调节问题
    idea怎么连接redis
    JVM类加载(类加载过程、双亲委派模型)
    AUTOSAR CAN网络Bus Load Reduction Mechanism
    竹云产品入选《2023年度上海市网络安全产业创新攻关成果目录》
  • 原文地址:https://blog.csdn.net/qq_63431773/article/details/133874522