首页 > 编程语言 > 详细

SpringBoot集成Caffeine作本地缓存

时间:2021-01-22 17:11:23      阅读:132      评论:0      收藏:0      [点我收藏+]
  1. 依赖引入
spring-cache
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

caffeine
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>
  1. 参数配置(一般配置可以完全放在yaml文件内,不用专门写配置bean)
spring:
  cache:
    type: caffeine
    cache-names: ‘ruleCache‘
    caffeine:
      spec: initialCapacity=1000, maximumSize=18000, expireAfterAccess=20D
  1. 缓存逻辑编写
package com.cfuture.dataqualitycontrol.service.impl;

import com.cfuture.dataqualitycontrol.domain.po.Rule;
import com.cfuture.dataqualitycontrol.service.RuleService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author yangjx
 * @date 2021/1/21 14:04
 * @description
 */
@Service
public class RuleServiceImpl implements RuleService {

    @Override
    @CachePut(value = "ruleCache", key = "#rule.id")
    public Rule addRule(Rule rule) {
        return rule;  // 必须返回被缓存对象
    }

    @Override
    @Cacheable(value = "ruleCache", key = "#id")
    public Rule getRule(Long id) {
        Rule rule = Rule.builder().expression(String.valueOf(id)).message(String.valueOf(System.currentTimeMillis())).build();
        rule.setId(id);
        return rule;  // 必须返回被缓存对象
    }

    @Override
    @CacheEvict(value = "ruleCache", key = "#id")
    public boolean deleteRule(Long id) {
        return true;
    }

    @Override
    @CachePut(value = "ruleCache", key = "#rule.id")
    public Rule updateRule(Rule rule) {
        return rule;  // 必须返回被缓存对象
    }

}

SpringBoot集成Caffeine作本地缓存

原文:https://www.cnblogs.com/JaxYoun/p/14313070.html

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