SpringBoot使用本地缓存——Caffeine
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class CachingService {
private final Cache<String, String> cache;
public CachingService() {
this.cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES) // 缓存写入后10分钟过期
.maximumSize(100) // 最大缓存数目
.build();
}
public void putInCache(String key, String value) {
cache.put(key, value);
}
public String getFromCache(String key) {
return cache.getIfPresent(key); // 如果缓存存在,返回缓存值,否则返回null
}
}
这段代码展示了如何在Spring Boot应用中使用Caffeine作为本地缓存。首先,我们创建了一个Cache实例,并设置了缓存的过期时间和最大容量。然后,我们提供了putInCache
方法将数据存入缓存,以及getFromCache
方法从缓存中获取数据。如果缓存中不存在数据,则返回null。这个例子简单易懂,并且展示了Caffeine的基本用法。
评论已关闭