SpringBoot 整合MybatisPlus&MongoDB&Redis基础

后端 专栏收录该内容
14 篇文章 1 订阅

SpringBoot 整合MybatisPlus&MongoDB&Redis基础

持续更新…


初始化数据库

连接Redis,初始时无数据:

在这里插入图片描述
连接Mysql,初始数据状态:

数据库名Test,表名students
在这里插入图片描述

连接MongoDB,初始数据状态:

数据库名story,集合名story,均为空
在这里插入图片描述


项目搭建

整体项目结构:

在这里插入图片描述

依赖配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wu</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>project</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!-- Redis依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- MongoDB依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>org.wu.project.ProjectApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

MybatisPlus映射配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace = "org.wu.project.mapper.StudentMapper">
    <resultMap id="studentMap" type="org.wu.project.entity.Student">
        <id property="studentId" column="student_id"></id>
        <result property="studentName" column="student_name"></result>
        <result property="studentAge" column="student_age"></result>
        <result property="studentGrade" column="student_grade"></result>
    </resultMap>
    <insert id="addStudent">
        insert into students(student_id,student_name,student_age,student_grade)
         values(#{studentId},#{studentName},#{studentAge},#{studentGrade})
    </insert>
    <select id="findStudentById" parameterType="integer" resultMap="studentMap">
        select * from students
        where student_id = #{id}
    </select>
</mapper>

application.yml:

# 端口配置
server:
  port: 8888
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.123.188:3333/Test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: defaultDataSource
  redis:
    host: 192.168.123.188
    port: 6666
    timeout: 1000
    database: 0 # 选择存储数据库
  application:
    name: project
  data:
    mongodb:
      host: 192.168.123.188
      database: story
      port: 22222
mybatis-plus:
  mapper-locations: classpath:/mybatis/mappers/*.xml
  type-aliases-package: org.wu.project.entity

# sql日志信息控制台输出
logging:
  level:
    org.wu.project.mapper: debug
    org.wu.project.service: debug

StudentServce.java:

package org.wu.project.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.wu.project.entity.Student;
import org.wu.project.mapper.StudentMapper;

@Slf4j
@Service("studentServiceBean")
public class StudentService {
    private StudentMapper studentMapper;
    @Autowired
    @Qualifier("studentMapperBean")
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }
    private RedisTemplate redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.redisTemplate.setKeySerializer(new StringRedisSerializer());
        this.redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }
    /**
     * 增加学生
     * @param student
     */
    public void addStudent(Student student){
        studentMapper.addStudent(student);
    }
    /**
     * 通过学生id查找学生
     * 需要采用高并发思维来看待
     * 这里采用了双重校验锁方式
     * @param id
     * @return
     */
    public Student findStudentById(Integer id){
        // 先从Redis缓存获取数据,如果有则直接返回该数据,如果未找到则查询数据库,并将该数据放入Redis中
        // 一般的redis键的命名规范为:表名:主键名:主键值:字段名
        // Json数据规范为:表名:主键名:主键值 json字符串
        Object student = redisTemplate.opsForValue().get("students:student_id:"+id);
        if(student == null){
            synchronized(this.getClass()){
                student = redisTemplate.opsForValue().get("students:student_id:"+id);
                if(student == null){
                    log.debug(">>>>> Mysql返回数据… ");
                    Student temp = studentMapper.findStudentById(id);
                    redisTemplate.opsForValue().set("students:student_id:"+id,temp);
                    return temp;
                }
            }
        }
        log.debug(">>>>> Redis返回数据… ");
        return (Student)student;
    }
}

StoryService:

package org.wu.project.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.wu.project.entity.Story;

import org.springframework.data.mongodb.core.query.Query;
import java.util.List;
import java.util.regex.Pattern;

@Service("storyServiceBean")
public class StoryService {
    private MongoTemplate mongoTemplate;
    @Autowired
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    /**
     * 将数据存入MongoDB
     * @param story
     */
    public void addStory(Story story){
        // insert(): 若新增数据的主键已经存在,则会抛异常提示主键重复,不保存当前数据。可批处理
        // save(): 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
        mongoTemplate.insert(story);
    }
    /**
     * 查找Story集合的所有文档
     * @return
     */
    public List<Story> findAllStory(){
        return mongoTemplate.findAll(Story.class);
    }

    /**
     * 通过故事ID查找故事对象
     * @param id
     * @return
     */
    public List<Story> findStoryById(String id){
        Query query = new Query();
        // 多个条件则重复类似以下语句
        query.addCriteria(Criteria.where("_id").is(id));
        return mongoTemplate.find(query,Story.class,"story");
    }

    /**
     * 模糊查询story集合content内容
     * @param content
     * @return
     */
    public List<Story> findContent(String content){
        Pattern pattern = Pattern.compile(".*"+content+".*");
        Query query = new Query(Criteria.where("content").regex(pattern));
        return mongoTemplate.find(query,Story.class,"story");
    }
}

Student实体类:

package org.wu.project.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class Student implements Serializable {
    String studentId;
    String studentName;
    Integer studentAge;
    String studentGrade;
}

Story实体类:

package org.wu.project.entity;


import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoId;
@Data
@Document(collection = "story") // MongoDB集合名
public class Story {
    @MongoId // 这个是将作为MongoDB的_id
    private String storyId; // 故事判别码
    @Field("name") // 别名,即MongoDB的属性名
    private String storyName; // 故事名称
    @Field("content") // 别名,即MongoDB的属性名
    private String storyContent; // 故事内容
    private String author; // 故事作者
    private Integer chapter; // 故事章节
}

StudentController.java:

package org.wu.project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wu.project.entity.Student;
import org.wu.project.service.StudentService;

@RestController
public class StudentController {

    private StudentService studentService;

    @Autowired
    @Qualifier("studentServiceBean")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @PostMapping("/add/student")
    public boolean addStudent(Student student){
        try {
            studentService.addStudent(student);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    @GetMapping("/get/student")
    public String getStudentById(Integer id){
        return studentService.findStudentById(id).toString();
    }
}

StoryControlle.java:

package org.wu.project.controller;

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.RestController;
import org.wu.project.entity.Story;
import org.wu.project.service.StoryService;

@RestController
public class StoryController {
    private StoryService storyService;

    @Autowired
    public void setStoryService(StoryService storyService) {
        this.storyService = storyService;
    }
    @PostMapping("/add/story")
    public boolean addStory(Story story){
        try{
            this.storyService.addStory(story);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    @GetMapping("/get/stories")
    public String getStories(){
        return this.storyService.findAllStory().toString();
    }
    @GetMapping("/get/story/id")
    public String getStoryById(String id){
        return this.storyService.findStoryById(id).toString();
    }
    @GetMapping("/get/story/content")
    public String getContent(String content){
        return this.storyService.findContent(content).toString();
    }
}

  • 测试MySQL以及Redis

在这里插入图片描述
日志输出信息:

在这里插入图片描述

MySQL数据库信息,添加成功:

在这里插入图片描述

在这里插入图片描述
请求成功:

在这里插入图片描述
多次重复请求使用Redis缓存,有利于高并发:

在这里插入图片描述

  • 测试MongoDB

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查看MongoDB数据信息,添加成功:

在这里插入图片描述

在这里插入图片描述
查询故事内容中带有水滴两字的所有文档:

在这里插入图片描述



  • 0
    点赞
  • 2
    评论
  • 1
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 2 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:博客之星2020 设计师:CSDN官方博客 返回首页

打赏作者

一夜星尘

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值