SpringBoot整合MongoDB(實現一個簡單緩存)

前言

SpringBoot是經常使用開發框架,而MongoDB也是最近愈來愈火的非關係型數據庫,這裏使用SpringBoot+MongoDB實現一個小案例,固然MongoDB實際作緩存的可能很少,可是這裏僅僅爲了一個小demo簡單的學習使用,入門上手爲目的,更多的複雜查詢還需關注MongoDB官網。前端

若是本篇對你有幫助,還請點贊支持一下!原創做者:bigsaijava

若是對MongoDB不太瞭解,還請先看上篇MongoDB從立地到成佛web

建立MongoDB數據庫和項目

建立MongoDB數據庫

打開Studio 3T數據庫管理工具,鏈接本地MongoDB數據庫以後,建立名爲test的數據庫,在test數據庫中建立名爲news得集合:spring

在這裏插入圖片描述

建立項目

首先,打開IDEA建立項目,選擇建立Springboot項目:
在這裏插入圖片描述
而後在選擇Gruop和Aritifact時候分別填寫commongodemo,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);
    
    
}

其中:框架

  • @RestController就聲明該類爲一個控制器,而且返回JSON字符串給前端。
  • 而Logger對象用於打印日誌。在web項目中咱們更傾向於使用log打印日誌而不在控制檯直接輸出。

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 表示該類爲一個service(事務處理),能夠被注入到其餘對象(Spring幫你管理)。
  • @Autowired表示要注入對象的意思。而MongoTemplate 就是已經封裝好在Spring中操做MongoDB的對象。

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;
   }

上面的代碼中:

  • 咱們核心使用mongoTemplate對象來實現查詢一條記錄,查詢語句爲:mongoTemplate.findOne(query, news.class),第一個參數爲查詢的條件,第二個參數爲查詢結果轉成Java對象的類型,它幫你自動處理。
  • 經過Query對象來輔助咱們實現條件查詢,這裏的意思就是查詢條件爲:MongoDB中title字段爲傳進來title字符串的該條記錄。
  • 而插入的語法爲 mongoTemplate.insert(news1,"news"),第一個參數爲插入的文檔記錄,第二個參數爲鏈接呃MongoDB對應數據庫下的集合(Collections)。

在newsController中,咱們編寫一個名稱爲getnews的接口,用來給用戶返回該標題新聞(news類)的一條數據的JSON文件,具體代碼爲:

@Autowired
   NewsService newsService;

   @GetMapping("getnews/{title}")
   public news getnews(@PathVariable String title)
   {
        news news=newsService.getNewsByTitle(title);
       return  news;
   }

上面代碼中:

  • @Autowired(required = false)用來注入對象,下面的NewsService userService就是被注入的對象,注入以後不須要手動建立對象能夠直接使用(Spring幫你管理)
  • @GetMapping("getnews/{title}") 意爲聲明一個get請求方式的接口,

咱們啓動程序,瀏覽器輸入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;
    }

其中:

  • Query對象來輔助咱們實現條件查詢待更新數據,這裏的意思就是查詢條件一樣爲:MongoDB中title字段爲傳進來title字符串的該條記錄。
  • Update對象用來記錄更新的字段和數據,這裏更新傳進來的content內容和date日期。
  • mongoTemplate.upsert(query, update, news.class)用來實現更新,若是MongoDB中不存在該數據那麼就插入到MongoDB中。

編寫完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資源一份!

相關文章
相關標籤/搜索