2流高手速成记(之四):SpringBoot整合redis及mongodb

2023-05-16

🚀 优质资源分享 🚀

学习路线指引(点击解锁)知识定位人群定位
🧡 Python实战微信订餐小程序 🧡进阶级本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。
💛Python量化交易实战💛入门级手把手带你打造一个易扩展、更安全、效率更高的量化交易系统

最近很忙,好不容易才抽出了时间,咱们接上回

上次我们主要讲了如何通过SpringBoot快速集成mybatis/mybatis-plus,以实现业务交互中的数据持久化,而这一切都是基于关系型数据库(SQL)实现的

本节我们来把关注点转向NoSQL

NoSQL的概念:

NoSQL,泛指非关系型的数据库。随着互联网web2.0网站的兴起,传统的关系数据库在处理web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,出现了很多难以克服的问题,而非关系型的数据库则由于其本身的特点得到了非常迅速的发展。NoSQL数据库的产生就是为了解决大规模数据集合多重数据种类带来的挑战,特别是大数据应用难题。(——来自百度百科)

得益于其直接基于内存的存储方式,NoSQL的访问速度可以用“飞快”两个字来形容

在生产环境中,NoSQL常常配合传统关系型数据库来使用,比如构建一层数据缓存来极大的提升数据的读取速度

NoSQL在日常业务的驱动之下,逐渐发展出几个主要的类别:键值对数据库、文档型数据库、列存储数据库以及图形化数据库

这4类NoSQL数据库之中最具代表性的,当属键值对数据库类别下的Redis,以及文档型数据库的Mongodb,本节我们重点关注这两个产品在SpringBoot下的整合及使用

照惯例先上项目结构:

一、先看Redis的使用:

1. 在pom.xml中添加Redis相关依赖项

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
 <artifactId>spring-boot-starter-data-redisartifactId>
 dependency>
 <dependency>
 <groupId>org.apache.commonsgroupId>
 <artifactId>commons-pool2artifactId>
 dependency>

2. 在application.properties中添加Redis的相关配置

# redis相关设置
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
# redis默认基于lettuce内核
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

这里关于lettuce内核有必要给大家解释一下:

在SpringBoot2.x版本之前,其集成的默认Redis库是Jedis,而在2.x版本之后才改为默认基于Lettuce

Jedis默认和Redis直连,为非线程安全模型,并发环境下需要池化使用

而Lettuce则是线程安全的,并发环境下可以通过一个实例搞定

当然,你也可以在SpringBoot2.x环境下依然使用Jedis,只需要把 spring.redis.lettuce 相关配置替换为 spring.redis.jedis 即可

更多内容大家感兴趣可以从网上查阅相关资料,这里推荐一篇:https://blog.csdn.net/kenkao/article/details/127085687

3. 新建 service/RedisService 接口及其实现类 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 ops = redis.opsForValue();
 ops.set(key, val);
 }

 public String get(String key){
 ValueOperations ops = redis.opsForValue();
 return ops.get(key);
 }
}

我们在Service中自动装载一个StringRedisTemplate实例,而后通过其创建Operation对象,进行可以进行各种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进行结果验证

通过RDM查看写入redis的数据:

之后是读操作:

至此我们便完成了SpringBoot中集成Redis的操作

二、MongoDB的使用

1. 首先还是先添加MongoDB相关依赖项

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
 <artifactId>spring-boot-starter-data-mongodbartifactId>
 dependency>

2. 然后是添加MongoDB相关配置

# mongodb相关设置
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

各注释项内容依次是:身份验证库、目标数据库、主机地址、端口以及用户名和口令

由于我没有设置用户名和口令,所以直接注释掉这两项

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 findByNameIs(String name);
 Person findByIdIs(int id);
 Person findByIdAndName(int id, String name);
 Person findByIdOrName(int id, String name);
}

这里出现了非常神奇的一幕:

我们仅需要提供一个接口,而不用提供具体实现!

仅凭方法的命名规范,spring.data.mongodb就能自行分析开发者的意图,进行补全内部的业务逻辑!

而同样具备这种智能化能力的还有spring.jpa,后者也是一种非常便捷高效数据库驱动,与mybatis属于同类产品

顺便也给大家提供一份方法命名规范清单,请各位在方法命名时务必遵循以下规则:

| 关键字 | 方法命名 | 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接口定义及实现

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实现

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的实现不再做过多赘述,还是老一套

6. Postman验证结果

向mongodb中写入一条数据

之后是几种读取操作:

不论是与或操作,我们都可以得到正确的结果

到这里,mongodb的集成就完成了

三、基于Redis实现Session配置共享

这部分纯属附送内容 ^ ^

前边我们已经完成了对Redis的集成操作,而基于Redis我们可以非常便捷的实现服务端Session配置的跨节点共享

服务端Session默认存储在本地,而当我们需要多台服务器共享一套Session配置时,本地化Session便不再满足我们的要求

而基于SpringSession,我们可以完全透明化的替换掉默认的Session容器,直接改为基于Redis存储

1. 添加相关依赖

        
        <dependency>
            <groupId>org.springframework.sessiongroupId>
 <artifactId>spring-session-data-redisartifactId>
 dependency>

2. 新增两个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);
 }

就完事儿了?对!就完事儿了 ^ ^,超级简单是吧?

到此,我们就完成了SpringBoot对于Redis以及MongoDB的集成和使用

非常感慨于SpringBoot框架设计的智能化及人性化,就像身边有一哥们说的:这年头,框架都能直接听懂人话了!哈哈

下一节我们讨论一个生产环境下常常面临的实际问题——安全管理

Shiro框架要来咯!敬请期待——

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

2流高手速成记(之四):SpringBoot整合redis及mongodb 的相关文章

随机推荐

  • Api Generator Plus & Copy as curl 自动上传YApi接口

    Api Generator Plus 插件能够一键自动上传YApi接口 xff1b 一键生成 curl 命令 fetch方法 axios方法 快速开始 1 打开插件管理 xff0c 搜索api generator plus xff0c 安装
  • centos6升级到7.2-----2023年

    CentOS 6 升级到 CentOS 7 准确的说 xff0c 是从 CentOS 6 5 先升级到 CentOS 7 2 只有 6 5 以上版本才能这么升级 xff0c 而且最高只能升级到 7 2 现在的问题是官网已经不再维护 Cent
  • 怎么在IDEA中配置power shell

    第一步 xff1a 接下来 xff0c 在步骤3那里找到黄色方框里面的powershell exe文件 在点击OK之后 xff0c 你就能看到以下 说明 xff0c 已经配置成功了
  • 【数据结构】——二叉树的创建详解

    之前有篇文章概要的叙述了一下关于二叉树的创建 xff0c 参考博文二叉树的c语言创建但是很不全面 xff0c 这篇文章就让我们来好好探讨一下关于二叉树的创建吧 首先 xff0c 我们要做一些前期准备 xff0c 有关于本课二叉树的结点信息和
  • Fortify--安装与使用

    Fortify是Micro Focus旗下AST xff08 应用程序安全测试 xff09 产品 xff0c 其产品组合包括 xff1a Fortify Static Code Analyzer提供静态代码分析器 xff08 SAST xf
  • [web安全]burpsuite抓取微信公众号、小程序数据包

    最近在接触微信公众号和微信小程序的渗透 xff0c 用过模拟器 xff0c 也直接在手机上设置代理 xff0c 都遇到各种问题 xff0c 用起来很不舒心 记录遇到的一些问题 xff0c 帮助和我一样踩过坑的 xff0c 亲测好用 IE浏览
  • 安全-开源项目安全检查规范

    有些公司为了提高在IT圈的技术知名度 xff0c 增加行业影响力 xff0c 一些技术会定期将非核心业务源代码以公司级名义上传到源码开源平台 xff0c 如GitHub 特此输出相关的安全检查规范 第一条 开源的代码项目可以为通用的解决方案
  • 安全-系统上线安全检查规范

    现在各个公司都开始重视安全 xff0c 不仅仅是因为国家开始重视安全 xff0c 而是安全漏洞一旦暴露 xff0c 被有心之人发现进行破坏 xff0c 损失将无法估量 xff1b 比如 xff1a 前端时间拼多多优惠券事件 安全测试是一项比
  • 应用安全测试技术DAST、SAST、IAST对比分析-持续更新

    应用安全测试技术DAST SAST IAST对比分析 持续更新 版权来源 xff1a 安全牛首发文章 xff0c 本文仅补充完善 一 全球面临软件安全危机 我们即将处于一个软件定义一切的时代 xff0c 这是 一个最好的时代 xff0c 也
  • Python中函数和方法的区别

    简单总结 xff1a 与类和实例无绑定关系的function都属于函数 xff08 function xff09 xff1b 与类和实例有绑定关系的function都属于方法 xff08 method xff09 首先摒弃错误认知 并不是类
  • 九宫格,二十五宫格,甚至八十一宫格 技巧

    九宫格 二十五宫格 甚至八十一宫格 只要是奇数的平方宫格者能做到横格相加 坚格相加 斜格相加得数相同 而偶数的宫格只有十六宫格有些规律 下面是三宫格 五宫格 七宫格 九宫格图 填写技巧 第一行中间填1 xff0c 右上没有的 xff0c 就
  • python 编写输出到csv

    def test write self fields 61 fields append orderCode with open r 39 test001 csv 39 39 a 39 newline 61 34 34 as f writer
  • Vagrant 共享目录出现 mount:unknown filesystem type ‘vboxsf‘

    环境 xff1a Windows 10 VirtualBox 7 0 6 Vagrant 2 3 4 错误如下 xff1a 61 61 gt default Attempting graceful shutdown of VM 61 61
  • 利用python进行企业微信机器人自动发送消息

    def test 004 robot self headers 61 34 Content Type 34 34 text plain 34 s 61 34 卖品 xff0c 打印码 xff1a 验证码 34 format str prin
  • js修改页面hidden属性

    想获取这个value的值 xff0c 但是看其是个input标签 xff0c 他的type属性是hidden 也就是只能定位 xff0c 不能对其操作 xff0c 想要通过元素的 get attribute 34 value 34 是不可能
  • mybatis的多表查询(一对一,一对多,多对多)

    mybatis多表查询 表之间的关系有几种 xff1a 一对多 多对一 一对一 多对多 举例 xff1a 用户和订单就是一对多 订单和用户就是多对一 一个用户可以下多个订单 多个订单属于同一个用户 人和身份证号就是一对一 一个人只能有一个身
  • 8款纯CSS3搜索框

    效果如下 xff1a 代码实现如下 xff1a span class token doctype lt DOCTYPE html gt span span class token tag span class token tag span
  • ViewBinding和DataBinding的理解和区别

    之前一直把ViewBinding当成了DataBinding xff0c 直到最近的学习中才发现他们不是一个东西 于是写下这篇笔记帮助理解和区分他们俩 一 ViewBinding 1 什么是ViewBinding 先来看看官方是怎么说的 通
  • Android KeyStore的使用

    在我们App开发过程中 xff0c 可能会涉及到一些敏感和安全数据需要加密的情况 xff0c 比如登录token的存储 我们往往会使用一些加密算法将这些敏感数据加密之后再保存起来 xff0c 需要取出来的时候再进行解密 此时就会有一个问题
  • 2流高手速成记(之四):SpringBoot整合redis及mongodb

    x1f680 优质资源分享 x1f680 学习路线指引 xff08 点击解锁 xff09 知识定位人群定位 x1f9e1 Python实战微信订餐小程序 x1f9e1 进阶级本课程是python flask 43 微信小程序的完美结合 xf