面对番石榴缓存的问题

时间:2017-07-07 15:33:50

标签: java spring caching spring-boot google-guava-cache

我使用Google Guava Cache + Spring缓存抽象来缓存。 我尝试使用Guava的加载缓存接口。

我知道Spring提供了对Guava Cache的支持,但我想知道我是否可以使用spring的可缓存注释以及Loading Cache?

基本上我想将业务层与Cache分开。

请帮助。感谢。

2 个答案:

答案 0 :(得分:1)

  1. 不推荐使用番石榴缓存。如果你有现有代码,那将是另一回事,但对于新代码,请使用Caffeine

  2. 在要为其缓存返回值的方法上放置@Cacheable("myCacheName")

  3. 如果使用Spring Boot,则在您的应用程序类上放置@EnableCaching,否则在某些@Configuration类上放置。

  4. 如果使用Spring Boot,请在application.properties中设置规范,如下所示:spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=5m。如果不使用Boot,请在与上面#3相同的类中使用@PropertySources注释。

  5. org.springframework.boot:spring-boot-starter-cachecom.github.ben-manes.caffeine:caffeine添加到您的构建文件中。如果不使用Boot,则需要以不同方式设置依赖关系。

  6. 你已经完成了。

答案 1 :(得分:0)

所以你想要黄油和果酱。好的。我将帮助您使用加载缓存以及保持缓存逻辑分离。

假设您有一个服务类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);
    }
}

在你的bean配置中:

@Bean
public SampleService sampleService() {
    return new SampleServiceCache(expiry, maxSize);
}

要删除缓存的那一天,您必须做两件事:
1.删​​除缓存类 2.更改bean配置以返回实际的实现对象,而不是缓存实现对象。

P.S。您可以为不同的行为定义多个加载缓存,例如用户检索,文章检索等。

相关问题