Преобразование Ehcache CacheManager (v 3.x) в Spring CacheManager без настройки XML

Я пытаюсь использовать диспетчер Ehcache в своем приложении. Я хотел бы настроить его без конфигурации xml. У меня есть следующие зависимости:

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.6.0</version>
</dependency>
<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.1.1.RELEASE</version>
</dependency>

У меня есть такой компонент CacheManager:

@Bean
public org.springframework.cache.CacheManager cacheManager() {
    org.ehcache.CacheManager mainPageCache = CacheManagerBuilder
            .newCacheManagerBuilder()
            .withCache("mainPageCache", CacheConfigurationBuilder
                    .newCacheConfigurationBuilder(
                            Pageable.class,
                            Collection.class,
                            ResourcePoolsBuilder.heap(10))
                    .withExpiry(ExpiryPolicyBuilder
                            .timeToLiveExpiration(Duration
                                    .of(10, ChronoUnit.SECONDS))))
            .build(true);
    // ...
}

Можно ли преобразовать Ehcache CacheManager в Spring CacheManager? Я думаю, что должно быть что-то вроде: return new JCacheCacheManager(/*some code*/);


person bovae    schedule 26.12.2018    source источник
comment
Созданный вами диспетчер кеша вообще не использует JCache, поэтому сначала вам нужно сделать это, см. ehcache.org/documentation/3.0/107.html   -  person Stephane Nicoll    schedule 26.12.2018


Ответы (1)


Вы не можете просто преобразовать ehcache CacheManager в Spring CacheManager.

Вы можете использовать org.ehcache.jsr107.EhcacheCachingProvider, чтобы получить javax.cache.CacheManager и передать его org.springframework.cache.jcache.JCacheCacheManager, который является реализацией org.springframework.cache.CacheManager для jcache (он же jsr107).

import java.util.HashMap;
import java.util.Map;

import javax.cache.CacheManager;
import javax.cache.Caching;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.ResourcePools;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.core.config.DefaultConfiguration;
import org.ehcache.jsr107.EhcacheCachingProvider;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {


    @Bean
    public JCacheCacheManager jCacheCacheManager() {
        JCacheCacheManager jCacheManager = new JCacheCacheManager(cacheManager());
        return jCacheManager;
    }

    @Bean(destroyMethod = "close")
    public CacheManager cacheManager() {

        ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder()
                .heap(2000, EntryUnit.ENTRIES)
                .offheap(100, MemoryUnit.MB)
                .build();


        CacheConfiguration<Object,Object> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(
                Object.class,
                Object.class,
                resourcePools).
                build();

        Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
        caches.put("myCache", cacheConfiguration);

        EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
        org.ehcache.config.Configuration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader());

        return  provider.getCacheManager(provider.getDefaultURI(), (org.ehcache.config.Configuration) configuration);
    }

}

Если вы используете spring-boot, он должен автоматически настроить JCacheCacheManager для вас. Затем вы можете использовать JCacheManagerCustomizer для настройки кеша.

person pcoates    schedule 26.12.2018