【springboot系列】springboot整合guava实现本地缓存

概述

Guava Cache 是 Google 开源的一套开发工具集合,Guava Cache 是其中的一个专门用于处理本地缓存的轻量级框架,是全内存方式的本地缓存,而且是线程安全的。
和 ConcurrentMap 相比,Guava Cache 可以限制内存的占用,并可设置缓存的过期时间,可以自动回收数据,而 ConcurrentMap 只能通过静态方式来控制缓存,移除数据元素需要显示的方式来移除。

缓存回收方式

1、基于容量回收

例如maximumSize
image.png

2、基于时间回收

image.png

3、基于引用类型

CacheBuilder.weakValues():和 CacheBuilder.weakKeys() 方法类似,该方法按照弱引用方式来存储缓存项的值,允许系统垃圾回收时回收缓存项。
CacheBuilder.weakValues(),使用软引用方式来包装缓存值,只有在内存需要时(一般在接近内存溢出时),系统会按照全局LRU(least-recently-used)原则进行垃圾回收。考虑到垃圾回收的性能问题,推荐使用基于容量的回收方式。

4、手动回收

  • 回收单个缓存项,Cache.invalidate(key)
  • 批量回收,Cache.invalidateAll(keys)
  • 全部回收Cache.invalidateAll()

image.png

使用

依赖

 <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>

缓存统计功能

recordStats:开启统计功能
stats:查看统计情况
例如:

void testRecordStats(){
        Cache<String, String> callCache = CacheBuilder.newBuilder().
                initialCapacity(5)
                .maximumSize(100)
                .recordStats()
                .expireAfterAccess(1, TimeUnit.SECONDS)
                .build();


        /**
        * CacheStats{hitCount=0, missCount=0, loadSuccessCount=0, loadExceptionCount=0, totalLoadTime=0, evictionCount=0}
        */
        CacheStats stats = callCache.stats();
        System.out.println(stats);

    }

hitRate(), 缓存命中率。 hitCount(),缓存命中次数。
loadCount(),新值加载次数。
requestCount(),缓存访问次数,是命中次数和非命中次数之和
averageLoadPenalty(),加载新值时的平均耗时,以纳秒为单位。
evictionCount(),除了手动清除意外的缓存回收总次数。

并发级别

调整concurrencyLevel即可
image.png

工具类

package com.walker.springbootdemo.common.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

public class CacheUtil {
    /** 缓存值的最大数 */
    private int maximumSize = 1000;

    /** 缓存过期分钟数 */
    private int expireAfterAccessMinutes = 60 * 72;

    private Cache<String,Object> _cache = null;

    public CacheUtil()
    {
        super();
    }

    public int getMaximumSize()
    {
        return maximumSize;
    }

    public void setMaximumSize(int maximumSize)
    {
        this.maximumSize = maximumSize;
    }

    public int getExpireAfterAccessMinutes()
    {
        return expireAfterAccessMinutes;
    }

    public void setExpireAfterAccessMinutes(int expireAfterAccessMinutes)
    {
        this.expireAfterAccessMinutes = expireAfterAccessMinutes;
    }

    //项目启动时加载
    @PostConstruct
    public void init() {
        _cache = CacheBuilder.newBuilder().maximumSize(this.maximumSize).expireAfterAccess(this.expireAfterAccessMinutes * 60, TimeUnit.SECONDS).build();
    }

   
    public  Object get(String key)
    {
        return this._cache.getIfPresent(key);
    }

    public  void put(String key,Object o)
    {
        this._cache.put(key, o);
    }

    
    public  void invalidate(String key)
    {
        this._cache.invalidate(key);
    }
}

参考:
https://blog.youkuaiyun.com/Q772363685/article/details/119635353

### Spring Boot本地缓存整合教程 #### 一、概述 在Spring Boot中,可以通过集成Caffeine来实现高效的本地缓存。Caffeine是一个高性能的Java缓存库,它提供了类似于Guava Cache的功能,但在性能和灵活性方面更胜一筹[^1]。 为了使Spring Boot应用程序能够使用缓存功能,在主类或配置类中需要添加`@EnableCaching`注解以启用缓存支持[^2]。此外,还需要定义一个自定义的`CacheManager` Bean,用于管理具体的缓存策略。 --- #### 二、具体步骤 ##### 1. 添加依赖项 在项目的`pom.xml`文件中引入必要的Maven依赖: ```xml <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> ``` 上述代码片段展示了如何将Caffeine作为缓存提供者引入到Spring Boot项目中。 --- ##### 2. 配置缓存管理器 创建一个配置类,用于初始化基于Caffeine的`CacheManager`实例: ```java import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.TimeUnit; @Configuration @EnableCaching public class CaffeineConfig { @Bean public CacheManager cacheManager() { CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager("exampleCache"); caffeineCacheManager.setCaffeine(Caffeine.newBuilder() .expireAfterWrite(5, TimeUnit.MINUTES) // 设置写入后过期时间 .maximumSize(100)); // 设置最大条目数 return caffeineCacheManager; } } ``` 此部分代码实现了对Caffeine缓存的具体配置,包括设置缓存的最大大小以及数据的有效期限[^3]。 --- ##### 3. 使用缓存注解 在业务逻辑层中利用Spring Cache提供的注解机制简化开发流程。以下是几个常用的注解及其作用说明: - `@Cacheable`: 当方法被调用时会先查找缓存;如果存在,则返回缓存中的值;否则执行实际的方法体并将结果保存至缓存。 - `@CachePut`: 更新缓存而不影响原方法的行为。 - `@CacheEvict`: 删除指定键对应的缓存记录。 下面展示了一个简单的例子,演示如何通过`@Cacheable`优化数据库查询操作: ```java import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class ExampleService { @Cacheable(value = "exampleCache", key = "#id") public String getDataById(Long id) { System.out.println("Fetching data from database..."); return "Data for ID: " + id; // 模拟从数据库获取数据的过程 } } ``` 当多次请求相同ID的数据时,只有第一次真正访问底层服务,后续均直接读取缓存内容。 --- #### 三、总结 以上即是在Spring Boot中完成本地缓存整合的主要过程。借助强大的Caffeine工具包与简洁明了的Spring Cache API设计模式相结合的方式,不仅极大地提升了系统的响应速度,同时也降低了对外部资源的压力[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WalkerShen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值