本地缓存ehcache使用

190 阅读2分钟

「这是我参与2022首次更文挑战的第25天,活动详情查看:2022首次更文挑战

1、前言

​ 有这样一种情况,有时计算一些数据时,我们会将频繁的公共数据放入成员变量中,供其他方法调用,避免重复计算。刚开始,我是把这些数据放入到ThreadLocal里,后面了解到本地缓存组件ehcache,可以更方便的管理缓存数据,读取效率高,可以设置过期时间、 清除策略等。(PS:ehcache等这些本地缓存组件,只适合少量数据使用,如果是百千万级以上的数据,还是放到redis中。另外,由于其数据是放在本地,也就是堆内存中,所以在分布式的环境下,是不适用的。)下面就为大家介绍下,如何在项目中使用。

2、引入ehcache

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<!-- ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.9.2</version>
</dependency>

创建ehcache配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    
     <!-- 设置磁盘缓存位置 -->
     <diskStore path="test/ehcache"/>
    
     <!-- 默认的缓存参数 -->
	 <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" />
	
    <!-- 自定义的缓存配置 -->
    <cache 
    	name="test"
        maxEntriesLocalHeap="2000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        statistics="true">
    </cache>
</ehcache>

3、测试代码

下面就是最基本的使用,@CacheConfig指定了对应的缓存名称,@CachePut注解表示会缓存方法的执行结果,同时还会执行该方法,所以在更新时使用。@CacheEvict注解修饰的方法会删除缓存数据。@Cacheable注解作用为第一次执行方法时,会缓存其结果,这样第二次执行时,便会直接返回结果。

@CacheConfig(cacheNames = "test")
public interface TestEhCacheService {
	@CachePut(key = "#id")
	Person update(Person person);

	@CacheEvict(key = "#id")
	void deletePersonById(String id);
	
	@Cacheable(key = "#id")
	Person queryPersonById(String id);
}

上面只是基础使用,如果我们的增删改查,想要加限制条件怎么办,可以通过配置condition来实现。

//将年龄小于35的用户数据保存到缓存中
@Cacheable(condition="#age < 35")
public Person queryPersonById(String id) {
    //do something...
} 

好了、本期就先介绍到这里,有什么需要交流的,大家可以随时私信我。😊