• 使用Caffeine实现帖子的缓存来优化网站的运行速度


    导入依赖

    		
    		<dependency>
    			<groupId>com.github.ben-manes.caffeinegroupId>
    			<artifactId>caffeineartifactId>
    			<version>3.1.7version>
    		dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在Service层中调用Caffeine的接口

    @Service
    public class DiscussPostService {
    
        private final static Logger logger = LoggerFactory.getLogger(DiscussPostService.class);
    
        @Autowired
        private DiscussPostMapper discussPostMapper;
    
        @Value("${caffeine.posts.max-size}")
        private int maxSize;
    
        @Value("${caffeine.posts.expire-seconds}")
        private int expireSeconds;
    
        // Caffeine's core API: Cache, LoadingCache, AsyncLoadingCache
    
        // posts list cache
        private LoadingCache<String, List<DiscussPost>> postListCache;
    
        // posts total number cache
        private LoadingCache<Integer, Integer> postRowsCache;
    
        @PostConstruct
        public void init(){
            // initialize the post list cache
            postListCache = Caffeine.newBuilder()
                    .maximumSize(maxSize)
                    .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                    .build(new CacheLoader<String, List<DiscussPost>>() {
                        @Override
                        public @Nullable List<DiscussPost> load(String key) throws Exception {
                            if(key == null || key.length() == 0){
                                throw new IllegalArgumentException("parameter error: key must not be null");
                            }
                            String[] params = key.split(":");
                            if(params == null || params.length != 2) {
                                throw new IllegalArgumentException("parameter error");
                            }
                            int offset = Integer.valueOf(params[0]);
                            int limit = Integer.valueOf(params[1]);
    
                            // in there, we can add second level cache, such as Redis
                            // if we can't find data in the Redis, then query it in MySQL
    
                            logger.debug("load post list from DB...");
                            return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);
                        }
                    });
            // initialize the post total number cache
            postRowsCache = Caffeine.newBuilder()
                    .maximumSize(maxSize)
                    .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                    .build(new CacheLoader<Integer, Integer>() {
                        @Override
                        public @Nullable Integer load(Integer key) throws Exception {
                            logger.debug("load post list from DB...");
                            return discussPostMapper.selectDiscussPostRows(key);
                        }
                    });
        }
    
        public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) {
            if(userId == 0 && orderMode == 1){
                return postListCache.get(offset + ":" + limit);
            }
            logger.debug("load post list from DB...");
            return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);
        }
    
        public int findDiscussPostRows(int userId) {
            if (userId == 0) {
                return postRowsCache.get(userId);
            }
            logger.debug("load post rows from DB...");
            return discussPostMapper.selectDiscussPostRows(userId);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    测试

    @SpringBootTest
    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = MyCommunityApplication.class)
    public class CaffeineTest {
    
        @Autowired
        private DiscussPostService postService;
    
        @Test
        public void testCache(){
            System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
            System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
            System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
            System.out.println(postService.findDiscussPosts(0, 0, 10, 0));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    结果:
    在这里插入图片描述
    可以看到,第一次记录还未加入缓存,所以是从DB中加载,而后两次访问记录都是从Caffeine中加载的;最后一次访问是强制要求从DB中访问的。

    通过压力测试检测使用缓存提高的效率

  • 相关阅读:
    全向相机模型Omnidirectional Camera Model
    Web前端—小兔鲜儿电商网站底部设计及网站中间过渡部分设计
    Transformer架构
    US-DAPQ-N驱动双比例阀的比例放大器
    软设上午题错题知识点5
    【MySQL】高性能高可用表设计实战-表设计篇(MySQL专栏启动)
    Oracle创建Trigger报错
    【Linux】进程信号
    利用通信基础设施提高电网的稳态稳定性(Matlab代码实现)
    c语言编程文件的输入输出函数
  • 原文地址:https://blog.csdn.net/weixin_44609676/article/details/132636725