从 01 开始 从 01 开始
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 新闻合订本
    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档

晓林

程序猿,自由职业者,博主,英语爱好者,健身达人
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 新闻合订本
    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

    • SpringBoot 教程-尚硅谷

      • SpringBoot 课程介绍
      • Spring 和 SpringBoot
      • HelloWorld
      • 了解自动配置原理
      • 底层注解-@Configuration 详解
      • 底层注解-@Import 导入组件
      • 底层注解-@Conditional 条件装配
      • 原生配置文件引入-@ImportResource
      • 底层注解-配置绑定 @ConfigurationProperties
      • 自动配置原理
      • 自动配置流程
      • Lombok 简化开发
      • DevTools
      • Spring-Initailizr
      • 配置文件-Yaml 用法
      • Web 开发简介
      • web 开发-静态资源规则于定制化
      • 静态资源配置原理
      • Rest 映射及源码解析
      • 请求映射原理
      • 常用参数注解使用
      • MatrixVariable:矩阵变量
      • 各种类型参数解析原理
      • Servlet-API 参数解析原理
      • Model、Map 参数解析原理
      • 自定义对象参数绑定原理
      • 自定义 Converter 原理
      • 数据响应原理
      • 内容协商原理
      • 基于请求参数的内容原理
      • 自定义 MessageConverter 原理
      • Thymeleaf 初体验
      • web 实验-后台管理系统
      • web 实验-抽取公共页面
      • web 实验-遍历数据
      • 源码分析-视图解析器与视图
      • 拦截器-登录检查与静态资源放行
      • 拦截器的执行时机和原理
      • 单文件和多文件上传的使用
      • 文件上传原理
      • 错误处理机制
      • 错误处理-底层组件源码分析
      • 异常处理流程
      • 几种异常处理原理
      • Web 原生对象注入
      • 嵌入式 Servlet 容器
      • 定制化原理
      • 数据库场景的自动配置分析和整合测试
      • 自定义方式整合 Druid
      • 通过 starter 整合 Druid
      • 整合 Mybatis
      • 使用注解整合 Mybatis
      • 整合 MybatisPlus 操作数据库
      • MybatisPlus-列表分页展示
      • 整合 Redis
        • 引入依赖
        • 自动配置分析
        • 准备 Redis
        • 切换至 Jedis
        • 统计功能
        • 扩展
        • 源码
      • 单元测试-Junit5
      • 单元测试-断言机制
      • 单元测试-前置条件
      • 单元测试-嵌套测试
      • 单元测试-参数化测试
      • 指标监控-基本概念
      • 指标监控-配置 EndPoint
      • 指标监控-可视化
      • 原理解析-Profile 功能
      • 配置文件深入
      • 自定义 Starter
      • SpringApplication 初始化过程
      • SpringBoot 完整启动过程
  • Java
  • SpringBoot
  • SpringBoot 教程-尚硅谷
2023-08-22
目录

整合 Redis

# 550.整合 Redis

接下来我们试试整合 NoSQL,例如 Redis

由于本系列教程是 SpringBoot,如果不熟悉 Redis 的话,可以参考下 Redis 教程 (opens new window)

# 引入依赖

SpringBoot 已经提供了相关的 starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1
2
3
4

‍

# 自动配置分析

‍ 可以分析下其依赖:

‍

引入了 keyvalue 等操作数据的,以及 lettuce 这个客户端用来操作 Redis(基于 Netty)

在 SpringBoot 的自动配置类中,有一个叫做 RedisAutoConfiguration,就是配置了和 Redis 相关的:

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)  throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)  throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

配置属性的类 RedisProperties,就是会将 spring.redis 开头的属性绑定:

@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {

	/**
	 * Database index used by the connection factory.
	 */
	private int database = 0;

	/**
	 * Connection URL. Overrides host, port, and password. User is ignored. Example:
	 * redis://user:password@example.com:6379
	 */
	private String url;

        //..................
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

还引入了 LettuceConnectionConfiguration,这个就是客户端连接的配置;该配置会放入一个客户端资源 DefaultClientResources,以及 Lettuce 的连接工厂

@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(ClientResources.class)
DefaultClientResources lettuceClientResources() {
	return DefaultClientResources.create();
}

@Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class)
LettuceConnectionFactory redisConnectionFactory() {
	//.....
}
1
2
3
4
5
6
7
8
9
10
11

除此之外,还引入了 JedisConnectionConfiguration,这也是一个客户端工具,至于到底是用 Jedis 还是 Lettuce,就看引入了哪个依赖了,或者指定配置。 ‍ 在自动配置类中,还注入了 RedisTemplate,StringRedisTemplate。Redis 是通过 key-value 方式存储数据的,第一个 template 中,可以用 Object 来表示 key 和 value;而第二个 template,则是用于 key 和 value 都是 String 的情况(因为 String 的情况比较多)。 ‍

# 准备 Redis

读者可以使用本地的 Redis,或者使用云服务器厂商的 Redis(按量访问)。 ‍ 然后新增配置:

spring:
  redis:
    url: redis://localhost:6379/0
1
2
3

在测试类中中新增方法:

class LearnSpringBootWebAdminApplicationTests {

    @Autowired
    StringRedisTemplate redisTemplate;

  
    @Test
    void testRedis(){
       ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
       stringStringValueOperations.set("hello", "world");
       String hello = stringStringValueOperations.get("hello");
       log.info("hello:{}", hello);
    }

    //............
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

‍ 然后可以运行该测试方法,并且可以用其他 Redis 客户端来查看数据

# 切换至 Jedis

默认使用的是 lettuce,如何使用 Jedis 呢?

  1. 引入 Jedis 的依赖(版本号已经默认配置了)
  2. 去除 lettuce 的依赖
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

然后我们可以打印下工厂的类型:

class LearnSpringBootWebAdminApplicationTests {


    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Test
    void testRedis(){
         log.info("redis类型:{}", redisConnectionFactory.getClass());
    }

    //............
1
2
3
4
5
6
7
8
9
10
11
12

‍ 运行结果:

redis类型:class org.springframework.data.redis.connection.jedis.JedisConnectionFactory
1

除此之外,还可以对连接池信息进行配置,例如:

spring: 
  redis:
    url: redis://localhost:6379/0
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
1
2
3
4
5
6
7

# 统计功能

我们可以做个统计,例如访问了多少次/sql 请求,然后展示到页面上:

‍

我们新增一个拦截器:

package com.peterjxl.learnspringbootwebadmin.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component  // 将拦截器交给Spring管理
public class RedisUrlCountInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();   // 获取请求的url
        // 访问量加1
        redisTemplate.opsForValue().increment(uri);
        return true;    // 放行
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

‍ 然后讲拦截器加入到 SpringBoot 中:

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {


    @Autowired
    RedisUrlCountInterceptor redisUrlCountInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**") // 拦截所有请求,包括静态资源
                .excludePathPatterns("/", "/login", "/css/**", "/fonts/**", "/images/**", "/js/**", "/sql");

        registry.addInterceptor(redisUrlCountInterceptor)
                .addPathPatterns("/**") // 拦截所有请求,包括静态资源
                .excludePathPatterns("/", "/login", "/css/**", "/fonts/**", "/images/**", "/js/**");

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

注意,不能用 registry.addInterceptor(new RedisUrlCountInterceptor),因为用 new 的话,我们拦截器中的 StringRedisTemplate 就不会注入了 ‍ 接下来我们可以重启下项目,然后多访问一些页面,可以看到 Redis 中确实有这些数据:

接下来我们展示在首页中,首先在首页的 controller 中放入次数:

 @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String s = opsForValue.get("/main.html");
        String s1 = opsForValue.get("/sql");
        model.addAttribute("mainCount", s);
        model.addAttribute("sqlCount", s1);

        return "main";
    }
1
2
3
4
5
6
7
8
9
10
11

‍ 然后在首页中修改:

效果:

# 扩展

Filter 和 Interceptor 几乎都有同样的功能,用哪个好?

  1. Filter 是 Servlet 原生的 API ,没有 Spring 也能使用
  2. Interceptor 是 Spring 定义的接口,只能在 Spring 中使用,好处是可以使用 Spring 的功能(例如注入) ‍

# 源码

已将本文源码上传到 Gitee (opens new window) 或 GitHub (opens new window) 的分支 demo16,读者可以通过切换分支来查看本文的示例代码

上次更新: 2025/6/3 09:31:54
MybatisPlus-列表分页展示
单元测试-Junit5

← MybatisPlus-列表分页展示 单元测试-Junit5→

最近更新
01
新闻合订本 2025-10
10-31
02
2025 年 10 月记
10-30
03
用 AI 批量优化思源笔记排版
10-15
更多文章>
Theme by Vdoing | Copyright © 2022-2025 | 粤 ICP 备 2022067627 号 -1 | 粤公网安备 44011302003646 号 | 点击查看十年之约
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式