王萍
摘要:從本質上看,EhCache是一個緩存管理器,不僅可以和Hibernate配合實現緩存,也可以和其他框架比如spring boot結合,作為一個緩存管理器,該文這里舉一個例子,來論述SpringBoot項目中EhCache緩存技術的實現過程,以“spring boot + mybatis + EhCache”實現本地緩存為例,探討了SpringBoot項目中EhCache緩存技術的實現。
關鍵詞:SpringBoot項目;EhCache;緩存技術
中圖分類號:TP311? 文獻標識碼:A
文章編號:1009-3044(2021)29-0079-03
1概述
1.1 SpringBoot
SpringBoot是由Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,SpringBoot在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。
簡而言之,SpringBoot是當前 web 開發主流,其簡化了 Spring 的配置讓開發者能夠更容易上手Web項目的開發。由于Spring 的發展、微服務的發展使得SpringBoot越來越流行,已經成為JavaWeb開發的主流框架。
1.2 Spring Boot的緩存機制
SpringBoot高速緩存抽象不提供實際存儲,且依賴于由org. springframework.cache.Cache和org.springframework.cache.Cache? Manager接口實現的抽象。 Spring Boot根據自動配置實現合適的CacheManager,只要緩存支持通過@EnableCaching 注釋啟用即可。
1.3 EhCache
EhCache是一個開源的基于標準的緩存,是一個純Java 的在進程中的緩存,可提高性能,減輕數據庫負載并簡化可伸縮性。它是使用最廣泛的基于Java 的高速緩存,功能全面,并且與其他流行的庫和框架集成在一起。EhCache從進程內緩存擴展到混合進程內/進程外部署與TB級緩存。EhCache是一個快速的、輕量級的、易于使用的、進程內的緩存。它支持read-on?ly和 read/write 緩存,內存和磁盤緩存。是一個非常輕量級的緩存實現,并支持集群。
現在的EhCache已經更新到了3.9版本,版本3加入一些新的功能,包括:1)改進了API,可以利用Java泛型并簡化緩存交互;2)與javax.cache API(JSR-107)完全兼容;3)Offheap存儲功能,包括僅堆外高速緩存;4)Spring Caching 和Hibernate集成得益于javax.cache支持。
1.4 Springboot整合EhCache的步驟
主要是:添加 pom 文件 maven 依賴——配置 ehcache.xml ——開啟緩存支持——在項目中使用。
2方法
下面這個例子是一個springboot工程項目,集成了mybatis來進行數據庫的訪問,只是一個簡單的數據庫表操作,在具體的方法上添加了相應的注解,從而實現了本地緩存。沒有用到EhCache集群和分布式,只是將信息緩存到內存中,從而降低數據庫之間的訪問,提高數據的訪問速度。
核心的代碼主要如下:
1)SpringCacheApplication啟動類
package com.example.ehcache;
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication;
import org. springframework. boot. autoconfigure. EnableAuto? Configuration;
import org.springframework.boot.autoconfigure.SpringBootAp? plication;
import org. springframework. boot. autoconfigure. jdbc. Data?SourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDis?coveryClient;
import org.springframework.cloud.config.server.EnableConfig? Server;
/**
*數據庫集成Mybatis、EhCache框架采用 Mapper 訪問數據庫。
*/
@EnableDiscoveryClient
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {
public static void main(String[] args){
SpringApplication. run(SpringCacheApplication. class,
args);
System.out.println("MysqlMybatisMapperEhCache數據庫微服務已啟動.");
}
}
如果想用EhCache緩存,在啟動類上一定要加上@Enable? Caching注解,否則緩存會不起作用。
2)UserServiceImpl實現類
package com.example.ehcache.service.impl;??? import com.github.pagehelper.util.StringUtil;??? import com.example.Ehcache.common.model.User; import com.example.ehcache.common.util.Result;
import com.example.ehcache.provider.dao.UserDao;??? import com.example.ehcache.provider.service.UserService; import com.mysql.jdbc.StringUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut;? import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service;
import org. springframework. transaction. annotation. Transac?tional;
import java.util.List;
@CacheConfig(cacheNames ="UserCache")
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory. getLogger(this. get?Class());
private static final String CACHE_KEY ="'user'";
private static final String CACHE_NAME_B ="user- cache";
@Autowired
private UserDaouserDao;
@CachePut(value =? CACHE_NAME_B,? key =
CACHE_KEY)
@Override
public int insert(User user){
return userDao.insert(user);
}
@CacheEvict(value = CACHE_NAME_B, key ="'user_'+ #id")
@Override
public int deleteByPrimaryKey(String id){
Result result = new Result();
return userDao.deleteByPrimaryKey(id);
}
@CachePut(value = CACHE_NAME_B, key ="'user_'+#us? er.id")
@Traditional
@Override
public User updateByPrimaryKey(User user){
if(userDao.updateByPrimaryKey(user)>0){
user=userDao.selectByPrimaryKey(user.getId());
return user;
}else{
return null;
}
}
@Cacheable(value = CACHE_NAME_B, key ="'user_'+
#id")
@Override
public User selectByPrimaryKey(String id){
return userDao.selectByPrimaryKey(id);
}
@Cacheable
@Override
public List<User>selectAllUser(){
return userDao.selectAllUser();
}
@Cacheable(value = CACHE_NAME_B, key ="#userId+'_'+#userName")
@Override
public Result selectUserByAcount(Integer userId, String userName){
Result result = new Result();
try {
List<User> list = userDao.selectUserByAcount(userId, userName);
if (list.size()==0 || list.isEmpty()){
result.setRetCode(Result.RECODE_ERROR);
result.setErrMsg("查找的數據不存在!");
return result;
}
result.setData(list);
} catch (Exception e){
result.setRetCode(Result.RECODE_ERROR);
result.setErrMsg("方法執行出錯了!");
logger.error("方法執行出錯了!", e);
throw new RuntimeException(e);
}
return result;
}
}
3結論
通過以上的論述,可以看出:1)Springboot整合Encache實現數據緩存時,可以通過注入CacheManager實現緩存內容的查詢和緩存清空;2)可以使用 @Cacheable、@CachePut 和@CacheEvict 實現緩存和緩存清空;3)清空緩存有兩種方式,方式一通過使用cache.clear(),方式二使用@CacheEvict 注解在調用指定方法時清空緩存。
EhCache是一個非常輕量級的緩存實現且支持集群,同時也是hibernate 默認的緩存provider。以上本文只是EhCache對頁面緩存的支持,EhCache的功能遠不止如此,當然要使用好緩存,需對JEE 中緩存的原理、使用范圍、適用場景等都有比較深刻的理解,這樣才能用好緩存、用對緩存。
參考文獻:
[1]王松.SPRING BOOT+VUE全棧開發實戰[M].北京:清華大學出版社,2019.
[2]陳韶健.深入實踐SpringBoot[M].北京:機械工業出版社,2016.
[3]彭志勇.基于Spring Boot技術的天津法院報表分析系統的設計與實現[D].南京:南京大學,2018.
[4]寧方美,賀雪梅,牟晉娟.SpringBoot集成Redis緩存技術在企業一卡通系統中的應用[J].電子技術與軟件工程,2019(24):133-134.
[5]楊家煒. 基于 Spring Boot 的 web 設計與實現[J].輕工科技, 2016,32(7):86-89.
【通聯編輯:張薇】