spring boot guavaCacheManager cacheName-cache

时间:2017-02-15 05:15:46

标签: spring-boot

这是春季启动源代码:

{{1}}

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

2 个答案:

答案 0 :(得分:0)

不确定问题究竟是什么,但您使用getCache(String)方法创建缓存。您可以根据需要创建任意数量的内容。

答案 1 :(得分:0)

您可以在春季用不同的expiry time创建多个GuavaCache:

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来访问这些缓存:

@Cacheable(value = CacheConfiguration.CACHE1)
int getAge(Person person){
}