
前言
在平時(shí)做項(xiàng)目都要用到緩存,方便臨時(shí)存儲(chǔ)一些數(shù)據(jù),加快訪問(wèn)速度。如果項(xiàng)目比較小,搭建redis服務(wù),后期在維護(hù)上比較麻煩。今天分享一個(gè)SpringBoot集成Ehcache實(shí)現(xiàn)緩存的教程,適合中小項(xiàng)目中使用。
準(zhǔn)備工作
1、maven中導(dǎo)入依賴(lài)
<!--開(kāi)啟Springboot cache 緩存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 緩存 -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.1</version>
</dependency>
2、啟動(dòng)類(lèi)上增加緩存注解
@MapperScan("com.zhangls.ehcache.dao.**")
@SpringBootApplication
@EnableCaching
public class EhcacheApplication {
public static void main(String[] args) {
SpringApplication.run(EhcacheApplication.class, args);
}
}
3、配置Ehcache
在resources下增加ehcache.xml文件,配置如下:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="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.0.xsd
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
<service>
<!--開(kāi)啟service注解-->
<jsr107:defaults enable-statistics="true"/>
</service>
<!-- user 為該緩存名稱(chēng) 對(duì)應(yīng)@Cacheable的屬性cacheNames-->
<cache alias="UserCache">
<!-- 指定緩存 key 類(lèi)型,對(duì)應(yīng)@Cacheable的屬性key -->
<key-type>java.lang.String</key-type>
<!-- 配置value類(lèi)型 -->
<value-type>com.zhangls.ehcache.entity.User</value-type>
<expiry>
<!-- 緩存 ttl,單位為分鐘,現(xiàn)在設(shè)置的是1分鐘 -->
<ttl unit="minutes">1</ttl>
</expiry>
<resources>
<!-- 分配資源大小 -->
<heap unit="entries">2000</heap>
<offheap unit="MB">100</offheap>
</resources>
</cache>
<!--這里可以配置N個(gè) 。。。。 不同的cache 根據(jù)業(yè)務(wù)情況配置-->
</config>
4、application.yml中配置
spring:
cache:
jcache:
config: classpath:ehcache.xml
注意事項(xiàng)
1.Ehcache 會(huì)在一定的規(guī)則下會(huì)序列化后存儲(chǔ)到硬盤(pán)上,因此緩存對(duì)象必須支持序列化。
public class User implements Serializable{}
2.Spring定義了緩存接口Cache和管理緩存控制器 CacheManager,路徑為
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
使用方法--手動(dòng)管理方式
@Autowired
private CacheManager cacheManager;
@GetMapping("/addCache")
public String addCache() {
User user = new User();
user.setUsername("九天銀河聊編程");
user.setAge(34);
Cache cache = cacheManager.getCache("UserCache");
cache.put("user", user);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
return sdf.format(now) + ": " + "保存成功";
}
@GetMapping("/getCache")
public String getCache() {
Cache cache = cacheManager.getCache("UserCache");
Cache.ValueWrapper res = cache.get("user");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
if (null != res) {
User user = (User) res.get();//這里獲取 ehcache.xml 中 <cache> value-type 定義的類(lèi)型,可以直接強(qiáng)轉(zhuǎn)。
return sdf.format(now) + ": " + "姓名:" + user.getUsername() + ",年齡:" + user.getAge();
}
return sdf.format(now) + ": " + "沒(méi)有找到緩存!";
}
運(yùn)行結(jié)果
執(zhí)行:127.0.0.1:8080/ehcache/addCache。

執(zhí)行:127.0.0.1:8080/ehcache/getCache。

1分鐘后執(zhí)行:127.0.0.1:8080/ehcache/getCache,緩存失效。

使用方法--@Cacheable 注解方式
service代碼:
@Service
public class ImPersonServiceImpl implements ImPersonService{
@Resource
private PersonMapper personMapper;
@Override
@Cacheable(cacheNames = "PersonCache", key = "#personId")
public ImPerson selectByPrimaryKey(String personId) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
System.out.println(sdf.format(now) + ": 未命中緩存,請(qǐng)求數(shù)據(jù)庫(kù)");
return personMapper.selectByPrimaryKey(personId);
}
}
controller代碼:
@GetMapping("/getCachePerson")
public ImPerson getCachePerson() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = new Date();
System.out.println(sdf.format(start) + ":執(zhí)行開(kāi)始------");
ImPerson person = imPersonService.selectByPrimaryKey("1");
Date end = new Date();
System.out.println(sdf.format(end) + ":執(zhí)行結(jié)束------");
return person;
}
執(zhí)行兩次:127.0.0.1:8080/ehcache/getCachePerson。

控制臺(tái)只打印一次SQL信息,說(shuō)明第二次請(qǐng)求從緩存中獲取。
@Cacheable屬性說(shuō)明
- cacheNames/value :用來(lái)指定緩存組件的名字。
- key :緩存數(shù)據(jù)時(shí)使用的 key,可以用它來(lái)指定。默認(rèn)是使用方法參數(shù)的值。(這個(gè) key 你可以使用 spEL 表達(dá)式來(lái)編寫(xiě))。
- keyGenerator :key 的生成器。 key 和 keyGenerator 二選一使用。
- cacheManager :可以用來(lái)指定緩存管理器。從哪個(gè)緩存管理器里面獲取緩存。
- condition :可以用來(lái)指定符合條件的情況下才緩存,如下表示id>1的進(jìn)行緩存。
@Cacheable(cacheNames = "PersonCache", condition = "#id > 1")
- unless :否定緩存。當(dāng) unless 指定的條件為 true ,方法的返回值就不會(huì)被緩存。當(dāng)然你也可以獲取到結(jié)果進(jìn)行判斷。(通過(guò) #result 獲取方法結(jié)果)。
- sync :是否使用異步模式。
踩坑說(shuō)明
Spring 緩存注解是基于Spring AOP切面,必須走代理才能生效。同類(lèi)調(diào)用或者子類(lèi)調(diào)用父類(lèi)帶有緩存注解的方法時(shí)屬于內(nèi)部調(diào)用,沒(méi)有走代理,所以注解不會(huì)生效。所以在使用@Cacheable時(shí),一定要放在在service的實(shí)現(xiàn)類(lèi)中進(jìn)行調(diào)用。