SpringBoot是經常使用開發框架,而MongoDB也是最近愈來愈火的非關係型數據庫,這裏使用SpringBoot+MongoDB實現一個小案例,固然MongoDB實際作緩存的可能很少,可是這裏僅僅爲了一個小demo簡單的學習使用,入門上手爲目的,更多的複雜查詢還需關注MongoDB官網。前端
若是本篇對你有幫助,還請點贊支持一下!原創做者:
bigsai
java
若是對MongoDB不太瞭解,還請先看上篇MongoDB從立地到成佛。web
打開Studio 3T數據庫管理工具,鏈接本地MongoDB數據庫以後,建立名爲test的數據庫,在test數據庫中建立名爲news得集合:spring
首先,打開IDEA建立項目,選擇建立Springboot項目:
而後在選擇Gruop和Aritifact時候分別填寫com和mongodemo,Java Version選擇8版本。
mongodb
在勾選模塊時候,這裏勾選Spring web、MongoDB依賴模塊,選擇合適位置建立項目,項目就能夠成功建立:數據庫
建立完項目,咱們須要作一些預備工做用來完成緩存。咱們首先要在項目中的application.properties中添加配置鏈接到數據庫,配置規則爲:spring.data.mongodb.uri=mongodb://地址:端口/數據庫名
,本案例使用本地的MongoDB數據庫,默認端口爲27017,而使用的MongoDB具體數據庫名稱爲test,那麼就能夠按照如下進行配置:瀏覽器
spring.data.mongodb.uri=mongodb://localhost:27017/test
這樣在項目中就能夠鏈接到本地的MongoDB的test數據庫並訪問。緩存
其次在項目中com.mongodb目錄下分別建立controller,service,pojo文件夾,在controller文件夾下建立newsController.java
類,爲負責url和邏輯的控制器:app
package com.mongodemo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RestController; @RestController public class newsController { private static Logger logger= LoggerFactory.getLogger(newsController.class); }
其中:框架
controller建立完畢在service 文件夾下建立NewsService.java
類,裏面先編寫如下內容:
package com.mongodemo.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; @Service public class NewsService { private static Logger logger= LoggerFactory.getLogger(NewsService.class); @Autowired MongoTemplate mongoTemplate; }
其中:
service建立完成,咱們須要在pojo中建立news類,表明新聞實體內容。
import java.util.Date; public class news { private String title; private Date date; private String brief; private String content; private String author; @Override public String toString() { return "news{" + "title='" + title + '\'' + ", date=" + date + ", brief='" + brief + '\'' + ", content='" + content + '\'' + ", author='" + author + '\'' + '}'; } public news(String title, Date date, String brief, String content, String author) { this.title = title; this.date = date; this.brief = brief; this.content = content; this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getBrief() { return brief; } public void setBrief(String brief) { this.brief = brief; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
其中各個字段分別表示爲:
名稱 | 含義 |
---|---|
title | 標題 |
date | 日期 |
brief | 概要 |
content | 內容 |
author | 做者 |
下面開始實戰MongoDB實現一個新聞得緩存功能,實現緩存以前,要清楚緩存的核心做用:提高web程序的查詢速度,將熱點數據放到非關係數據庫中。本案例對接口進行緩存,不過真正的緩存實例須要考慮不少問題好比時效性,緩存那些數據等。在這裏主要爲了講解MongoDB的一個實例。
在查詢時候,緩存和數據庫之間一般是這麼配合的:
爲了下降整個項目的複雜度,這裏用手動生成的數據對象代替成數據庫中查詢的數據,咱們在NewsService中編寫getNewsByTitle(String title)函數,其功能是根據標題返回緩存或數據庫中該條news數據,若是MongoDB中存在則直接返回該對象,不然先從數據庫查詢(這裏直接生成),而後存到MongoDB中再返回。具體代碼爲:
public news getNewsByTitle(String title) { //查詢數據先從MongoDB中查詢 Query query = new Query(Criteria.where("title").is(title)); news news=mongoTemplate.findOne(query, news.class); if(news==null)//緩存中沒該條記錄 { logger.info("從數據庫查詢數據"); //假設news1從數據庫中查詢 news news1=new news(title,new Date(),"","","bigsai"); news1.setBrief("有了博學谷,媽媽不再用擔憂個人java學習!"); news1.setContent("博學谷優質學習資料爲java學習提供更好環境,愈來愈多開發者學習使用"); mongoTemplate.insert(news1,"news"); logger.info("數據插入到MongoDB成功"); news=news1; } else { logger.info("數據從緩存訪問成功"); } return news; }
上面的代碼中:
在newsController中,咱們編寫一個名稱爲getnews的接口,用來給用戶返回該標題新聞(news類)的一條數據的JSON文件,具體代碼爲:
@Autowired NewsService newsService; @GetMapping("getnews/{title}") public news getnews(@PathVariable String title) { news news=newsService.getNewsByTitle(title); return news; }
上面代碼中:
咱們啓動程序,瀏覽器輸入localhost:8080/getnews/好好學java
頁面會有返回的結果,返回的一個news對象序列化成JSON的字符串的文本。
同時,你查看IDEA的日誌,因爲第一次查詢,MongoDB中沒有對應數據你會發現會先從數據庫中查詢而後存儲到MongoDB中:
查看MongoDB的news集合發現記錄被成功插入了,多刷新頁面localhost:8080/getnews/好好學java
你會發現數據會直接從MongoDB中返回:
緩存中的數據和存儲的關係數據庫的數據是一致的,當咱們只有查詢操做的時候,能夠一直保持數據的一致性,可是咱們若是對數據有更新、刪除的操做,就須要對關係數據庫和MongoDB中的數據同時進行更新或刪除的操做,讓數據再次達到一致性的效果。
雖然大部分狀況咱們對熱點新聞數據可能不多更新,可是也有時候新聞中有部份內容須要更改的須要咱們完成,好比比分錯字或者不妥的言論。
咱們在NewsService中編寫updateNewsContentByTitle((String title,String content)函數,其做用爲更新數據庫(這裏沒有具體實現)和MongoDB緩存中的數據:
public boolean updateNewsContentByTitle(String title,String content) { try { Query query = new Query(Criteria.where("title").is(title)); Update update = new Update(); update.set("content", content);//更新內容 update.set("date",new Date());//更新時間 // 假設在這裏數據庫中更新過這裏跳過 // updateFirst 更新查詢返回結果集的第一條 //upsert 更新若是不存在就插入 mongoTemplate.upsert(query, update, news.class); } catch (Exception e) { return false; } return true; }
其中:
編寫完service,在newsController中編寫一個名爲updatenews的接口,用來更新數據庫數據和緩存在MongoDB的數據:
@GetMapping("updatenews") public String updatenews(String title,String content) { boolean bool=newsService.updateNewsContentByTitle(title,content); if(bool) return "更新成功"; else return "更新失敗"; }
啓動程序訪問localhost:8080/updatenews?title=好好學java&content=學好java走遍全天下
,你會發現數據更新成功:
除了更新的時候須要保證數據一致性,刪除的時候也須要保證數據一致性,若是在刪除關係數據庫的數據而不刪除MongoDB緩存,那麼下次查詢該條數據MongoDB中存在而關係數據庫中不存在,這樣就形成了數據不一致,因此在刪除數據的時候咱們須要在MongoDB中的數據也刪除。
在NewsService中編寫deleteNewsByTitle(String title)函數,用來根據標題title刪除MongoDB中的記錄:
public boolean deleteNewsByTitle(String title) { try { Query query = new Query(Criteria.where("title").is(title)); mongoTemplate.remove(query,news.class); } catch (Exception e) { return false; } return true; }
mongoTemplate.remove(query,news.class);意味從MongoDB中刪除知足查詢條件的記錄。其中query爲查詢條件,news.class爲刪除對象在Java中的類。
在newsController中編寫deletenews接口,用來處理刪除的請求:
@GetMapping("deletenews/{title}") public String deletenews(@PathVariable String title) { try { newsService.deleteNewsByTitle("好好學java"); return "刪除成功"; } catch (Exception e) { return "刪除失敗"; } }
啓動程序,訪問http://localhost:8080/deletenews/好好學java
,會發現緩存在MongoDB中的記錄被成功刪除,這樣就保證MongoDB中不會出現關係數據庫中不存在的髒數據,達到數據一致性!
本篇到這裏就結束了,若是幫助還請不要吝嗇你的小贊、收藏一份若有更多期待還請關注公衆號bigsai
,回覆bigsai獲取珍藏pdf資源一份!