最近碰到的问题需要使用全局缓存。项目中没有使用Redis,又是单体应用,又要实现缓存那种时效性(HashMap没有这种功能),后来找到了GuavaCache。Guava Cache是Google Guava库中的一个模块,提供了基于内存的本地缓存实现。以下是整合使用Guava Cache的具体步骤:
一、添加Maven依赖
<dependencies>
<!-- 其他依赖 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
</dependencies>
二、创建Cache实例
可以包装增强Cache实例再使用,或者直接创建一个全局的Cache实例使用。以下是对这两种情况的创建使用说明。
①在服务类中创建缓存实例,对缓存进行包装,再使用。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
@Service
public class MyService {
private final Cache<String, Object> myCache;
public MyService() {
this.myCache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES) // 设置缓存过期时间
.maximumSize(100) // 设置缓存最大容量
.build();
}
public Object getFromCache(String key) {
return myCache.getIfPresent(key);
}
public void putIntoCache(String key, Object value) {
myCache.put(key, value);
}
// 其他业务逻辑...
}
在上面的例子中,创建了一个Guava Cache实例,并设置了写入后10分钟过期和最大容量为100条记录的限制。
使用guava cache:
public TestService{
@Autowired
MyService myService;
public Object getData(String key) {
Object cachedData = myService.getFromCache(key);
if (cachedData != null) {
return cachedData;
}
// 如果缓存中没有数据,则从数据源获取并放入缓存
Object newData = fetchDataFromDataSource(key);
myService.putIntoCache(key, newData);
return newData;
}
private Object fetchDataFromDataSource(String key) {
// 模拟从数据源获取数据的过程
// ...
return new Object();
}
}
② 配置为SpringBean
这个也是常用的方式。适用于不需要包装增强的情况。配置为Spring管理的Bean,可以在配置类中创建一个Bean。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
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> myCache() {
return CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(100)
.build();
}
}
然后,在服务中,可以通过@Autowired
注解来注入这个Bean:
import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyTestService {
private final Cache<String, Object> myCache;
@Autowired
public MyTestService(Cache<String, Object> myCache) {
this.myCache = myCache;
}
// 使用myCache进行缓存操作...
}
这样,就可以在Spring Boot应用中轻松地使用Guava Cache来缓存数据了。根据应用需求调整缓存的过期时间和容量大小。
至此整合完成。