首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >春季引导guavaCacheManager缓存名-缓存

春季引导guavaCacheManager缓存名-缓存
EN

Stack Overflow用户
提问于 2017-02-15 05:15:45
回答 1查看 1.3K关注 0票数 1

这是spring引导的源代码:

代码语言:javascript
复制
/**
 * Create a native Guava Cache instance for the specified cache name.
 * @param name the name of the cache
 * @return the native Guava Cache instance
 */
protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(String name) {
    if (this.cacheLoader != null) {
        return this.cacheBuilder.build(this.cacheLoader);
    }
    else {
        return this.cacheBuilder.build();
    }
}

缓存的所有名称只有一个缓存如何创建两个不同的缓存?

EN

回答 1

Stack Overflow用户

发布于 2018-11-23 18:32:57

您可以在春季使用不同的GuavaCache创建多个expiry time,如下所示:

代码语言:javascript
复制
import com.google.common.cache.CacheBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfiguration extends CachingConfigurerSupport {

    private static final int TIME_TO_LEAVE = 120;                //in minutes
    private static final int CACHE_SIZE = 100;

    public static final String CACHE1 = "cache1";
    public static final String CACHE2 = "cache2";

    @Bean
    @Override
    public CacheManager cacheManager() {
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();

        GuavaCache cache1 = new GuavaCache(CACHE1,
                CacheBuilder.newBuilder()
                        .expireAfterWrite(TIME_TO_LEAVE, TimeUnit.MINUTES)
                        .maximumSize(CACHE_SIZE)
                        .build());

        GuavaCache cache2 = new GuavaCache(CACHE2,
                CacheBuilder.newBuilder()
                        .expireAfterWrite(TIME_TO_LEAVE, TimeUnit.MINUTES)
                        .maximumSize(CACHE_SIZE)
                        .build());


        simpleCacheManager.setCaches(Arrays.asList(cache1, cache2));

        return simpleCacheManager;
    }
}

您可以访问这些缓存,只需用Cacheable注释注释一个方法,并以value的形式提供缓存名称:

代码语言:javascript
复制
@Cacheable(value = CacheConfiguration.CACHE1)
int getAge(Person person){
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42241211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档