日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

ehcache 缓存java对象_Ehcache 整合Spring 使用页面、对象缓存

發(fā)布時間:2023/12/15 javascript 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ehcache 缓存java对象_Ehcache 整合Spring 使用页面、对象缓存 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Ehcache在很多項目中都出現(xiàn)過,用法也比較簡單。一般的加些配置就可以了,而且Ehcache可以對頁面、對象、數(shù)據(jù)進行緩存,同時支持集群/分布式緩存。如果整合Spring、Hibernate也非常的簡單,Spring對Ehcache的支持也非常好。EHCache支持內(nèi)存和磁盤的緩存,支持LRU、LFU和FIFO多種淘汰算法,支持分布式的Cache,可以作為Hibernate的緩存插件。同時它也能提供基于Filter的Cache,該Filter可以緩存響應(yīng)的內(nèi)容并采用Gzip壓縮提高響應(yīng)速度。

Email:hoojo_@126.com

一、準備工作

如果你的系統(tǒng)中已經(jīng)成功加入Spring、Hibernate;那么你就可以進入下面Ehcache的準備工作。

1、? 下載jar包

2、? 需要添加如下jar包到lib目錄下

ehcache-core-2.5.2.jar

ehcache-web-2.0.4.jar 主要針對頁面緩存

3、? 當前工程的src目錄中加入配置文件

ehcache.xml

ehcache.xsd

這些配置文件在ehcache-core這個jar包中可以找到

二、Ehcache基本用法

CacheManager cacheManager = CacheManager.create();

// 或者

cacheManager = CacheManager.getInstance();

// 或者

cacheManager = CacheManager.create("/config/ehcache.xml");

// 或者

cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml");

cacheManager = CacheManager.newInstance("/config/ehcache.xml");

// .......

// 獲取ehcache配置文件中的一個cache

Cache sample = cacheManager.getCache("sample");

// 獲取頁面緩存

BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter"));

// 添加數(shù)據(jù)到緩存中

Element element = new Element("key", "val");

sample.put(element);

// 獲取緩存中的對象,注意添加到cache中對象要序列化 實現(xiàn)Serializable接口

Element result = sample.get("key");

// 刪除緩存

sample.remove("key");

sample.removeAll();

// 獲取緩存管理器中的緩存配置名稱

for (String cacheName : cacheManager.getCacheNames()) {

System.out.println(cacheName);

}

// 獲取所有的緩存對象

for (Object key : cache.getKeys()) {

System.out.println(key);

}

// 得到緩存中的對象數(shù)

cache.getSize();

// 得到緩存對象占用內(nèi)存的大小

cache.getMemoryStoreSize();

// 得到緩存讀取的命中次數(shù)

cache.getStatistics().getCacheHits();

// 得到緩存讀取的錯失次數(shù)

cache.getStatistics().getCacheMisses();

三、頁面緩存

頁面緩存主要用Filter過濾器對請求的url進行過濾,如果該url在緩存中出現(xiàn)。那么頁面數(shù)據(jù)就從緩存對象中獲取,并以gzip壓縮后返回。其速度是沒有壓縮緩存時速度的3-5倍,效率相當之高!其中頁面緩存的過濾器有CachingFilter,一般要擴展filter或是自定義Filter都繼承該CachingFilter。

CachingFilter功能可以對HTTP響應(yīng)的內(nèi)容進行緩存。這種方式緩存數(shù)據(jù)的粒度比較粗,例如緩存整張頁面。它的優(yōu)點是使用簡單、效率高,缺點是不夠靈活,可重用程度不高。

EHCache使用SimplePageCachingFilter類實現(xiàn)Filter緩存。該類繼承自CachingFilter,有默認產(chǎn)生cache key的calculateKey()方法,該方法使用HTTP請求的URI和查詢條件來組成key。也可以自己實現(xiàn)一個Filter,同樣繼承CachingFilter類,然后覆寫calculateKey()方法,生成自定義的key。

CachingFilter輸出的數(shù)據(jù)會根據(jù)瀏覽器發(fā)送的Accept-Encoding頭信息進行Gzip壓縮。

在使用Gzip壓縮時,需注意兩個問題:

1. Filter在進行Gzip壓縮時,采用系統(tǒng)默認編碼,對于使用GBK編碼的中文網(wǎng)頁來說,需要將操作系統(tǒng)的語言設(shè)置為:zh_CN.GBK,否則會出現(xiàn)亂碼的問題。

2. 默認情況下CachingFilter會根據(jù)瀏覽器發(fā)送的請求頭部所包含的Accept-Encoding參數(shù)值來判斷是否進行Gzip壓縮。雖然IE6/7瀏覽器是支持Gzip壓縮的,但是在發(fā)送請求的時候卻不帶該參數(shù)。為了對IE6/7也能進行Gzip壓縮,可以通過繼承CachingFilter,實現(xiàn)自己的Filter,然后在具體的實現(xiàn)中覆寫方法acceptsGzipEncoding。

具體實現(xiàn)參考:

protectedboolean acceptsGzipEncoding(HttpServletRequest request) {

boolean ie6 = headerContains(request,"User-Agent", "MSIE 6.0");

boolean ie7 = headerContains(request,"User-Agent", "MSIE 7.0");

return acceptsEncoding(request,"gzip") || ie6 || ie7;

}

在ehcache.xml中加入如下配置

maxElementsInMemory="10000"

eternal="false"

overflowToDisk="false"

timeToIdleSeconds="900"

timeToLiveSeconds="1800"

memoryStoreEvictionPolicy="LFU" />

具體代碼:

package com.hoo.ehcache.filter;

import java.util.Enumeration;

import javax.servlet.FilterChain;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.CacheException;

import net.sf.ehcache.constructs.blocking.LockTimeoutException;

import net.sf.ehcache.constructs.web.AlreadyCommittedException;

import net.sf.ehcache.constructs.web.AlreadyGzippedException;

import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException;

import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

/**

* function: mobile 頁面緩存過濾器

* @author hoojo

* @createDate 2012-7-4 上午09:34:30

* @file PageEhCacheFilter.java

* @package com.hoo.ehcache.filter

* @project Ehcache

* @blog http://blog.csdn.net/IBM_hoojo

* @email hoojo_@126.com

* @version 1.0

*/

public class PageEhCacheFilter extends SimplePageCachingFilter {

private final static Logger log = Logger.getLogger(PageEhCacheFilter.class);

private final static String FILTER_URL_PATTERNS = "patterns";

private static String[] cacheURLs;

private void init() throws CacheException {

String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);

cacheURLs = StringUtils.split(patterns, ",");

}

@Override

protected void doFilter(final HttpServletRequest request,

final HttpServletResponse response, final FilterChain chain)

throws AlreadyGzippedException, AlreadyCommittedException,

FilterNonReentrantException, LockTimeoutException, Exception {

if (cacheURLs == null) {

init();

}

String url = request.getRequestURI();

boolean flag = false;

if (cacheURLs != null && cacheURLs.length > 0) {

for (String cacheURL : cacheURLs) {

if (url.contains(cacheURL.trim())) {

flag = true;

break;

}

}

}

// 如果包含我們要緩存的url 就緩存該頁面,否則執(zhí)行正常的頁面轉(zhuǎn)向

if (flag) {

String query = request.getQueryString();

if (query != null) {

query = "?" + query;

}

log.info("當前請求被緩存:" + url + query);

super.doFilter(request, response, chain);

} else {

chain.doFilter(request, response);

}

}

@SuppressWarnings("unchecked")

private boolean headerContains(final HttpServletRequest request, final String header, final String value) {

logRequestHeaders(request);

final Enumeration accepted = request.getHeaders(header);

while (accepted.hasMoreElements()) {

final String headerValue = (String) accepted.nextElement();

if (headerValue.indexOf(value) != -1) {

return true;

}

}

return false;

}

/**

* @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest)

* function: 兼容ie6/7 gzip壓縮

* @author hoojo

* @createDate 2012-7-4 上午11:07:11

*/

@Override

protected boolean acceptsGzipEncoding(HttpServletRequest request) {

boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");

boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");

return acceptsEncoding(request, "gzip") || ie6 || ie7;

}

}

這里的PageEhCacheFilter繼承了SimplePageCachingFilter,一般情況下SimplePageCachingFilter就夠用了,這里是為了滿足當前系統(tǒng)需求才做了覆蓋操作。使用SimplePageCachingFilter需要在web.xml中配置cacheName,cacheName默認是SimplePageCachingFilter,對應(yīng)ehcache.xml中的cache配置。

在web.xml中加入如下配置

PageEhCacheFilter

com.hoo.ehcache.filter.PageEhCacheFilter

patterns

/cache.jsp, product.action, market.action

PageEhCacheFilter

*.action

PageEhCacheFilter

*.jsp

當?shù)谝淮握埱筮@些頁面后,這些頁面就會被添加到緩存中,以后請求這些頁面將會從緩存中獲取。你可以在cache.jsp頁面中用小腳本來測試該頁面是否被緩存。如果時間是變動的,則表示該頁面沒有被緩存或是緩存已經(jīng)過期,否則則是在緩存狀態(tài)了。

四、對象緩存

對象緩存就是將查詢的數(shù)據(jù),添加到緩存中,下次再次查詢的時候直接從緩存中獲取,而不去數(shù)據(jù)庫中查詢。

對象緩存一般是針對方法、類而來的,結(jié)合Spring的Aop對象、方法緩存就很簡單。這里需要用到切面編程,用到了Spring的MethodInterceptor或是用@Aspect。

代碼如下:

package com.hoo.common.ehcache;

import java.io.Serializable;

import net.sf.ehcache.Cache;

import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.InitializingBean;

/**

* function: 緩存方法攔截器核心代碼

* @author hoojo

* @createDate 2012-7-2 下午06:05:34

* @file MethodCacheInterceptor.java

* @package com.hoo.common.ehcache

* @project Ehcache

* @blog http://blog.csdn.net/IBM_hoojo

* @email hoojo_@126.com

* @version 1.0

*/

public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean {

private static final Logger log = Logger.getLogger(MethodCacheInterceptor.class);

private Cache cache;

public void setCache(Cache cache) {

this.cache = cache;

}

public void afterPropertiesSet() throws Exception {

log.info(cache + " A cache is required. Use setCache(Cache) to provide one.");

}

public Object invoke(MethodInvocation invocation) throws Throwable {

String targetName = invocation.getThis().getClass().getName();

String methodName = invocation.getMethod().getName();

Object[] arguments = invocation.getArguments();

Object result;

String cacheKey = getCacheKey(targetName, methodName, arguments);

Element element = null;

synchronized (this) {

element = cache.get(cacheKey);

if (element == null) {

log.info(cacheKey + "加入到緩存: " + cache.getName());

// 調(diào)用實際的方法

result = invocation.proceed();

element = new Element(cacheKey, (Serializable) result);

cache.put(element);

} else {

log.info(cacheKey + "使用緩存: " + cache.getName());

}

}

return element.getValue();

}

/**

* function: 返回具體的方法全路徑名稱 參數(shù)

* @author hoojo

* @createDate 2012-7-2 下午06:12:39

* @param targetName 全路徑

* @param methodName 方法名稱

* @param arguments 參數(shù)

* @return 完整方法名稱

*/

private String getCacheKey(String targetName, String methodName, Object[] arguments) {

StringBuffer sb = new StringBuffer();

sb.append(targetName).append(".").append(methodName);

if ((arguments != null) && (arguments.length != 0)) {

for (int i = 0; i < arguments.length; i++) {

sb.append(".").append(arguments[i]);

}

}

return sb.toString();

}

}

這里的方法攔截器主要是對你要攔截的類的方法進行攔截,然后判斷該方法的類路徑+方法名稱+參數(shù)值組合的cache key在緩存cache中是否存在。如果存在就從緩存中取出該對象,轉(zhuǎn)換成我們要的返回類型。沒有的話就把該方法返回的對象添加到緩存中即可。值得主意的是當前方法的參數(shù)和返回值的對象類型需要序列化。

我們需要在src目錄下添加applicationContext.xml完成對MethodCacheInterceptor攔截器的配置,該配置主意是注入我們的cache對象,哪個cache來管理對象緩存,然后哪些類、方法參與該攔截器的掃描。

添加配置如下:

com.hoo.rest.*RestService*\.*get.*

com.hoo.rest.*RestService*\.*search.*

在ehcache.xml中添加如下cache配置

maxElementsInMemory="10000"

eternal="false"

overflowToDisk="true"

timeToIdleSeconds="1800"

timeToLiveSeconds="3600"

memoryStoreEvictionPolicy="LFU" />

總結(jié)

以上是生活随笔為你收集整理的ehcache 缓存java对象_Ehcache 整合Spring 使用页面、对象缓存的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。