Java轻量级缓存Ehcache与SpringBoot整合

前言

业务需要将数据临时存储一下,但是想做一个搭建轻量级应用,不需要任何第三方中间件(考虑过MySQL、Redis等都比较麻烦)。
Java EhCache是一个轻量级内存缓存,也支持持久化,所以采用该种方式。

配置

引入依赖

<dependencies>
    <!-- spring boot 单元测试依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!-- SpringBoot 缓存 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- ehcache -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

启动类添加开启缓存注解

package com.terry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * ehcache demo
 * @author terry
 * @version 1.0
 * @date 2022/4/18 11:38
 */
@SpringBootApplication
@EnableCaching
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

ehcache.xml配置

<!-- ehcache配置 -->
<ehcache
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false">
    <!--缓存路径,用户目录下的base_ehcache目录-->
    <diskStore path="base_ehcache"/>

    <!--
    默认缓存
    可以设置文件名:user,同样的可以配置多个缓存
    maxElementsInMemory:内存中最多存储
    eternal:外部存储
    overflowToDisk:超出缓存到磁盘
    diskPersistent:磁盘持久化
    timeToLiveSeconds:缓存时间
    diskExpiryThreadIntervalSeconds:磁盘过期时间(秒为单位,0 为永久)
    -->
    <defaultCache
            maxElementsInMemory="20000"
            eternal="true"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="true"
            diskExpiryThreadIntervalSeconds="0"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

application.yml 配置


spring:
  # 缓存配置
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

实战

增删改查例子
package com.terry.ehcache.test;

import com.terry.App;
import lombok.extern.java.Log;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Map;

/**
 * ehcache 增删改查测试
 * @author terry
 * @version 1.0
 * @date 2022/4/25 23:01
 */
@SpringBootTest(classes = App.class)
@Log
public class TestEhCache {

    @Autowired
    private CacheManager cacheManager;

    @Test
    public Cache getCache(){
        String cacheName = "user";
        Cache user = cacheManager.getCache(cacheName);
        if (user == null) {
            cacheManager.addCache(cacheName);
            user = cacheManager.getCache(cacheName);
        }
        return user;
    }

    @Test
    public void addUser(){
        Cache cache = getCache();
        // 添加一个用户,key:user01,value:张三
        cache.put(new Element("user01", "张三"));
    }

    @Test
    public void getUser(){
        Cache cache = getCache();
        log.info(cache.get("user01").getObjectValue().toString());
    }

    @Test
    public void removeUser(){
        Cache cache = getCache();
        cache.remove("user01");
        // 获取所有的keys
        log.info(cache.getKeys().toString());
    }

    @Test
    public void getUserAll(){
        Cache cache = getCache();
        cache.put(new Element("user01", "张三"));
        cache.put(new Element("user02", "李四"));
        cache.put(new Element("user03", "王五"));
        cache.put(new Element("user04", "赵六"));
        // 获取所有的keys
        Map<Object, Element> all = cache.getAll(cache.getKeys());
        all.forEach((k, v) -> {
            log.info("key:" + k + ", value:" + v.getObjectValue().toString());
        });
    }
}
使用SpringBoot Cache注解
package com.terry.ehcache.service;

import lombok.Data;
import lombok.extern.java.Log;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务层
 * @author terry
 * @version 1.0
 * @date 2022/4/18 14:35
 */
@Service
@Log
public class UserService {

    @Cacheable(cacheNames = "user")
    public List<User> getUser(){
        log.info("添加进缓存");
        // 模拟数据库
        List<User> list = new ArrayList<>();
        list.add(new User("张三", 18));
        list.add(new User("李四", 18));
        return list;
    }

    @Data
    public static class User implements Serializable {
        private String name;
        private int age;
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}
封装工具类
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * ehcache 工具类
 * @version 1.0
 * @author terry
 * @date 2022/4/22
 */
@Slf4j
@Component
public class EhcacheService {
 

    @Autowired
    private CacheManager cacheManager;

    /**
     * 获得一个Cache,没有则创建一个。
     * @return
     */
    private Cache getCache(){
        return getCache(EhcacheEnum.CACHE_NAME);
    }

    /**
     * 获得一个Cache,没有则创建一个。
     * @param cacheName
     * @return
     */
    public Cache getCache(String cacheName){
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null){
            cacheManager.addCache(cacheName);
            cache = cacheManager.getCache(cacheName);
            cache.getCacheConfiguration().setEternal(true);
        }
        return cache;
    }

    /**
     * 放置缓存(带过期时间)
     * @param key
     * @param value
     * @param timeToLiveSeconds
     */
    public void setCacheElement(String key, Object value,int timeToLiveSeconds) {
        Element element = new Element(key, value);
        element.setEternal(false);
        element.setTimeToLive(timeToLiveSeconds);
        getCache().put(element);
    }

    /**
     * 放置缓存(带过期时间)
     * @param cacheName
     * @param key
     * @param value
     * @param timeToLiveSeconds
     */
    public void setCacheElement(String cacheName, String key, Object value,int timeToLiveSeconds) {
        Element element = new Element(key, value);
        element.setEternal(false);
        element.setTimeToLive(timeToLiveSeconds);
        getCache(cacheName).put(element);
    }

    /**
     * 放置缓存(永久)
     * @param key
     * @param value
     */
    public void setCacheElement(String key, Object value) {
        Element element = new Element(key, value);
        element.setEternal(false);
        getCache().put(element);
    }

    /**
     * 放置缓存(永久)
     * @param cacheName
     * @param key
     * @param value
     */
    public void setCacheElement(String cacheName, String key, Object value) {
        Element element = new Element(key, value);
        element.setEternal(false);
        getCache(cacheName).put(element);
    }

    /**
     * 设置过期时间
     * @param key
     * @param seconds
     * @return
     */
    public long expire(String key,int seconds) {
        Element element = getCache().get(key);
        element.setEternal(false);
        element.setTimeToLive(seconds);
        return 0;
    }

    /**
     * 设置过期时间
     * @param key
     * @param cacheName
     * @param seconds
     * @return
     */
    public long expire(String key,String cacheName, int seconds) {
        Element element = getCache(cacheName).get(key);
        element.setEternal(false);
        element.setTimeToLive(seconds);
        return 0;
    }

    /**
     * 获取缓存值
     * @param key
     * @return
     */
    public Object getCacheValue(String key) {
        Element element = getCache().get(key);
        if(element != null)
        {
            return element.getObjectValue();
        }
        return null;
    }

    /**
     * 获取缓存值
     * @param cacheName
     * @param key
     * @return
     */
    public Object getCacheValue(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        if(element != null)
        {
            return element.getObjectValue();
        }
        return null;
    }

    /**
     * 根据key删除缓存
     * @param cacheName
     * @return
     */
    public Map<Object, Element> getCacheAll(String cacheName) {
        Cache cache = getCache(cacheName);
        return cache.getAll(cache.getKeys());
    }

    /**
     * 根据key删除缓存
     * @param cacheName
     * @param key
     * @return
     */
    public Boolean removeCacheKey(String cacheName, String key) {
        return getCache(cacheName).remove(key);
    }
    /**
     * 获取缓存过期时间
     * @param key
     * @return
     */
    public int getCacheExpire(String key) {
        Element element = getCache().get(key);
        List keys = getCache().getKeys();
        if(element != null)
        {
            return element.getTimeToLive();
        }
        return 0;
    }
    /**
     * 获取缓存过期时间
     * @param cacheName
     * @param key
     * @return
     */
    public int getCacheExpire(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        if(element != null)
        {
            return element.getTimeToLive();
        }
        return 0;
    }
 
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,在项目中引入依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 然后,在 Spring Boot 启动类中添加 @EnableCaching 注解开启缓存功能: ```java @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 接下来,需要创建一个配置类,配置 Ehcache 作为缓存管理器: ```java @Configuration @EnableCaching public class EhcacheConfig { @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; } } ``` 接着,在项目的 classpath 下新建一个名为 ehcache.xml 的配置文件,并在其中定义一个缓存(cache),作为二级缓存: ```xml <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd" updateCheck="true" monitoring="autodetect"> <cache name="secondLevelCache" maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" diskSpoolBufferSizeMB="20" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache> ``` 最后,在需要使用二级缓存的实体类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

terrybg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值