业务需要将数据临时存储一下,但是想做一个搭建轻量级应用,不需要任何第三方中间件(考虑过MySQL、Redis等都比较麻烦)。
Java EhCache是一个轻量级内存缓存,也支持持久化,所以采用该种方式。
引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
<dependency>
<groupId>net.sf.ehcachegroupId>
<artifactId>ehcacheartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
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
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="base_ehcache"/>
<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;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)