SpringBoot整合redis及mongodb的詳細(xì)過程
NoSQL數(shù)據(jù)庫之中最具代表性的,當(dāng)屬鍵值對(duì)數(shù)據(jù)庫類別下的Redis,以及文檔型數(shù)據(jù)庫的Mongodb,本節(jié)我們重點(diǎn)關(guān)注這兩個(gè)產(chǎn)品在SpringBoot下的整合及使用
最近很忙,好不容易才抽出了時(shí)間,咱們接上回
上次我們主要講了如何通過SpringBoot快速集成mybatis/mybatis-plus,以實(shí)現(xiàn)業(yè)務(wù)交互中的數(shù)據(jù)持久化,而這一切都是基于關(guān)系型數(shù)據(jù)庫(SQL)實(shí)現(xiàn)的
本節(jié)我們來把關(guān)注點(diǎn)轉(zhuǎn)向NoSQL
NoSQL的概念:
NoSQL,泛指非關(guān)系型的數(shù)據(jù)庫。隨著互聯(lián)網(wǎng)web2.0網(wǎng)站的興起,傳統(tǒng)的關(guān)系數(shù)據(jù)庫在處理web2.0網(wǎng)站,特別是超大規(guī)模和高并發(fā)的SNS類型的web2.0純動(dòng)態(tài)網(wǎng)站已經(jīng)顯得力不從心,出現(xiàn)了很多難以克服的問題,而非關(guān)系型的數(shù)據(jù)庫則由于其本身的特點(diǎn)得到了非常迅速的發(fā)展。NoSQL數(shù)據(jù)庫的產(chǎn)生就是為了解決大規(guī)模數(shù)據(jù)集合多重?cái)?shù)據(jù)種類帶來的挑戰(zhàn),特別是大數(shù)據(jù)應(yīng)用難題。(——來自百度百科)
得益于其直接基于內(nèi)存的存儲(chǔ)方式,NoSQL的訪問速度可以用“飛快”兩個(gè)字來形容
在生產(chǎn)環(huán)境中,NoSQL常常配合傳統(tǒng)關(guān)系型數(shù)據(jù)庫來使用,比如構(gòu)建一層數(shù)據(jù)緩存來極大的提升數(shù)據(jù)的讀取速度
NoSQL在日常業(yè)務(wù)的驅(qū)動(dòng)之下,逐漸發(fā)展出幾個(gè)主要的類別:鍵值對(duì)數(shù)據(jù)庫、文檔型數(shù)據(jù)庫、列存儲(chǔ)數(shù)據(jù)庫以及圖形化數(shù)據(jù)庫
這4類NoSQL數(shù)據(jù)庫之中最具代表性的,當(dāng)屬鍵值對(duì)數(shù)據(jù)庫類別下的Redis,以及文檔型數(shù)據(jù)庫的Mongodb,本節(jié)我們重點(diǎn)關(guān)注這兩個(gè)產(chǎn)品在SpringBoot下的整合及使用
照慣例先上項(xiàng)目結(jié)構(gòu):

一、先看Redis的使用:
1. 在pom.xml中添加Redis相關(guān)依賴項(xiàng)
<!-- 引入redis依賴(基于lettuce) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>2. 在application.properties中添加Redis的相關(guān)配置
# redis相關(guān)設(shè)置 spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= # redis默認(rèn)基于lettuce內(nèi)核 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.min-idle=0
這里關(guān)于lettuce內(nèi)核有必要給大家解釋一下:
在SpringBoot2.x版本之前,其集成的默認(rèn)Redis庫是Jedis,而在2.x版本之后才改為默認(rèn)基于Lettuce
Jedis默認(rèn)和Redis直連,為非線程安全模型,并發(fā)環(huán)境下需要池化使用
而Lettuce則是線程安全的,并發(fā)環(huán)境下可以通過一個(gè)實(shí)例搞定
當(dāng)然,你也可以在SpringBoot2.x環(huán)境下依然使用Jedis,只需要把spring.redis.lettuce 相關(guān)配置替換為spring.redis.jedis 即可
更多內(nèi)容大家感興趣可以從網(wǎng)上查閱相關(guān)資料,這里推薦一篇:https://blog.csdn.net/kenkao/article/details/127085687
3. 新建 service/RedisService 接口及其實(shí)現(xiàn)類 service/impl/RedisServiceImpl
package com.example.hellospringboot.service;
public interface RedisService {
void set(String key, String val);
String get(String key);
}package com.example.hellospringboot.service.impl;
import com.example.hellospringboot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
StringRedisTemplate redis;
public void set(String key, String val){
ValueOperations<String,String> ops = redis.opsForValue();
ops.set(key, val);
}
public String get(String key){
ValueOperations<String,String> ops = redis.opsForValue();
return ops.get(key);
}
}我們?cè)赟ervice中自動(dòng)裝載一個(gè)StringRedisTemplate實(shí)例,而后通過其創(chuàng)建Operation對(duì)象,進(jìn)行可以進(jìn)行各種Redis讀寫操作
4. 新建 controller/RedisController
package com.example.hellospringboot.controller;
import com.example.hellospringboot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
RedisService service;
@PostMapping("/set")
public void set(String key, String val){
service.set(key, val);
}
@GetMapping("/get")
public String get(String key){
return service.get(key);
}
}5. 通過Postman進(jìn)行結(jié)果驗(yàn)證

通過RDM查看寫入redis的數(shù)據(jù):

之后是讀操作:

至此我們便完成了SpringBoot中集成Redis的操作
二、MongoDB的使用
1. 首先還是先添加MongoDB相關(guān)依賴項(xiàng)
<!-- 引入mongodb依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>2. 然后是添加MongoDB相關(guān)配置
# mongodb相關(guān)設(shè)置 spring.data.mongodb.authentication-database=admin spring.data.mongodb.database=local spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 #spring.data.mongodb.username=admin #spring.data.mongodb.password=admin
各注釋項(xiàng)內(nèi)容依次是:身份驗(yàn)證庫、目標(biāo)數(shù)據(jù)庫、主機(jī)地址、端口以及用戶名和口令
由于我沒有設(shè)置用戶名和口令,所以直接注釋掉這兩項(xiàng)
3. 新建 repository/PersonRepository
package com.example.hellospringboot.repository;
import com.example.hellospringboot.model.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends MongoRepository<Person, Integer> {
Person findByNameIs(String name);
Person findByIdIs(int id);
Person findByIdAndName(int id, String name);
Person findByIdOrName(int id, String name);
}這里出現(xiàn)了非常神奇的一幕:
我們僅需要提供一個(gè)接口,而不用提供具體實(shí)現(xiàn)!
僅憑方法的命名規(guī)范,spring.data.mongodb就能自行分析開發(fā)者的意圖,進(jìn)行補(bǔ)全內(nèi)部的業(yè)務(wù)邏輯!
而同樣具備這種智能化能力的還有spring.jpa,后者也是一種非常便捷高效數(shù)據(jù)庫驅(qū)動(dòng),與mybatis屬于同類產(chǎn)品
順便也給大家提供一份方法命名規(guī)范清單,請(qǐng)各位在方法命名時(shí)務(wù)必遵循以下規(guī)則:
| 關(guān)鍵字 | 方法命名 | sql where字句 |
| And | findByNameAndPwd | where name= ? and pwd =? |
| Or | findByNameOrSex | where name= ? or sex=? |
| Is,Equals | findById,findByIdEquals | where id= ? |
| Between | findByIdBetween | where id between ? and ? |
| LessThan | findByIdLessThan | where id < ? |
| LessThanEqual | findByIdLessThanEqual | where id <= ? |
| GreaterThan | findByIdGreaterThan | where id > ? |
| GreaterThanEqual | findByIdGreaterThanEqual | where id > = ? |
| After | findByIdAfter | where id > ? |
| Before | findByIdBefore | where id < ? |
| IsNull | findByNameIsNull | where name is null |
| isNotNull,NotNull | findByNameNotNull | where name is not null |
| Like | findByNameLike | where name like ? |
| NotLike | findByNameNotLike | where name not like ? |
StartingWith | findByNameStartingWith | where name like '?%' |
| EndingWith | findByNameEndingWith | where name like '%?' |
| Containing | findByNameContaining | where name like '%?%' |
| OrderBy | findByIdOrderByXDesc | where id=? order by x desc |
| Not | findByNameNot | where name <> ? |
| In | findByIdIn(Collection<?> c) | where id in (?) |
| NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |
| True | findByAaaTue | where aaa = true |
| False | findByAaaFalse | where aaa = false |
| IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |
4. Service接口定義及實(shí)現(xiàn)
package com.example.hellospringboot.service;
import com.example.hellospringboot.model.Person;
public interface MongoService {
public void insert(Person person);
public Person findByName(String name);
public Person findById(int id);
public Person findByIdAndName(int id, String name);
public Person findByIdOrName(int id, String name);
}package com.example.hellospringboot.service.impl;
import com.example.hellospringboot.model.Person;
import com.example.hellospringboot.repository.PersonRepository;
import com.example.hellospringboot.service.MongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MongoServiceImpl implements MongoService {
@Autowired
PersonRepository repository;
public void insert(Person person){
repository.insert(person);
}
public Person findByName(String name){
return repository.findByNameIs(name);
}
public Person findById(int id){
return repository.findByIdIs(id);
}
public Person findByIdAndName(int id, String name){
return repository.findByIdAndName(id, name);
}
public Person findByIdOrName(int id, String name){
return repository.findByIdOrName(id, name);
}
}
5. Controller實(shí)現(xiàn)
package com.example.hellospringboot.controller;
import com.example.hellospringboot.model.Person;
import com.example.hellospringboot.service.MongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mongo")
public class MongoController {
@Autowired
MongoService service;
@PostMapping("/insert")
public void insert(Person person){
service.insert(person);
}
@GetMapping("/findByName")
public Person findByName(String name){
return service.findByName(name);
}
@GetMapping("/findById")
public Person findById(int id){
return service.findById(id);
}
@GetMapping("/findByIdAndName")
public Person findByIdAndName(int id, String name){
return service.findByIdAndName(id, name);
}
@GetMapping("/findByIdOrName")
public Person findByIdOrName(int id, String name) {
return service.findByIdOrName(id, name);
}
}Service及Controller的實(shí)現(xiàn)不再做過多贅述,還是老一套
6. Postman驗(yàn)證結(jié)果
向mongodb中寫入一條數(shù)據(jù)


之后是幾種讀取操作:



不論是與或操作,我們都可以得到正確的結(jié)果
到這里,mongodb的集成就完成了
三、基于Redis實(shí)現(xiàn)Session配置共享
這部分純屬附送內(nèi)容 ^ ^
前邊我們已經(jīng)完成了對(duì)Redis的集成操作,而基于Redis我們可以非常便捷的實(shí)現(xiàn)服務(wù)端Session配置的跨節(jié)點(diǎn)共享
服務(wù)端Session默認(rèn)存儲(chǔ)在本地,而當(dāng)我們需要多臺(tái)服務(wù)器共享一套Session配置時(shí),本地化Session便不再滿足我們的要求
而基于SpringSession,我們可以完全透明化的替換掉默認(rèn)的Session容器,直接改為基于Redis存儲(chǔ)
1. 添加相關(guān)依賴
<!-- 引入spring session無縫替換原有的session系統(tǒng) -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>2. 新增兩個(gè)RedisController方法
@PostMapping("/setSession")
public void setSession(String key, String val, HttpSession session){
session.setAttribute(key, val);
}
@GetMapping("/getSession")
public Object getSession(String key, HttpSession session){
return session.getAttribute(key);
}就完事兒了?對(duì)!就完事兒了 ^ ^,超級(jí)簡單是吧?
到此,我們就完成了SpringBoot對(duì)于Redis以及MongoDB的集成和使用
非常感慨于SpringBoot框架設(shè)計(jì)的智能化及人性化,就像身邊有一哥們說的:這年頭,框架都能直接聽懂人話了!哈哈
到此這篇關(guān)于SpringBoot整合redis及mongodb的文章就介紹到這了,更多相關(guān)SpringBoot整合redis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入分析Mongodb數(shù)據(jù)的導(dǎo)入導(dǎo)出
這幾天想著公司要用MongoDB,自然就要用到數(shù)據(jù)導(dǎo)入導(dǎo)出,就自己學(xué)習(xí)了一下。本文介紹了mongoDb導(dǎo)入導(dǎo)出數(shù)據(jù)的方法,有需要的朋友參考下。2015-05-05
Windows下MongoDB配置用戶權(quán)限實(shí)例
這篇文章主要介紹了Windows下MongoDB配置用戶權(quán)限實(shí)例,本文實(shí)現(xiàn)需要輸入用戶名、密碼才可以訪問MongoDB數(shù)據(jù)庫,需要的朋友可以參考下2015-01-01
MongoDB查詢字段沒有創(chuàng)建索引導(dǎo)致的連接超時(shí)異常解案例分享
這篇文章主要介紹了MongoDB查詢字段沒有創(chuàng)建索引導(dǎo)致的連接超時(shí)異常解案例分享,本文是生產(chǎn)環(huán)境下總結(jié)而來,需要的朋友可以參考下2014-10-10
mongo數(shù)據(jù)集合屬性中存在點(diǎn)號(hào)(.)的解決方法
這篇文章主要給大家介紹了關(guān)于mongo數(shù)據(jù)集合屬性中存在點(diǎn)號(hào)(.)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-10-10
MongoDB入門教程之Windows下的MongoDB數(shù)據(jù)庫安裝圖解
這篇文章主要介紹了MongoDB入門教程之Windows下的MongoDB數(shù)據(jù)庫安裝圖解,本文還講解了MongoDB的基本操作,如insert、find、 update、remove等操作,需要的朋友可以參考下2014-08-08
MongoDB數(shù)據(jù)庫安裝部署及警告優(yōu)化
大家好,本篇文章主要講的是MongoDB數(shù)據(jù)庫安裝部署及警告優(yōu)化,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12

