EhCache 是一个纯Java的进程内缓存框架,对于springboot项目来说如果只是简单使用选择该工具是最优解。由于项目中需要对某些数据进行缓存同时项目有一定限制不能使用spring cache,这里记录下如何基于Ehcache的xml来配置使用Ehcache。

首先项目中需要引入依赖(基于3.x版本):

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

编写Ehcache配置xml:

<?xml version="1.0" encoding="UTF-8"?>
<eh:config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns:eh='http://www.ehcache.org/v3'
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
        xsi:schemaLocation="
        http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.3.xsd
        http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.3.xsd">
    <!--缓存模板-->
    <eh:cache-template name="default">
        <eh:expiry>
            <eh:ttl unit="hours">2</eh:ttl>
        </eh:expiry>
        <eh:resources>
            <eh:heap>2000</eh:heap>
            <eh:offheap unit="MB">50</eh:offheap>
        </eh:resources>
    </eh:cache-template>

    <eh:cache alias="xxxxx" uses-template="default">
        <eh:key-type serializer="org.ehcache.impl.serialization.StringSerializer">java.lang.String</eh:key-type>
        <eh:value-type serializer="org.ehcache.impl.serialization.LongSerializer">java.lang.Long</eh:value-type>
    </eh:cache>
</eh:config>

SpringBoot配置类:

@Configuration
public class EhCacheConfig {
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * EhcacheManager
     *
     * @return
     * @throws IOException
     */
    @Bean
    public EhcacheManager ehcacheManager() throws IOException {
        URL url = resourceLoader.getResource("classpath:ehcache.xml").getURL();
        XmlConfiguration configuration = new XmlConfiguration(url);
        EhcacheManager manager = new EhcacheManager(configuration);
        manager.init();
        return manager;
    }

    /**
     * xxxCache
     *
     * @param manager
     * @return
     */
    @Bean("xxxxx")
    public Cache<String, Long> xxxCache(@Autowired EhcacheManager manager) {
        return manager.getCache("xxxxx", String.class, Long.class);
    }
}