springboot+EHcache 實現(xiàn)文章瀏覽量的緩存和超時更新
問題描述
當(dāng)我們需要統(tǒng)計文章的瀏覽量的時候,最常規(guī)的做法就是:
1.訪問文章鏈接www.abc.com/article/{id}
2.在控制層獲取Article實體
3.得到文章瀏覽量count并且count++
4.最后update實體Article。
這么做對沒有訪問量的網(wǎng)站來說很棒,如果網(wǎng)站訪問量很大,這么不停的讀寫數(shù)據(jù)庫,會對服務(wù)器造成很大的壓力。
解決思路
引入Ehcache,將文章的訪問量存在cache中,每點擊一次文章,將cache中的count加1.在有效的時間內(nèi)訪問文章只是將cache中的數(shù)據(jù)+1,超過指定時間則進行一次數(shù)據(jù)庫更新。
解決方案
本文是在springboot整合ehcache的環(huán)境下驗證的。springboot版本1.5.2 。ehcache版本2.6.11。springboot整合ehcache的步驟很簡單,下面簡單提一下,在pom文件中引入ehcache依賴
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency>
在類路徑下存放ehcache.xml文件。
在application.yml中指定:
spring: cache: jcache: config: classpath:ehcache.xml
最后在啟動類標(biāo)注@EnableCaching
引入緩存之后,接著我們的正題
在ehcache.xml文件中定義dayHits緩存
<cache name="dayHits" maxEntriesLocalHeap="500" eternal="true" overflowToDisk="true"> </cache>
表示保存當(dāng)日點擊量的
在controller層定義緩存點擊量的方法
public Integer cacheCount(Long articleId){ Content content = contentRepository.findOne(articleId); Ehcache cache = cacheManager.getEhcache("dayHits"); Element element = cache.get(articleId+"_count"); Integer count = 0; if(element!=null){ count = (Integer) element.getValue(); }else{ count = content.getHits()== null?0:content.getHits(); } count++; cache.put(new Element(articleId+"_count",count)); cache.put(new Element(articleId+"_dayHitsDate",SystemUtils.getNowDate())); Long time = System.currentTimeMillis(); if(time > (viewArticleTime+ 300000)){ viewArticleTime = time; content.setHits(count); contentRepository.save(content); cache.removeAll(); } return count; }
3.在查看文章方法中進行調(diào)用。
@RequestMapping(value = "article/{id}",method = RequestMethod. GET) public String detail(@PathVariable Long id,ModelMap map){ Integer hits = cacheCount(id); }
4.其中局部變量的定義:
private static CacheManager cacheManager = CacheManager.newInstance(); private static Long viewArticleTime = System.currentTimeMillis();
5.保存訪問看看效果吧。
以上所述是小編給大家介紹的springboot+EHcache 實現(xiàn)文章瀏覽量的緩存和超時更新,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Mac下安裝配置Maven并在IDEA中配置的詳細(xì)教程
這篇文章主要介紹了Mac下安裝配置Maven并在IDEA中配置,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07在Java中String和Date、Timestamp之間的轉(zhuǎn)換
這篇文章主要介紹了在Java中String和Date、Timestamp之間的轉(zhuǎn)換 的相關(guān)資料,需要的朋友可以參考下2015-12-12SpringBoot使用knife4j進行在線接口調(diào)試
這篇文章主要介紹了SpringBoot使用knife4j進行在線接口調(diào)試,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09java數(shù)據(jù)結(jié)構(gòu)與算法之中綴表達(dá)式轉(zhuǎn)為后綴表達(dá)式的方法
這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)與算法之中綴表達(dá)式轉(zhuǎn)為后綴表達(dá)式的方法,簡單分析了java中綴表達(dá)式轉(zhuǎn)為后綴表達(dá)式的相關(guān)實現(xiàn)方法與技巧,需要的朋友可以參考下2016-08-08