当前位置: 首页 > news >正文

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

导入依赖

		<!-- https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine --><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>3.1.7</version></dependency>

在Service层中调用Caffeine的接口

@Service
public class DiscussPostService {private final static Logger logger = LoggerFactory.getLogger(DiscussPostService.class);@Autowiredprivate 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 cacheprivate LoadingCache<String, List<DiscussPost>> postListCache;// posts total number cacheprivate LoadingCache<Integer, Integer> postRowsCache;@PostConstructpublic void init(){// initialize the post list cachepostListCache = Caffeine.newBuilder().maximumSize(maxSize).expireAfterWrite(expireSeconds, TimeUnit.SECONDS).build(new CacheLoader<String, List<DiscussPost>>() {@Overridepublic @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 MySQLlogger.debug("load post list from DB...");return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);}});// initialize the post total number cachepostRowsCache = Caffeine.newBuilder().maximumSize(maxSize).expireAfterWrite(expireSeconds, TimeUnit.SECONDS).build(new CacheLoader<Integer, Integer>() {@Overridepublic @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);}
}

测试

@SpringBootTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyCommunityApplication.class)
public class CaffeineTest {@Autowiredprivate DiscussPostService postService;@Testpublic 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));}
}

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

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

http://www.lryc.cn/news/162233.html

相关文章:

  • Webpack5 搭建Vue项目(进阶版)
  • 论文阅读:Distortion-Free Wide-Angle Portraits on Camera Phones
  • 力扣每日一题---207. 课程表
  • 在Kubernetes环境中有关Nginx Ingress与API Gateway的连接问题
  • c语言练习44:深入理解strstr
  • 渗透测试漏洞原理之---【业务安全】
  • CentOS查看CPU、内存、网络流量和磁盘 I/O
  • 无人机航线规划
  • react中受控组件与非受控组件
  • 【网络教程】如何解决Docker删除镜像和容器后磁盘空间未释放的问题
  • Python中的进度条显示方案
  • 2023-09-05力扣每日一题
  • ODC现已开源:与开发者共创企业级的数据库协同开发工具
  • 生成克隆钓鱼网站与对win7进行后渗透操作
  • Ubuntu18中NVIDIA,cuda,cudnn,pytorch安装
  • MATLAB中M文件编写
  • 企业数字化神经网络
  • C++this指针
  • 【初阶C语言】操作符1--对二进制的操作
  • 安装pyscipopt
  • 原生js实现的轮盘抽奖案例
  • 最经典的解析LSA数据库(第六课)
  • C++基础入门
  • 【每日随笔】驾驭人性 ② ( 员工立场问题 | 立场转变 | 吴越同舟 | 老板如何与员工结成利益共同体 )
  • C++(QT)画图行车
  • Unity中Shader抓取屏幕并实现扭曲效果(优化)
  • 肖sir__设计测试用例方法之_(白盒测试)
  • GoT:用大语言模型解决复杂的问题
  • nginx服务和uwsgi服务如何设置开机自启动
  • 算法-分治算法