溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Restful: Spring Boot with Mongodb

發(fā)布時(shí)間:2020-07-21 12:36:03 來(lái)源:網(wǎng)絡(luò) 閱讀:310 作者:沙漏半杯 欄目:編程語(yǔ)言

為什么是mongodb?

繼續(xù)之前的dailyReport項(xiàng)目,今天的任務(wù)是選擇mongogdb作為持久化存儲(chǔ)。

關(guān)于nosql和rdbms的對(duì)比以及選擇,我參考了不少資料,關(guān)鍵一點(diǎn)在于:nosql可以輕易擴(kuò)展表的列,對(duì)于業(yè)務(wù)快速變化的應(yīng)用場(chǎng)景非常適合;rdbms則需要安裝關(guān)系型數(shù)據(jù)庫(kù)模式對(duì)業(yè)務(wù)進(jìn)行建模,適合業(yè)務(wù)場(chǎng)景已經(jīng)成熟的系統(tǒng)。我目前的這個(gè)項(xiàng)目——dailyReport,我暫時(shí)沒(méi)法確定的是,對(duì)于一個(gè)report,它的屬性應(yīng)該有哪些:date、title、content、address、images等等,基于此我選擇mongodb作為該項(xiàng)目的持久化存儲(chǔ)。

如何將mongodb與spring boot結(jié)合使用

  • 修改Pom文件,增加mongodb支持

<dependency>
??<groupId>org.springframework.boot</groupId>
??<artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
  • 重新設(shè)計(jì)Report實(shí)體類(lèi),id屬性是給mongodb用的,用@Id注解修飾;重載toString函數(shù),使用String.format輸出該對(duì)象。

import?org.springframework.data.annotation.Id;/**
?*?@author?duqi
?*?@create?2015-11-17?19:31
?*/public?class?Report?{????@Id
????private?String?id;????private?String?date;????private?String?content;????private?String?title;????public?Report()?{

????}????public?Report(String?date,?String?title,?String?content)?{????????this.date?=?date;????????this.title?=?title;????????this.content?=?content;
????}????public?String?getId()?{????????return?id;
????}????public?void?setId(String?id)?{????????this.id?=?id;
????}????public?String?getTitle()?{????????return?title;
????}????public?void?setTitle(String?title)?{????????this.title?=?title;
????}????public?String?getDate()?{????????return?date;
????}????public?void?setDate(String?dateStr)?{????????this.date?=?dateStr;
????}????public?String?getContent()?{????????return?content;
????}????public?void?setContent(String?content)?{????????this.content?=?content;
????}????@Override
????public?String?toString()?{????????return?String.format("Report[id=%s,?date='%s',?content='%s',?title='%s']",?id,?date,?content,?title);
????}
}
  • 增加ReportRepository接口,它繼承自MongoRepository接口,MongoRepository接口包含了常用的CRUD操作,例如:save、insert、findall等等。我們可以定義自己的查找接口,例如根據(jù)report的title搜索,具體的ReportRepository接口代碼如下:

import?org.springframework.data.mongodb.repository.MongoRepository;import?java.util.List;/**
?*?Created?by?duqi?on?15/11/22.
?*/public?interface?ReportRepository?extends?MongoRepository<Report,?String>?{????Report?findByTitle(String?title);????List<Report>?findByDate(String?date);
}
  • 修改ReportService代碼,增加createReport函數(shù),該函數(shù)根據(jù)Conroller傳來(lái)的Map參數(shù)初始化一個(gè)Report對(duì)象,并調(diào)用ReportRepository將數(shù)據(jù)save到mongodb中;對(duì)于getReportDetails函數(shù),仍然開(kāi)啟緩存,如果沒(méi)有緩存的時(shí)候則利用findByTitle接口查詢mongodb數(shù)據(jù)庫(kù)。

import?com.javadu.dailyReport.domain.Report;import?com.javadu.dailyReport.domain.ReportRepository;import?org.springframework.beans.factory.annotation.Autowired;import?org.springframework.cache.annotation.Cacheable;import?org.springframework.stereotype.Service;import?java.util.Map;/**
?*?@author?duqi
?*?@create?2015-11-17?20:05
?*/@Servicepublic?class?ReportService?{????@Autowired
????private?ReportRepository?repository;????public?Report?createReport(Map<String,?Object>?reportMap)?{
????????Report?report?=?new?Report(reportMap.get("date").toString(),
????????????????reportMap.get("title").toString(),
????????????????reportMap.get("content").toString());

????????repository.save(report);????????return?report;
????}????@Cacheable(value?=?"reportcache",?keyGenerator?=?"wiselyKeyGenerator")????public?Report?getReportDetails(String?title)?{
????????System.out.println("無(wú)緩存的時(shí)候調(diào)用這里---數(shù)據(jù)庫(kù)查詢,?title="?+?title);????????return?repository.findByTitle(title);
????}
}

Restful接口

Controller只負(fù)責(zé)URL到具體Service的映射,而在Service層進(jìn)行真正的業(yè)務(wù)邏輯處理,我們這里的業(yè)務(wù)邏輯異常簡(jiǎn)單,因此顯得Service層可有可無(wú),但是如果業(yè)務(wù)邏輯復(fù)雜起來(lái)(比方說(shuō)要通過(guò)RPC調(diào)用一個(gè)異地服務(wù)),這些操作都需要再service層完成??傮w來(lái)講,Controller層只負(fù)責(zé):轉(zhuǎn)發(fā)請(qǐng)求 + 構(gòu)造Response數(shù)據(jù);在需要進(jìn)行權(quán)限驗(yàn)證的時(shí)候,也在Controller層利用aop完成。

一般將對(duì)于Report(某個(gè)實(shí)體)的所有操作放在一個(gè)Controller中,并用@RestController和@RequestMapping("/report")注解修飾,表示所有xxxx/report開(kāi)頭的URL會(huì)由這個(gè)ReportController進(jìn)行處理。

. POST

對(duì)于增加report操作,我們選擇POST方法,并使用@RequestBody修飾POST請(qǐng)求的請(qǐng)求體,也就是createReport函數(shù)的參數(shù);

. GET

對(duì)于查詢r(jià)eport操作,我們選擇GET方法,URL的形式是:“xxx/report/${report's title}”,使用@PathVariable修飾url輸入的參數(shù),即title。

import?com.javadu.dailyReport.domain.Report;import?com.javadu.dailyReport.service.ReportService;import?org.slf4j.Logger;import?org.slf4j.LoggerFactory;import?org.springframework.beans.factory.annotation.Autowired;import?org.springframework.web.bind.annotation.*;import?java.util.LinkedHashMap;import?java.util.Map;/**
?*?@author?duqi
?*?@create?2015-11-17?20:10
?*/@RestController@RequestMapping("/report")public?class?ReportController?{????private?static?final?Logger?logger?=?LoggerFactory.getLogger(ReportController.class);????@Autowired
????ReportService?reportService;????@RequestMapping(method?=?RequestMethod.POST)????public?Map<String,?Object>?createReport(@RequestBody?Map<String,?Object>?reportMap)?{
????????logger.info("createReport");
????????Report?report?=?reportService.createReport(reportMap);

????????Map<String,?Object>?response?=?new?LinkedHashMap<String,?Object>();
????????response.put("message",?"Report?created?successfully");
????????response.put("report",?report);????????return?response;
????}????@RequestMapping(method?=?RequestMethod.GET,?value?=?"/{reportTitle}")????public?Report?getReportDetails(@PathVariable("reportTitle")?String?title)?{
????????logger.info("getReportDetails");????????return?reportService.getReportDetails(title);
????}
}

Update和delete操作我這里就不一一講述了

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI