SpringBoot整合Redis做缓存,实战分享(上)

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 我们都知道,把首页数据放到Redis里,能够加快首页数据的访问速度。但是我们要如何准确又快速的将 Redis 整合到自己的 SpringBoot2.x 项目中呢?今天阿粉就带大家爬一爬其中的门门道道。

Redis 介绍

Redis 使用了浪费流量的文本协议,但因为它数据存储在内存中的,相对而言,依然可以取得极高的访问性能。并且 Redis 是线程安全的。

RESP 就是 Redis 序列化协议的简称。它是一种直观的文本协议,优势在于实现异常简单,解析性能极好。

Redis 协议里面虽然有大量冗余的回车换行符,但是这不影响它成为技术领域非常受欢迎的一个文本协议。在技术领域,性能并不总是一切,还有简单性、易理解性和易实现性,这些都需要进行适当权衡。

Redis 基础数据结构

1、字符串:(缓存)

  • key:value

value 可以是对象转换成的 JSON 字符串,也可以是对象序列化后的二进制字符串

2、列表:(异步队列) 类似linkedlist

  • 右边进左边出:队列
  • 右边进右边出:栈

3、字典(哈希) 类似hashmap:数组+链表

不过rehash是渐进式hash策略

4、集合:(去重)

  • 无序 set:类似hashset
  • 有序 zset:类似SortedSet和HashMap的结合体,内部实现是跳跃列表

Lettuce

随着 Spring Boot2.x 的到来,支持的组件越来越丰富,也越来越成熟,其中对 Redis 的支持不仅仅是丰富了它的API,更是替换掉底层 Jedis 的依赖,取而代之换成了 Lettuce。

虽然 Lettuce 和 Jedis 的都是连接 Redis Server 的客户端程序,但是 Jedis 在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接。而 Lettuce 基于 Netty 的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

Lettuce是可扩展的Redis客户端,用于构建无阻塞的Reactive应用程序.

Luttuce官网:https://lettuce.io/

74.jpg

谷歌翻译后的页面是:

75.jpg

原来这玩意儿叫生菜,你别说,看着图标还真有点像。

76.jpg

实操

项目中使用的 SpringBoot2.x 实现,如果之前是 SpringBoot1.x 则需要注意,底层已经由 Jedis 升级成了 Lettuce 。

3.1、引入依赖

除去 SpringBoot 项目需要的 jar 包外,另外还需要引入 redis 相关的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

3.2、application.yml 配置文件

此处用到的 application.yml 文件,配置如下:

spring:
  redis:
    # Redis默认情况下有16个分片,这里配置具体使用的分片。默认是索引为0的分片
    database: 1
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    # Redis服务器连接密码(默认为空)
    password: mmzsblog
    # 连接超时时间(毫秒)
    timeout: 2000s
    # 配置文件中添加 lettuce.pool 相关配置,则会使用到lettuce连接池
    lettuce:
      pool:
        # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-wait: 60s
        # 连接池中的最大空闲连接 默认 8
        max-idle: 10
        # 连接池中的最小空闲连接 默认 0
        min-idle: 10
        # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-activ: 8

如果项目是由 SpringBoot1.x 升级到 SpringBoot2.x 的,要沿用 jedis 连接池配置时会用到配置 jedis 相关的属性:

# 配置文件中添加 jedis.pool 相关配置,则会使用到 jedis 连接池
    jedis:
      pool:
        max-active: 10
        max-idle: 8
        min-idle: 0
        max-wait: 60s

并且引用的 jar 包也需要调整:

<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>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

另外,这里再贴一下 Spring Boot 关于 RedisProperties 的所有配置项

# REDIS RedisProperties
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.jedis.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.lettuce.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of the Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs.
spring.redis.ssl=false # Whether to enable SSL support.
spring.redis.timeout= # Connection timeout.

3.3、自定义一个 RedisTemplate

这个看你自己,不自定义也不影响使用,只是说可能不那么顺手,所以阿粉习惯自定义一个。因为 Spring BootRedisAutoConfiguration 中默认配置了 RedisTemplate<Object, Object>StringRedisTemplate两个模板类,然而RedisTemplate<Object, Object>并未指定keyvalue的序列化器。

@Configuration
public class RestTemplateConfig {
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

3.4、Person 实体类

声明一个 Person 实体类:

/**
 * @author :created by mmzsblog
 * @date :created at 2020/06/23 16:41
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private static final long serialVersionUID = -8183942491930372236L;
    private Long userId;
    private String username;
    private String password;
}

3.5、测试

通过编写一个 UserController 来进行测试:

@RestController
public class UserController {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/set")
    public String set() {
        stringRedisTemplate.opsForValue().set("one", "1");
        // redisTemplate 保存的是字节序列,因为 RestTemplateConfig 自定义的时候指定了 key 和 value 的序列化器。
        redisTemplate.opsForValue().set("two", "2");
        redisTemplate.opsForValue().set("person", new Person(1L, "luffy", "123456789"));
        // 测试线程安全
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i -> {
            executorService.execute(() -> stringRedisTemplate.opsForValue().increment("num", 1));
        });
        return "Ok!";
    }
    @GetMapping("/get")
    public String get() {
        String one = stringRedisTemplate.opsForValue().get("one");
        if ("1".equals(one)) {
            System.out.println("key: one" + " || value: " + one);
        }
        Object two = redisTemplate.opsForValue().get("two");
        if ("2".equals(two.toString())) {
            System.out.println("key: two" + " || value: " + two);
        }
        Person user = (Person) redisTemplate.opsForValue().get("person");
        if ("luffy".equals(user.getUsername())) {
            System.out.println("key: person" + " || value: " + user);
        }
        return "Ok!";
    }
}

用RedisDesktopManager工具查看,数据如下:

StringRedisTemplate 设置的键值是String类型的:

77.jpg

RedisTemplate 设置的键值是二进制的字节流形式存储的,从截图中的 [Binary] 标识符也能看出:

78.jpg

自定义的 RedisTemplateStringRedisTemplate 并不会有什么冲突,想用 String 存储还是二进制的字节流形式存储完全取决于你自己。


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
打赏
0
0
0
0
150
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
26 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
Redis--缓存击穿、缓存穿透、缓存雪崩
缓存击穿、缓存穿透和缓存雪崩是Redis使用过程中可能遇到的常见问题。理解这些问题的成因并采取相应的解决措施,可以有效提升系统的稳定性和性能。在实际应用中,应根据具体场景,选择合适的解决方案,并持续监控和优化缓存策略,以应对不断变化的业务需求。
54 29
缓存与数据库的一致性方案,Redis与Mysql一致性方案,大厂P8的终极方案(图解+秒懂+史上最全)
缓存与数据库的一致性方案,Redis与Mysql一致性方案,大厂P8的终极方案(图解+秒懂+史上最全)
|
3天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
17 0
|
3天前
|
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
12 0
Idea创建SpringBoot多模块项目
我们可以定义一个维度,以此来划分模块,例如上述商城、可以划分成商品、库存和订单模块。也可以目录结构分层,`Controller`层,只不过没人这样做。这样就引申出了下一个问题`拆分策略`。
999 0
Idea创建SpringBoot多模块项目
传统maven项目和现在spring boot项目的区别
Spring Boot:传统 Web 项目与采用 Spring Boot 项目区别
560 0
传统maven项目和现在spring boot项目的区别
创建springboot项目的基本流程——以宠物类别为例
创建springboot项目的基本流程——以宠物类别为例
173 0
创建springboot项目的基本流程——以宠物类别为例
自定义SpringBoot项目的启动Banner
``Banner``是``SpringBoot``框架一个特色的部分,其设计的目的无非就是一个框架的标识,其中包含了版本号、框架名称等内容,既然``SpringBoot``为我们提供了这个模块,它肯定也是可以更换的这也是``Spring``开源框架的设计理念。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等