yh yang
yh yang

Reputation: 11

spring boot guavaCacheManager cacheName-cache

This is the spring boot source code:

/**
 * 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();
    }
}

all the name of cache only one cache How do I create two different caches???

Upvotes: 1

Views: 1530

Answers (2)

Utsav Chokshi
Utsav Chokshi

Reputation: 1395

You can create multiple GuavaCache with different expiry time in spring like this :

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;
    }
}

You can access these cache by simply annotating a method with Cacheable annotation and providing cache name as value :

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

Upvotes: 1

Strelok
Strelok

Reputation: 51421

Not sure what the problem is exactly for you, but you create caches using the getCache(String) method. You can create as many as you want.

Upvotes: 0

Related Questions