王萍
摘要:從本質(zhì)上看,EhCache是一個(gè)緩存管理器,不僅可以和Hibernate配合實(shí)現(xiàn)緩存,也可以和其他框架比如spring boot結(jié)合,作為一個(gè)緩存管理器,該文這里舉一個(gè)例子,來論述SpringBoot項(xiàng)目中EhCache緩存技術(shù)的實(shí)現(xiàn)過程,以“spring boot + mybatis + EhCache”實(shí)現(xiàn)本地緩存為例,探討了SpringBoot項(xiàng)目中EhCache緩存技術(shù)的實(shí)現(xiàn)。
關(guān)鍵詞:SpringBoot項(xiàng)目;EhCache;緩存技術(shù)
中圖分類號(hào):TP311? 文獻(xiàn)標(biāo)識(shí)碼:A
文章編號(hào):1009-3044(2021)29-0079-03
1概述
1.1 SpringBoot
SpringBoot是由Pivotal 團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡化新 Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,SpringBoot在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。
簡而言之,SpringBoot是當(dāng)前 web 開發(fā)主流,其簡化了 Spring 的配置讓開發(fā)者能夠更容易上手Web項(xiàng)目的開發(fā)。由于Spring 的發(fā)展、微服務(wù)的發(fā)展使得SpringBoot越來越流行,已經(jīng)成為JavaWeb開發(fā)的主流框架。
1.2 Spring Boot的緩存機(jī)制
SpringBoot高速緩存抽象不提供實(shí)際存儲(chǔ),且依賴于由org. springframework.cache.Cache和org.springframework.cache.Cache? Manager接口實(shí)現(xiàn)的抽象。 Spring Boot根據(jù)自動(dòng)配置實(shí)現(xiàn)合適的CacheManager,只要緩存支持通過@EnableCaching 注釋啟用即可。
1.3 EhCache
EhCache是一個(gè)開源的基于標(biāo)準(zhǔn)的緩存,是一個(gè)純Java 的在進(jìn)程中的緩存,可提高性能,減輕數(shù)據(jù)庫負(fù)載并簡化可伸縮性。它是使用最廣泛的基于Java 的高速緩存,功能全面,并且與其他流行的庫和框架集成在一起。EhCache從進(jìn)程內(nèi)緩存擴(kuò)展到混合進(jìn)程內(nèi)/進(jìn)程外部署與TB級(jí)緩存。EhCache是一個(gè)快速的、輕量級(jí)的、易于使用的、進(jìn)程內(nèi)的緩存。它支持read-on?ly和 read/write 緩存,內(nèi)存和磁盤緩存。是一個(gè)非常輕量級(jí)的緩存實(shí)現(xiàn),并支持集群。
現(xiàn)在的EhCache已經(jīng)更新到了3.9版本,版本3加入一些新的功能,包括:1)改進(jìn)了API,可以利用Java泛型并簡化緩存交互;2)與javax.cache API(JSR-107)完全兼容;3)Offheap存儲(chǔ)功能,包括僅堆外高速緩存;4)Spring Caching 和Hibernate集成得益于javax.cache支持。
1.4 Springboot整合EhCache的步驟
主要是:添加 pom 文件 maven 依賴——配置 ehcache.xml ——開啟緩存支持——在項(xiàng)目中使用。
2方法
下面這個(gè)例子是一個(gè)springboot工程項(xiàng)目,集成了mybatis來進(jìn)行數(shù)據(jù)庫的訪問,只是一個(gè)簡單的數(shù)據(jù)庫表操作,在具體的方法上添加了相應(yīng)的注解,從而實(shí)現(xiàn)了本地緩存。沒有用到EhCache集群和分布式,只是將信息緩存到內(nèi)存中,從而降低數(shù)據(jù)庫之間的訪問,提高數(shù)據(jù)的訪問速度。
核心的代碼主要如下:
1)SpringCacheApplication啟動(dòng)類
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;
/**
*數(shù)據(jù)庫集成Mybatis、EhCache框架采用 Mapper 訪問數(shù)據(jù)庫。
*/
@EnableDiscoveryClient
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {
public static void main(String[] args){
SpringApplication. run(SpringCacheApplication. class,
args);
System.out.println("MysqlMybatisMapperEhCache數(shù)據(jù)庫微服務(wù)已啟動(dòng).");
}
}
如果想用EhCache緩存,在啟動(dòng)類上一定要加上@Enable? Caching注解,否則緩存會(huì)不起作用。
2)UserServiceImpl實(shí)現(xiàn)類
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("查找的數(shù)據(jù)不存在!");
return result;
}
result.setData(list);
} catch (Exception e){
result.setRetCode(Result.RECODE_ERROR);
result.setErrMsg("方法執(zhí)行出錯(cuò)了!");
logger.error("方法執(zhí)行出錯(cuò)了!", e);
throw new RuntimeException(e);
}
return result;
}
}
3結(jié)論
通過以上的論述,可以看出:1)Springboot整合Encache實(shí)現(xiàn)數(shù)據(jù)緩存時(shí),可以通過注入CacheManager實(shí)現(xiàn)緩存內(nèi)容的查詢和緩存清空;2)可以使用 @Cacheable、@CachePut 和@CacheEvict 實(shí)現(xiàn)緩存和緩存清空;3)清空緩存有兩種方式,方式一通過使用cache.clear(),方式二使用@CacheEvict 注解在調(diào)用指定方法時(shí)清空緩存。
EhCache是一個(gè)非常輕量級(jí)的緩存實(shí)現(xiàn)且支持集群,同時(shí)也是hibernate 默認(rèn)的緩存provider。以上本文只是EhCache對(duì)頁面緩存的支持,EhCache的功能遠(yuǎn)不止如此,當(dāng)然要使用好緩存,需對(duì)JEE 中緩存的原理、使用范圍、適用場景等都有比較深刻的理解,這樣才能用好緩存、用對(duì)緩存。
參考文獻(xiàn):
[1]王松.SPRING BOOT+VUE全棧開發(fā)實(shí)戰(zhàn)[M].北京:清華大學(xué)出版社,2019.
[2]陳韶健.深入實(shí)踐SpringBoot[M].北京:機(jī)械工業(yè)出版社,2016.
[3]彭志勇.基于Spring Boot技術(shù)的天津法院報(bào)表分析系統(tǒng)的設(shè)計(jì)與實(shí)現(xiàn)[D].南京:南京大學(xué),2018.
[4]寧方美,賀雪梅,牟晉娟.SpringBoot集成Redis緩存技術(shù)在企業(yè)一卡通系統(tǒng)中的應(yīng)用[J].電子技術(shù)與軟件工程,2019(24):133-134.
[5]楊家煒. 基于 Spring Boot 的 web 設(shè)計(jì)與實(shí)現(xiàn)[J].輕工科技, 2016,32(7):86-89.
【通聯(lián)編輯:張薇】