spring boot 2.1.4 hibernate 二级缓存 Caffeine实现
The Ehcache second-level cache provider for Hibernate is deprecated
當(dāng)我們使用hibernate-ehcache包(Ehcache 2)作為hibernate二級(jí)緩存時(shí),系統(tǒng)會(huì)提示警告說已經(jīng)過時(shí)了,那這時(shí)候找到spring boot推薦的新的二級(jí)緩存方案,現(xiàn)在推薦hibernate-jcache,可以與Ehcache 3或是其他實(shí)現(xiàn)了javax.cache.spi.CachingProvider的緩存自動(dòng)集成
jcache是一種緩存門面規(guī)范,并不包含具體緩存實(shí)現(xiàn),spring boot推薦與jcache搭配使用的是Hazelcast,Hazelcast實(shí)現(xiàn)了CachingProvider,可以直接作為hibernate二級(jí)緩存,Hazelcast實(shí)現(xiàn)下一篇再提供
hibernate二級(jí)緩存重構(gòu)之后,要自己實(shí)現(xiàn)也非常簡(jiǎn)單,只需要實(shí)現(xiàn)
org.hibernate.cache.spi.support.RegionFactoryTemplate
org.hibernate.cache.spi.support.DomainDataStorageAccess
這兩個(gè)類就可以了,引入caffeine包
<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId> </dependency>下面是DomainDataStorageAccess實(shí)現(xiàn),這個(gè)類就是緩存操作的實(shí)現(xiàn)
import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils; import org.hibernate.cache.spi.support.DomainDataStorageAccess; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine;import lombok.NonNull;public class CaffeineDataRegion implements DomainDataStorageAccess {protected final Logger log = LoggerFactory.getLogger(this.getClass());/*** Region regionName*/private final String regionName;private final Cache<Object, Object> cache;private final int expiryInSeconds; // secondsstatic final int DEFAULT_EXPIRY_IN_SECONDS = 1800;public CaffeineDataRegion(@NonNull String regionName) {this.regionName = StringUtils.replace(regionName, ".", ":") + ":";this.expiryInSeconds = DEFAULT_EXPIRY_IN_SECONDS;cache = Caffeine.newBuilder()// 設(shè)置cache中的數(shù)據(jù)在寫入之后的存活時(shí)間.expireAfterWrite(30, TimeUnit.MINUTES)// 構(gòu)建cache實(shí)例.build();log.debug("caffeiene region={}, expiryInSeconds={}", regionName, expiryInSeconds);}/*** confirm the specified key exists in current region** @param key* cache key* @return if cache key is exists in current region return true, else return* false*/@Overridepublic boolean contains(Object key) {try {log.debug("contains key={}", key);return cache.getIfPresent(key) != null;} catch (Exception ignored) {log.warn("Fail to exists key. key=" + key, ignored);return false;}}@Overridepublic Object getFromCache(Object key, SharedSessionContractImplementor session) {try {return cache.getIfPresent(key);} catch (Exception ignored) {log.warn("Fail to get cache item... key=" + key, ignored);return null;}}@Overridepublic void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) {try {cache.put(key, value);} catch (Exception ignored) {log.warn("Fail to put cache item... key=" + key, ignored);}}@Overridepublic void evictData() {try {cache.invalidateAll();} catch (Exception ignored) {log.warn("Fail to clear region... name=" + regionName, ignored);}}@Overridepublic void evictData(Object key) {try {cache.invalidate(key);} catch (Exception ignored) {log.warn("Fail to remove cache item... key=" + key, ignored);}}@Overridepublic void release() {} }下面是RegionFactoryTemplate實(shí)現(xiàn),這個(gè)類是緩存啟動(dòng)類
import java.util.Map;import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.cfg.spi.DomainDataRegionBuildingContext; import org.hibernate.cache.cfg.spi.DomainDataRegionConfig; import org.hibernate.cache.spi.support.DomainDataStorageAccess; import org.hibernate.cache.spi.support.RegionFactoryTemplate; import org.hibernate.cache.spi.support.StorageAccess; import org.hibernate.engine.spi.SessionFactoryImplementor;import com.bc.plugin.caffeine.hibernate.regions.CaffeineDataRegion;import lombok.extern.slf4j.Slf4j;@Slf4j public class CaffeineRegionFactory extends RegionFactoryTemplate {private static final long serialVersionUID = 1L;@Overrideprotected StorageAccess createQueryResultsRegionStorageAccess(String regionName,SessionFactoryImplementor sessionFactory) {return new CaffeineDataRegion(regionName);}@Overrideprotected StorageAccess createTimestampsRegionStorageAccess(String regionName,SessionFactoryImplementor sessionFactory) {return new CaffeineDataRegion(regionName);}@Overrideprotected DomainDataStorageAccess createDomainDataStorageAccess(DomainDataRegionConfig regionConfig,DomainDataRegionBuildingContext buildingContext) {return new CaffeineDataRegion(regionConfig.getRegionName());}@Overrideprotected void prepareForUse(SessionFactoryOptions settings, @SuppressWarnings("rawtypes") Map configValues) {log.debug("RegionFactory is starting... options={}, properties={}", settings, configValues);}@Overrideprotected void releaseFromUse() {} }?
然后配置spring.jpa.properties.hibernate.cache.region.factory_class=/*org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory? */
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory是hibernate-ehcache包中的實(shí)現(xiàn),
替換成我們CaffeineRegionFactory類的全路徑就可以了
引入caffeine包后,spring cache也會(huì)使用caffeine,springboot會(huì)自動(dòng)配置caffeine
轉(zhuǎn)載于:https://my.oschina.net/u/1428688/blog/3063953
總結(jié)
以上是生活随笔為你收集整理的spring boot 2.1.4 hibernate 二级缓存 Caffeine实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机一级考试考什么呢,计算机一级考试考
- 下一篇: 基于SSH的电子政务系统(附论文)