如何在没有xml的情况下配置Ehcache 3 +spring boot + java配置?

2022-09-03 01:32:25

我使用.这是我的配置:Ehcache 2 + spring boot

@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
    cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
    cmfb.setShared(true);
    return cmfb;
}

ehcache.xml - in resources.

现在我想使用Java配置而不是xml,但我还没有找到任何例子。我的问题:Ehcache 3 + spring boot

1)为什么几乎所有的例子都是基于xml的?这怎么能比java配置更好呢

2) 如何在不使用 xml 的情况下在 spring boot 中使用 java 配置 Ehcache 3


答案 1

下面是用于创建 Ehcache 管理器 bean 的等效 java 配置。

应用程序配置.java

@Configuration
@EnableCaching
public class ApplicationConfig {

    @Bean
    public CacheManager ehCacheManager() {
        CachingProvider provider = Caching.getCachingProvider();
        CacheManager cacheManager = provider.getCacheManager();

        CacheConfigurationBuilder<String, String> configuration =
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                        String.class,
                        String.class,
                     ResourcePoolsBuilder
                             .newResourcePoolsBuilder().offheap(1, MemoryUnit.MB))
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20)));

        javax.cache.configuration.Configuration<String, String> stringDoubleConfiguration = 
Eh107Configuration.fromEhcacheCacheConfiguration(configuration);

            cacheManager.createCache("users", stringDoubleConfiguration);
            return cacheManager;

    }

}

服务简介.java

@Service
public class ServiceImpl {

    @Cacheable(cacheNames = {"users"})
    public String getThis(String id) {
        System.out.println("Method called............");
        return "Value "+ id;
    }
}

啪.xml

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>

答案 2

有很多例子。我个人是Java配置的粉丝。

以下是主要的官方示例:


推荐