SpringBoot集成Redis


根據學生 id 查詢學生的功能,先從 redis 緩存中查找,如果找不到,再從數據庫中查找,然后放到 redis 緩存中

一、通過 MyBatis 逆向工程生成實體 bean 和數據持久層

具體過程看之前寫的

二、在 pom.xml 文件中添加 redis 依賴

完整的pom文件

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.md</groupId>
	<artifactId>04-redis</artifactId>
	<version>1.0.0</version>

	<name>04-redis</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


		<!--redis依賴-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.0</version>
		</dependency>

		<!--mysql依賴-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</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>

	<build>
		<!--加載mapper.xml文件-->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>

		<plugins>

			<!--mybatis 代碼自動生成插件-->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.6</version>
				<configuration>
					<!--配置文件的位置-->
					<configurationFile>GeneratorMapper.xml</configurationFile>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

三、Spring Boot 核心配置文件

根據自己的情況進行修改

#配置內嵌 Tomcat 端口號
server.port=9090
#配置項目上下文根
server.servlet.context-path=/


#用的mysql5.7

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot

spring.datasource.username=root
spring.datasource.password=123456


#配置 redis 連接信息
spring.redis.host=192.168.52.130
spring.redis.port=6379
spring.redis.password=123456

四、啟動 redis 服務

  1. 先關閉防火牆:systemctl stop firewalld
  2. 根據如下命令啟動即可
  3. 還得先設置密碼,在redis的配置文件redis.conf中有個參數,requirepass  這個就是配置redis訪問密碼的參數,例:requirepass 123456,然后重啟就生效了

五、RedisController類

package com.md.web;


import com.md.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author md
 * @Desc
 * @date 2020/10/24 15:50
 */

@RestController
public class RedisController {

    @Autowired
    private StudentService studentService;


    @GetMapping(value = "/students")
    public Object allStudentCount(){
        Long i = studentService.queryAllStudentCount();
        return "學生的總人數為:"+i;
    }

}

六、StudentService 接口及實現

Spring Boot 將自動配置 RedisTemplate,在需要操作 redis 的類中注入 redisTemplate 即可

Spring Boot 幫我們注入 RedisTemplate 類,泛型里面只能寫 <String, String>、<Object, Object> 或者什么都不寫

重點看注釋

package com.md.service;


/**
 * @author md
 * @Desc
 * @date 2020/10/24 15:53
 */

public interface StudentService {

    Long queryAllStudentCount();
}



package com.md.service.impl;

import com.md.mapper.StudentMapper;
import com.md.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author md
 * @Desc
 * @date 2020/10/24 15:57
 */
@Service
public class StudentServiceImpl implements StudentService {


    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public Long queryAllStudentCount() {

        // 設置redisTemplate對象key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 從redis緩存中獲取總人數
        Long allStudentCount = (Long) redisTemplate.opsForValue().get("allStudentCount");

        // 判斷redis中是否存在數據
        if(null == allStudentCount){
            // 如果為空,就去數據庫中進行查詢
            allStudentCount = studentMapper.selectAllStudentCount();
            // 並且把查詢到的數據放入大redis中
            redisTemplate.opsForValue().set("allStudentCount",allStudentCount,15, TimeUnit.SECONDS);
        }

        return allStudentCount;

    }
}

七、StudentMapper接口及映射文件

直接在自動生成的文件中添加自定義的功能就可以了

Long selectAllStudentCount();

mapper文件中
 <select id="selectAllStudentCount" resultType="java.lang.Long">
    select
      count(*)
    from
      t_student
  </select>

八、啟動類 Application

添加掃描數據持久層的注解並指定掃描包

package com.md;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.md.mapper")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

九、讓 Student 類實現序列化接口(可選)

在類名上 Alt + 回車,如果沒有提示生成序列化 id,那么需要做如下的配置

然后就可以使用了

十、啟動測試

也可以在這里查看

由於設置了時間,會自動銷毀


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM