首页 > 其他分享 >SpringBoot整合Caffeine本地缓存

SpringBoot整合Caffeine本地缓存

时间:2024-03-06 11:11:07浏览次数:18  
标签:缓存 SpringBoot Caffeine public oldUserInfo id userInfo

一、Caffeine性能

二、Caffeine配置

注意:

1、weakValues 和 softValues 不可以同时使用。
2、maximumSize 和 maximumWeight 不可以同时使用。
3、expireAfterWrite 和 expireAfterAccess 同事存在时,以 expireAfterWrite 为准。

三、软引用和弱引用

软引用:如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。

弱引用:弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存
// 软引用
Caffeine.newBuilder().softValues().build();

// 弱引用
Caffeine.newBuilder().weakKeys().weakValues().build();

四、SpringBoot 集成 Caffeine 两种方式

SpringBoot 有两种使用 Caffeine 作为缓存的方式:

  • 方式一:直接引入 Caffeine 依赖,然后使用 Caffeine 方法实现缓存。
  • 方式二:引入 Caffeine 和 Spring Cache 依赖,使用 SpringCache 注解方法实现缓存。

1、SpringBoot 集成 Caffeine 方式一

1、Maven 引入相关依赖

<dependency>
       <groupId>com.github.ben-manes.caffeine</groupId>
       <artifactId>caffeine</artifactId>
</dependency>

2、配置缓存配置类

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .build();
    }

}

3、需要本地缓存的位置引入配置对象调用方法

@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {

    /**
     * 模拟数据库存储数据
     */
    private HashMap<Integer, UserInfo> userInfoMap = new HashMap<>();

    @Autowired
    Cache<String, Object> caffeineCache;

    @Override
    public void addUserInfo(UserInfo userInfo) {
        log.info("create");
        userInfoMap.put(userInfo.getId(), userInfo);
        // 加入缓存
        caffeineCache.put(String.valueOf(userInfo.getId()),userInfo);
    }

    @Override
    public UserInfo getByName(Integer id) {
        // 先从缓存读取
        caffeineCache.getIfPresent(id);
        UserInfo userInfo = (UserInfo) caffeineCache.asMap().get(String.valueOf(id));
        if (userInfo != null){
            return userInfo;
        }
        // 如果缓存中不存在,则从库中查找
        log.info("get");
        userInfo = userInfoMap.get(id);
        // 如果用户信息不为空,则加入缓存
        if (userInfo != null){
            caffeineCache.put(String.valueOf(userInfo.getId()),userInfo);
        }
        return userInfo;
    }

    @Override
    public UserInfo updateUserInfo(UserInfo userInfo) {
        log.info("update");
        if (!userInfoMap.containsKey(userInfo.getId())) {
            return null;
        }
        // 取旧的值
        UserInfo oldUserInfo = userInfoMap.get(userInfo.getId());
        // 替换内容
        if (!StringUtils.isEmpty(oldUserInfo.getAge())) {
            oldUserInfo.setAge(userInfo.getAge());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getName())) {
            oldUserInfo.setName(userInfo.getName());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getSex())) {
            oldUserInfo.setSex(userInfo.getSex());
        }
        // 将新的对象存储,更新旧对象信息
        userInfoMap.put(oldUserInfo.getId(), oldUserInfo);
        // 替换缓存中的值
        caffeineCache.put(String.valueOf(oldUserInfo.getId()),oldUserInfo);
        return oldUserInfo;
    }

    @Override
    public void deleteById(Integer id) {
        log.info("delete");
        userInfoMap.remove(id);
        // 从缓存中删除
        caffeineCache.asMap().remove(String.valueOf(id));
    }

}

2、SpringBoot 集成 Caffeine 方式二

1、Maven 引入相关依赖

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
       <groupId>com.github.ben-manes.caffeine</groupId>
       <artifactId>caffeine</artifactId>
 </dependency>

2、配置类

@Configuration
public class CacheConfig {

    /**
     * 配置缓存管理器
     *
     * @return 缓存管理器
     */
    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterAccess(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000));
        return cacheManager;
    }

}

3、使用

@Slf4j
@Service
@CacheConfig(cacheNames = "caffeineCacheManager")
public class UserInfoServiceImpl implements UserInfoService {

    /**
     * 模拟数据库存储数据
     */
    private HashMap<Integer, UserInfo> userInfoMap = new HashMap<>();

    @Override
    @CachePut(key = "#userInfo.id")
    public void addUserInfo(UserInfo userInfo) {
        log.info("create");
        userInfoMap.put(userInfo.getId(), userInfo);
    }

    @Override
    @Cacheable(key = "#id")
    public UserInfo getByName(Integer id) {
        log.info("get");
        return userInfoMap.get(id);
    }

    @Override
    @CachePut(key = "#userInfo.id")
    public UserInfo updateUserInfo(UserInfo userInfo) {
        log.info("update");
        if (!userInfoMap.containsKey(userInfo.getId())) {
            return null;
        }
        // 取旧的值
        UserInfo oldUserInfo = userInfoMap.get(userInfo.getId());
        // 替换内容
        if (!StringUtils.isEmpty(oldUserInfo.getAge())) {
            oldUserInfo.setAge(userInfo.getAge());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getName())) {
            oldUserInfo.setName(userInfo.getName());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getSex())) {
            oldUserInfo.setSex(userInfo.getSex());
        }
        // 将新的对象存储,更新旧对象信息
        userInfoMap.put(oldUserInfo.getId(), oldUserInfo);
        // 返回新对象信息
        return oldUserInfo;
    }

    @Override
    @CacheEvict(key = "#id")
    public void deleteById(Integer id) {
        log.info("delete");
        userInfoMap.remove(id);
    }

}

标签:缓存,SpringBoot,Caffeine,public,oldUserInfo,id,userInfo
From: https://www.cnblogs.com/sun-10387834/p/18056107

相关文章

  • springboot集成neo4j
    1创建一个springboot项目引入neo4j的依赖<!--neo4j依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-neo4j</artifactId></dependency>......
  • 聊一聊Integer的缓存机制问题
    在Java编程中,Integer类作为基本类型int的包装器,提供了对象化的操作和自动装箱与拆箱的功能。从JDK5开始引入了一项特别的优化措施——Integer缓存机制,它对于提升程序性能和减少内存消耗具有重要意义。接下来我们由一段代码去打开Integer缓存机制的秘密。publicstaticvoidmain(......
  • springboot 应用程序 pom节点版本冲突问题解决思路
    springboot应用程序pom节点版本冲突问题解决思路一、首先 mavenhelper 查看是否有冲突 conflicts 二、allDenpendencies  查询如poi 查询冲突 ps: <scope>compile</scope>  compile:这是默认的依赖项范围。指定为compile的依赖项将在编译、测试和......
  • 01_尚硅谷_SpringBoot课件
    框架高级课程系列之SpringBoot-2.3.6尚硅谷JavaEE教研组版本:V3.3一.SpringBoot概述与入门(掌握) 1.1SpringBoot概述1.1.1什么是SpringBootSpringBoot是Spring项目中的一个子工程,与我们所熟知的Spring-framework同属于spring的产品:其最主要作用就是帮助开发人员快速的......
  • springboot - 配置文件 @ConfigurationProperties
    1.简单属性@Configuration@ConfigurationProperties(prefix="mail")publicclassConfigProperties{privateStringhostName;privateintport;privateStringfrom;//standardgettersandsetters}注意:如果我们不在POJO中使用@Configurati......
  • SpringBoot中try/catch异常并回滚事务(自动回滚/手动回滚/部分回滚)
    https://www.cnblogs.com/cfas/p/16423510.html https://www.cnblogs.com/konglxblog/p/16229175.htmlSpringBoot异常处理回滚事务详解(自动回滚、手动回滚、部分回滚)(事务失效) 参考:https://blog.csdn.net/zzhongcy/article/details/102893309概念事务定义事务,就是一......
  • SpringBoot3整合Druid数据源的解决方案
    druid-spring-boot-3-starter目前最新版本是1.2.20,虽然适配了SpringBoot3,但缺少自动装配的配置文件,会导致加载时报加载驱动异常。<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-3-starter</artifactId><version>1.2.20</version......
  • SpringBoot常用注解
    SpringBoot常用注解  @SpringBootApplication=@SpringBootConfiguration+@ComponentScan+@EnableAutoConfiguration@Configuration注解能够将一个类定义为SpringBoot应用程序中的配置类,等同于spring的XML配置文件,从而使该类中的Bean对象能够被SpringIoC容器进行自动管......
  • mybatis面试高频问题---执行流程/延迟加载/缓存
    mybatis一.mybatis执行流程理解了各个组件的关系Sql的执行过程(参数映射、sql解析、执行和结果处理)二.mybatis支持延迟加载1.立即加载查询用户信息的同时也可以查询到相关订单信息UserMapper:OrderMapper:UserTest.java打印输出用户信息执行结果:2.延迟加载f......
  • spring面试高频问题---springboot自动配置
    springboot自动配置1.springboot自动配置原理自动配置主要依赖于@SpringBootApplication注解,其中还包含了三个注解@SpringBootConfiguration:该注解与@Configuration注解作用相同,用来声明当前也是个配置类。@ComponentScan:组件扫描,默认扫描当前引导类所在包及其子包。@Ena......