spring boot中如何使用ehcache

小码农贱贱 发布于 2016/11/13 12:38
阅读 969
收藏 0

【Gopher China万字分享】华为云的Go语言云原生实战经验!>>>

请问各位大牛,如何在spring boot中配置和使用ehcache
加载中
1
夏天飘过的风
夏天飘过的风
可以看看 http://git.oschina.net/roncoocom/spring-boot-demo
求是科技
求是科技
正好用得上
0
canghailan
canghailan

pom.xml

<dependencies>
    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
</dependencies>

CachingConfiguration.java

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;

import javax.cache.annotation.CacheResult;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@EnableCaching
@Configuration
public class CachingConfiguration {
    public Set<String> getCacheNames() {
        try {
            Set<String> cacheNames = new HashSet<>();
            ClassPathScanningCandidateComponentProvider provider =
                    new ClassPathScanningCandidateComponentProvider(true);
            Set<BeanDefinition> components = provider.findCandidateComponents(
                    getClass().getPackage().getName().replace('.', '/'));
            for (BeanDefinition component : components) {
                for (Method method : Class.forName(component.getBeanClassName()).getMethods()) {
                    CacheResult cacheResult = method.getAnnotation(CacheResult.class);
                    if (cacheResult != null) {
                        cacheNames.add(cacheResult.cacheName());
                    }
                }
            }
            return cacheNames;
        } catch (Exception e) {
            return Collections.emptySet();
        }
    }

    public <K, V> MutableConfiguration<K, V> configuration() {
        return new MutableConfiguration<K, V>()
                .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1)))
                .setStoreByValue(false)
                .setStatisticsEnabled(true);
    }

    @Bean
    public JCacheManagerCustomizer jCacheManagerCustomizer() {
        return cacheManager -> {
            for (String cacheName : getCacheNames()) {
                cacheManager.createCache(cacheName, configuration());
            }
        };
    }
}



我用的是JCache注解



0
小码农贱贱
你好 可以加个好友 聊一下吗843156108
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部