Java 番石榴缓存面临的问题
我正在使用GoogleGuavaCache+SpringCache抽象来进行缓存。 我正试图利用Guava的加载缓存接口实现同样的功能 我知道Spring提供了对Guava缓存的支持,但我想知道是否可以在加载缓存的同时使用Spring的可缓存注释 基本上,我希望将业务层与缓存分开Java 番石榴缓存面临的问题,java,spring,caching,spring-boot,google-guava-cache,Java,Spring,Caching,Spring Boot,Google Guava Cache,我正在使用GoogleGuavaCache+SpringCache抽象来进行缓存。 我正试图利用Guava的加载缓存接口实现同样的功能 我知道Spring提供了对Guava缓存的支持,但我想知道是否可以在加载缓存的同时使用Spring的可缓存注释 基本上,我希望将业务层与缓存分开 请帮忙。谢谢。那么你想要黄油和果酱。可以我将帮助您使用加载缓存以及保持缓存逻辑分离 假设您有一个服务类SampleServiceImpl,它实现了SampleService接口 服务接口: public interfa
请帮忙。谢谢。那么你想要黄油和果酱。可以我将帮助您使用加载缓存以及保持缓存逻辑分离 假设您有一个服务类
SampleServiceImpl
,它实现了SampleService
接口
服务接口:
public interface SampleService {
User getUser(int id);
}
服务实施:
@Service
public class SampleServiceImpl implements SampleService {
public User getUser(int id) {
// fetch user from database
return user;
}
}
再创建一个类SampleServiceCache
public class SampleServiceCache extends ServiceCacheImpl {
@Autowired
public SampleServiceCache(int expiryTime, int maximumSize) {
loadingCache =
CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(expiryTime, TimeUnit.HOURS).build(
new CacheLoader<Integer, User>() {
@Override
public User load(@Nonnull Integer userId) {
return SampleServiceCache.super.getUser(userId);
}
});
}
@Override
public User getUser(int userId) {
return loadingCache.getUnchecked(userId);
}
}
在您想要删除缓存的那天,您必须做两件事:1.删除缓存类。
2.更改bean配置以返回实际的实现对象,而不是缓存实现对象 另外,您可以为不同的行为定义多个加载缓存,如用户检索、文章检索等
@Cacheable(“myCacheName”)
@EnableCaching
,否则在某些@Configuration
类上放置application.properties
中设置规范,如下所示:Spring.cache.caffee.spec=maximumSize=10000,expireAfterWrite=5m
。如果不使用Boot,请在与上面第3节相同的类上使用@PropertySources
注释org.springframework.boot:springbootstartercache
和com.github.ben manes.caffeine:caffeine
添加到构建文件中。如果不使用Boot,则需要以不同的方式设置依赖项完成了。这与Spring缓存抽象无关。如果使用@Cacheable,则无法解耦代码。因此,您将无法从加载缓存中获益。我认为您不知道解耦的含义。@cacheable以声明方式处理缓存。因此,无法在加载缓存时使用可缓存注释。如果您认为还有一个问题,您可以发布一个答案。如果您想在同一个类(AOP)中缓存调用,您必须使用aspectj,复杂的拼写来生成密钥,存储缓存名称(它们是编译时常量),这是在Spring中进行缓存的理想方式,但是加载缓存提供了额外的灵活性。有什么答案对你有帮助吗?若否,原因为何?
@Bean
public SampleService sampleService() {
return new SampleServiceCache(expiry, maxSize);
}