从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • 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完整启动过程
      • SpringBoot
  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • 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

‍

然后在首页中修改:

​​​​

‍

‍

效果:​

image​

‍

‍

‍

# 扩展

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

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

‍

# 源码

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

在GitHub上编辑此页 (opens new window)
上次更新: 2023/8/23 10:10:57
MybatisPlus-列表分页展示
单元测试-Junit5

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

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式