您好,登錄后才能下訂單哦!
在springboot中使用EHcache 如何實(shí)現(xiàn)文章瀏覽量的更新與緩存?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
問題描述
當(dāng)我們需要統(tǒng)計(jì)文章的瀏覽量的時(shí)候,最常規(guī)的做法就是:
1.訪問文章鏈接www.abc.com/article/{id}
2.在控制層獲取Article實(shí)體
3.得到文章瀏覽量count并且count++
4.最后update實(shí)體Article。
這么做對(duì)沒有訪問量的網(wǎng)站來說很棒,如果網(wǎng)站訪問量很大,這么不停的讀寫數(shù)據(jù)庫,會(huì)對(duì)服務(wù)器造成很大的壓力。
解決思路
引入Ehcache,將文章的訪問量存在cache中,每點(diǎn)擊一次文章,將cache中的count加1.在有效的時(shí)間內(nèi)訪問文章只是將cache中的數(shù)據(jù)+1,超過指定時(shí)間則進(jìn)行一次數(shù)據(jù)庫更新。
解決方案
本文是在springboot整合ehcache的環(huán)境下驗(yàn)證的。springboot版本1.5.2 。ehcache版本2.6.11。springboot整合ehcache的步驟很簡(jiǎn)單,下面簡(jiǎn)單提一下,在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
最后在啟動(dòng)類標(biāo)注@EnableCaching
引入緩存之后,接著我們的正題
在ehcache.xml文件中定義dayHits緩存
<cache name="dayHits" maxEntriesLocalHeap="500" eternal="true" overflowToDisk="true"> </cache>
表示保存當(dāng)日點(diǎn)擊量的
在controller層定義緩存點(diǎn)擊量的方法
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.在查看文章方法中進(jìn)行調(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();
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。