redis储存实体类对象_Spring Boot (五): Redis缓存使用姿势盘点

本文详细介绍了如何在Spring Boot应用中使用Redis作为缓存,包括通过RedisTemplate操作Redis,自定义RedisTemplate以存储实体类对象,以及使用Spring Cache集成Redis进行方法级缓存。同时,文章探讨了Spring Session实现Session共享的配置和测试。
摘要由CSDN通过智能技术生成

7822e82bc6f59b6399c78cf23a6bc5b8.png

1. Redis 简介

Redis 是目前业界使用最广泛的内存数据存储。相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化。除此之外,Redis 还提供一些类数据库的特性,比如事务,HA,主从库。可以说 Redis 兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍 Redis 在 Spring Boot 中两个典型的应用场景。

2. Lettuce 简介

如果在 Java 应用中使用过 Redis 缓存,那么对 Jedis 一定不陌生, LettuceJedis 一样,都是连接 Redis Server 的客户端程序。Jedis 在实现上是直连 Redis Server,多线程环境下非线程安全,除非使用连接池,为每个 Jedis 实例增加物理连接。 Lettuce 基于 Netty 的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

3. Spring Boot 应用中使用方式

  • 直接通过 RedisTemplate 来使用
  • 使用 Spring Cache 集成 Redis
  • 通过 Spring SessionSession 共享

4. 工程实战

4.1 工程依赖 pom.xml 如下:

代码清单:spring-boot-redis/pom.xml

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </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>
    </dependency>
</dependencies>
  • spring-boot-starter-data-redis :在 Spring Boot 2.x 后底层不再是使用 Jedis ,而是换成了 Lettuce ,如图:
  • commons-pool2 : 用作 redis 连接池,如不引入启动会报错。
  • spring-session-data-redis : Spring Session 引入,用作共享 Session

f2c3a9b993dbe08bacf66474d3a0b0ee.png

4.2 配置文件 application.yml

代码清单:spring-boot-redis/src/main/resources/application.yml

server:
  port: 8080
  servlet:
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值