All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.eworkcloud.caffeine.CaffeineConfiguration Maven / Gradle / Ivy

There is a newer version: 2.5.8
Show newest version
package com.eworkcloud.caffeine;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
@EnableConfigurationProperties(CaffeineProperties.class)
public class CaffeineConfiguration {

    @Resource
    private CaffeineProperties caffeineProperties;

    @Bean
    public CaffeineCacheManager caffeineCacheManager() {
        Caffeine cacheBuilder = Caffeine.newBuilder();
        if (caffeineProperties.getMaximumSize() > 0) {
            cacheBuilder.maximumSize(caffeineProperties.getMaximumSize());
        }
        if (caffeineProperties.getExpireAfterAccess() > 0) {
            cacheBuilder.expireAfterAccess(caffeineProperties.getExpireAfterAccess(), TimeUnit.SECONDS);
        }
        if (caffeineProperties.getExpireAfterWrite() > 0) {
            cacheBuilder.expireAfterWrite(caffeineProperties.getExpireAfterWrite(), TimeUnit.SECONDS);
        }
        if (caffeineProperties.getRefreshAfterWrite() > 0) {
            cacheBuilder.refreshAfterWrite(caffeineProperties.getRefreshAfterWrite(), TimeUnit.SECONDS);
        }
        if (caffeineProperties.getInitialCapacity() > 0) {
            cacheBuilder.initialCapacity(caffeineProperties.getInitialCapacity());
        }

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(cacheBuilder);
        return caffeineCacheManager;
    }

    @Bean
    public CaffeineCacheTemplate caffeineCacheTemplate(CaffeineCacheManager caffeineCacheManager) {
        return new CaffeineCacheTemplate(caffeineCacheManager);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy