java 使用Caffeine实现本地缓存

Caffeine 是一个高性能的本地缓存库,广泛用于 Java 应用程序中。它支持多种缓存淘汰策略(如基于容量、时间、引用等),并且性能优于 Guava Cache,因此成为许多开发者的首选。

以下是一个完整的 Caffeine 本地缓存实例的实现:

1. 添加依赖

如果你使用 Maven 构建项目,请在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>3.1.8</version> <!-- 版本号可以根据需要更新 -->
</dependency>

2. 示例代码

以下是一个完整的示例,展示如何使用 Caffeine 创建和使用本地缓存。

(1) 基本缓存操作

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

public class CaffeineCacheExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建缓存实例
        Cache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100) // 设置最大容量为 100
                .expireAfterWrite(1, TimeUnit.MINUTES) // 写入后 1 分钟过期
                .build();

        // 向缓存中添加数据
        cache.put("key1", "value1");
        cache.put("key2", "value2");

        // 获取缓存中的值
        System.out.println("key1: " + cache.getIfPresent("key1")); // 输出: value1
        System.out.println("key3: " + cache.getIfPresent("key3")); // 输出: null

        // 模拟过期
        Thread.sleep(65000); // 等待 65 秒(超过 1 分钟)
        System.out.println("key1 after expiration: " + cache.getIfPresent("key1")); // 输出: null
    }
}

(2) 使用加载函数

Caffeine 支持在缓存未命中时自动加载数据。可以通过 CacheLoader 或 LoadingCache 实现。

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;

import java.util.concurrent.TimeUnit;

public class CaffeineLoadingCacheExample {
    public static void main(String[] args) {
        // 创建 LoadingCache 实例
        LoadingCache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100) // 设置最大容量为 100
                .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后 10 分钟过期
                .build(new CacheLoader<>() {
                    @Override
                    public String load(String key) {
                        return "Default Value for " + key; // 缓存未命中时加载默认值
                    }
                });

        // 获取缓存中的值(如果不存在则调用 load 方法)
        System.out.println(cache.get("key1")); // 输出: Default Value for key1
        System.out.println(cache.get("key2")); // 输出: Default Value for key2

        // 手动放入值
        cache.put("key1", "Custom Value for key1");
        System.out.println(cache.get("key1")); // 输出: Custom Value for key1
    }
}

(3) 异步加载缓存

Caffeine 支持异步加载缓存,适合耗时的数据加载场景。

import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CaffeineAsyncCacheExample {
    public static void main(String[] args) {
        // 创建异步缓存实例
        AsyncCache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .buildAsync((key, executor) -> {
                    // 模拟异步加载数据
                    return CompletableFuture.supplyAsync(() -> "Async Value for " + key);
                });

        // 异步获取缓存值
        cache.get("key1").thenAccept(value -> {
            System.out.println("key1: " + value); // 输出: Async Value for key1
        });
    }
}

(4) 统计功能

Caffeine 提供了丰富的统计功能,可以帮助你监控缓存的命中率、加载时间等。

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

public class CaffeineStatsExample {
    public static void main(String[] args) {
        // 创建带有统计功能的缓存
        Cache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100)
                .recordStats() // 开启统计功能
                .build();

        // 添加数据
        cache.put("key1", "value1");

        // 查询数据
        cache.getIfPresent("key1"); // 命中
        cache.getIfPresent("key2"); // 未命中

        // 打印统计信息
        var stats = cache.stats();
        System.out.println("Hit Count: " + stats.hitCount()); // 输出: 1
        System.out.println("Miss Count: " + stats.missCount()); // 输出: 1
    }
}

3. 常见配置选项

4. 总结

  • 优点:
    • 高性能,适合高并发场景。
    • 功能丰富,支持多种淘汰策略和加载方式。
    • 易于集成 Spring Cache。
  • 适用场景:
    • 数据频繁读取但不经常变化的场景。
    • 需要快速响应的本地缓存需求。

Spring Boot整合Caffeine实现本地缓存,是一个将高性能、基于内存的Caffeine库集成到Spring框架中的过程。Caffeine是一个轻量级且功能强大的Java高速缓存库,它提供了一种简单的方式来添加缓存功能到Spring应用。 以下是步骤: 1. 添加依赖:首先在你的`pom.xml`文件中添加Caffeine的依赖: ```xml <dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>caffeine</artifactId> <version>2.9.4</version> </dependency> ``` 2. 配置Caffeine Cache:在Spring Boot中,你可以通过配置类(如`application.properties`或`application.yml`)设置Caffeine缓存的属性,比如过期时间、最大容量等: ```properties spring.cache.type=caffeine spring.cache.caffeine.expireAfterWrite=5m // 缓存数据默认超时时间为5分钟 spring.cache.caffeine.maxSize=1000 // 设置最大缓存条目数 ``` 3. 创建缓存注解:在需要缓存的方法上使用`@Cacheable`注解,表示当这个方法的结果不在缓存中时,才会去计算并存储结果: ```java @GetMapping("/cacheExample") @Cacheable(value = "exampleCache", key = "#id") // 缓存名称和生成键的方式 public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User not found")); } ``` 4. 自定义缓存管理器:如果你想要更精细地控制缓存策略,可以创建自定义的`CaffeineCacheManager`或实现`CacheManager`接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值