Dark Horse Programmer Redis Study Notes--Redis Basics

write first

  • For the best reading experience, please go to my personal blog to view this article: https://cyborg2077.github.io/2022/10/21/RedisBasic/

Getting to know Redis

Redis is a key-value NoSQL database, here are two keywords

  • key-value
  • NoSQL

Among them 键值型, the data stored in Redis is stored in the form of Key-Value key-value pairs, and Value can be in various forms, such as strings, values ​​or even Json

NoSQL is a database that is very different from traditional relational databases.

Know NoSQL

NoSqlCan be translated as Not Only Sql (not just SQL), or No Sql (non-Sql) database. It is a special database that is very different from traditional relational databases, so it is also called 非关系型数据库.

structured and unstructured

Traditional relational databases are structured data. Each table has strict constraint information when it is created, such as field name, field data type, field constraints, etc. The inserted data must follow these constraints

On the other hand, NoSQL has no restrictions on the database format, which can be key-value type, document type, or even graph format.

Association and non-association

There are often associations between tables in traditional databases. For example, foreign key constraints
and non-relational databases do not have association relationships. To maintain relationships, either rely on business logic in the code or coupling between data

{
  id: 1,
  name: "张三",
  orders: [
    {
       id: 1,
       item: {
	 id: 10, title: "荣耀6", price: 4999
       }
    },
    {
       id: 2,
       item: {
	 id: 20, title: "小米11", price: 3999
       }
    }
  ]
}

For example, to maintain the relationship between Zhang San and two mobile phone orders here, we have to redundantly save these two products in Zhang San's order document, which is not elegant enough, so it is recommended to use business logic to maintain the relationship

inquiry mode

Traditional relational databases will query based on Sql statements, and the syntax has a unified standard

SELECT id, age FROM tb_user WHERE id = 1

The query syntax of different non-relational databases varies greatly

Redis:  get user:1
MongoDB: db.user.find({_id: 1})
elasticsearch:  GET http://localhost:9200/users/1

affairs

Traditional relational databases can meet the ACID principles of transactions (atomicity, consistency, independence, and durability)
and non-relational databases do not support transactions, or cannot guarantee the characteristics of ACID, and can only achieve cost consistency

Summarize

SQL NoSQL
data structure Structured unstructured
data association Relational unrelated
inquiry mode SQL query non-SQL
transaction characteristics ACID BASE
storage method disk Memory
Scalability vertical level
scenes to be used 1) The data structure is fixed
2) The requirements for consistency and security are not high
1) The data structure is not fixed
2) Related businesses have high requirements for data security and consistency
3) Performance requirements
  • storage method
    • Relational databases are based on disk storage, and there will be a lot of disk IO, which will have a certain impact on performance
    • For non-relational databases, their operations are more dependent on memory to operate, the read and write speed of memory will be very fast, and the performance will naturally be better
  • Scalability
    • The relational database cluster mode is generally master-slave, and the master-slave data is consistent, which plays the role of data backup, which is called vertical expansion.
    • Non-relational databases can split data and store it on different machines, which can save massive amounts of data and solve the problem of limited memory size. It's called horizontal scaling.
    • Relational databases cause a lot of trouble for data query because of the relationship between tables.

Meet Redis

Redis was born in 2009. Its full name is Remote Dictionary Server. It is a memory-based key-value NoSQL database.

feature:

  • Key-value (Key-Value) type, Value supports a variety of different data structures, rich in functions
  • Single-threaded, each command is atomic
  • Low latency, fast (memory based, IO multiplexing, good encoding)
  • Support data persistence
  • Support master-slave cluster and shard cluster
  • Support multilingual clients

Author: Antirez

Redis official website: https://redis.io/

Install Redis

Regarding the installation of Redis, I have made a detailed description in the previous article, so I won’t go into details here

{% link Getting started with Redis, https://cyborg2077.github.io/2022/10/17/ReggieRedis/, https://pic1.imgdb.cn/item/6335135c16f2c2beb100182d.jpg %}

Redis desktop client

After installing Redis, we can operate Redis to realize CRUD of data. This requires the use of Redis clients, including:

  • command line client
  • Graphical desktop client
  • programming client

Redis command line client

After the Redis installation is complete, it comes with a command line client: redis-cli, which can be used as follows:

redis-cli [options] [commonds]

Among the common options are:

  • -h 127.0.0.1: Specify the IP address of the redis node to connect to, the default is 127.0.0.1
  • -p 6379: Specify the port of the redis node to be connected, the default is 6379
  • -a 123321: Specify the access password of redis

The commonds are Redis operation commands, for example:

  • ping: Do a heartbeat test with the redis server, and the server will return `pong normally

Graphical desktop client

Installation package: https://github.com/lework/RedisDesktopManager-Windows/releases

Redis has 16 warehouses by default, numbered from 0 to 15. The number of warehouses can be set through the configuration file, but it does not exceed 16, and the warehouse name cannot be customized.

If you are connecting to the Redis service based on redis-cli, you can use the select command to select the database:

# 选择0号数据库
select 0

Redis common commands

Redis is a typical key-value database, the key is generally a string, and the value contains many different data types

Redis common commands

Commonly used general commands are as follows

Order describe
KEYs pattern Find all keys matching the given pattern
EXISTs key Check if the given key exists
TYPE key Returns the type of the value stored by the key
TTL key Returns the remaining time to live (TTL, time to live) of the given key in seconds
DEL key This command is used to delete the key when the key exists
  • KEYS: View all keys matching the template
    • It is not recommended to use it on production environment devices, because Redis is single-threaded, and it will block other commands when executing queries. When the amount of data is large, using KEYS for fuzzy queries is very inefficient.
  • DEL: delete a specified key
    • You can also delete multiple keys, DEL name age, both name and age will be deleted
  • EXISTS: Determine whether the key exists
    • EXISTS name, returns 1 if it exists, and returns 0 if it does not exist
  • EXPIRE: Set a validity period for a key, and the key will be automatically deleted when the validity period expires
    • EXPIRE name 20, set a validity period of 20 seconds for the name, and it will be automatically deleted when it expires
  • TTL: View the remaining validity period of a key (Time-To-Live)
    • TTL name, check the remaining validity period of name, if no validity period is set, return -1

String type

The String type, that is, the string type, is the simplest storage type in Redis.
Its value is a string, but it can be divided into three types according to the format of the string.

  • string: normal string
  • int: Integer type, can do self-increment and self-decrement operations
  • float: Floating-point type, which can perform self-increment and self-decrement operations
    No matter what format it is, the bottom layer is stored in the form of byte array, but the encoding method is different, and the maximum space of the string type cannot exceed 512M

String common commands

The common commands of String are

Order describe
SET Add or modify an existing key-value pair of String type
GET Get the value of String type according to the key
MOST Add multiple key-value pairs of String type in batches
MGET Get multiple values ​​of String type according to multiple keys
INCR Increment an integer key by 1
INCRBY Let an integer key auto-increment and specify the step value, for example: incrby num 2, let the num value auto-increment by 2
INCRBYFLOAT Increment a floating-point number with a specified step value
SETNX Add a key-value pair of String type, provided that the key does not exist, otherwise it will not be executed, which can be understood as a real increase
SEVEN Add a key-value pair of String type and specify the validity period

Key structure

  • Redis does not have a concept similar to Table in MySQL, so how do we distinguish between different types of Keys?
  • For example: you need to store user and product information in Redis. There is a user whose id is 1, and a product whose id happens to be 1. If the id is used as the key at this time, there will be a conflict. What should I do?
  • We can distinguish by adding a prefix to the key, but this prefix is ​​not added casually, there are certain specifications
    • The key of Redis allows multiple words to form a hierarchical structure, :separated by multiple words, the format is as follows
    项目名:业务名:类型:id
    
    • This format is not fixed, you can delete/add entries according to your own needs, so that we can distinguish data of different data types, thereby avoiding key conflicts
    • For example, our project is called reggie, and there are two different types of data, user and dish. We can define key like this
      • User-related keys:reggie:user:1
      • dish related key:reggie:dish:1
  • If value is a Java object, such as a User object, you can serialize the object into a JSON string and store it
KEY VALUE
reggie:user:1 {“id”:1, “name”: “Jack”, “age”: 21}
reggie:dish:1 {"id": 1, "name": "Sturgeon Hot Pot", "price": 4999}
  • And in the desktop client of Redis, the same prefix will also be used as the hierarchical structure, so that the data looks hierarchical and the relationship is clear

Hash type

  • Hash type, also called hash, where value is an unordered dictionary, similar to the HashMap structure in Java
  • The String structure is stored after serializing the object into a JSON string, which is very inconvenient when we want to modify the value of an attribute of the object
KEY VALUE
reggie:user:1 {“id”:1, “name”: “Jack”, “age”: 21}
reggie:dish:1 {"id": 1, "name": "Sturgeon Hot Pot", "price": 4999}
  • The Hash structure can store each field in the object independently, and can do CRUD for a single field
KEY VALUE
field value
reggie:user:1 name Jack
age  21

reggie:user:2
name  Rose
age  18
  • Common commands for Hash are
Order describe
HSET key field value Add or modify the value of the field of the hash type key
HGET key field Get the field value of a hash type key
HMSET Batch add the field values ​​of multiple hash type keys
HMGET Get the field values ​​of multiple hash type keys in batches
HGETALL Get all fields and values ​​in a hash type key
HKEYS Get all the fields in a hash type key
HINCRBY Let the field value of a hash type key auto-increment and specify the step size
HSETNX Add a field value of a hash type key, provided that the field does not exist, otherwise it will not be executed

List type

  • Redis中的List类型与Java中的LinkedList类似,可以看做是一个双向链表结构。既可以支持正向检索和也可以支持反向检索。

  • 特征也与LinkedList类似:

    • 有序
    • 元素可以重复
    • 插入和删除快
    • 查询速度一般
  • 常用来存储一个有序数据,例如:朋友圈点赞列表,评论列表等。

  • List的常见命令有:

命令 描述
LPUSH key element … 向列表左侧插入一个或多个元素
LPOP key 移除并返回列表左侧的第一个元素,没有则返回nil
RPUSH key element … 向列表右侧插入一个或多个元素
RPOP key 移除并返回列表右侧的第一个元素
LRANGE key star end 返回一段角标范围内的所有元素
BLPOP和BRPOP 与LPOP和RPOP类似,只不过在没有元素时等待指定时间,而不是直接返回nil

Set类型

  • Redis的Set结构与Java中的HashSet类似,可以看做是一个value为null的HashMap。因为也是一个hash表,因此具备与HashSet类似的特征:
    • 无序
    • 元素不可重复
    • 查找快
    • 支持交集、并集、差集等功能
  • Set的常见命令有:
命令 描述
SADD key member … 向set中添加一个或多个元素
SREM key member … 移除set中的指定元素
SCARD key 返回set中元素的个数
SISMEMBER key member 判断一个元素是否存在于set中
SMEMBERS 获取set中的所有元素
SINTER key1 key2 … 求key1与key2的交集
SUNION key1 key2 … 求key1与key2的并集
SDIFF key1 key2 … 求key1与key2的差集

{% note info no-icon %}
练习题:

  1. 将下列数据用Redis的Set集合来存储:
  • 张三的好友有:李四、王五、赵六
127.0.0.1:6379> sadd zhangsan lisi wangwu zhaoliu
(integer) 3
  • 李四的好友有:王五、麻子、二狗
127.0.0.1:6379> sadd lisi wangwu mazi ergou
(integer) 3
  1. 利用Set的命令实现下列功能:
  • 计算张三的好友有几人
127.0.0.1:6379> scard zhangsan
(integer) 3
  • 计算张三和李四有哪些共同好友
127.0.0.1:6379> sinter zhangsan lisi
1) "wangwu"
  • 查询哪些人是张三的好友却不是李四的好友
127.0.0.1:6379> sdiff zhangsan lisi
1) "zhaoliu"
2) "lisi"
  • 查询张三和李四的好友总共有哪些人
127.0.0.1:6379> sunion zhangsan lisi
1) "wangwu"
2) "zhaoliu"
3) "ergou"
4) "lisi"
5) "mazi"
  • 判断李四是否是张三的好友
127.0.0.1:6379> sismember zhangsan lisi
(integer) 1
  • 判断张三是否是李四的好友
127.0.0.1:6379> sismember lisi zhangsan
(integer) 0
  • 将李四从张三的好友列表中移除
127.0.0.1:6379> srem zhangsan lisi
(integer) 1

{% endnote %}

SortedSet类型

  • Redis的SortedSet是一个可排序的set集合,与Java中的TreeSet有些类似,但底层数据结构却差别很大。SortedSet中的每一个元素都带有一个score属性,可以基于score属性对元素排序,底层的实现是一个跳表(SkipList)加 hash表。
  • SortedSet具备下列特性:
    • 可排序
    • 元素不重复
    • 查询速度快
  • 因为SortedSet的可排序特性,经常被用来实现排行榜这样的功能。
  • SortedSet的常见命令有:
命令 描述
ZADD key score member 添加一个或多个元素到sorted set ,如果已经存在则更新其score值
ZREM key member 删除sorted set中的一个指定元素
ZSCORE key member 获取sorted set中的指定元素的score值
ZRANK key member 获取sorted set 中的指定元素的排名
ZCARD key 获取sorted set中的元素个数
ZCOUNT key min max 统计score值在给定范围内的所有元素的个数
ZINCRBY key increment member 让sorted set中的指定元素自增,步长为指定的increment值
ZRANGE key min max 按照score排序后,获取指定排名范围内的元素
ZRANGEBYSCORE key min max 按照score排序后,获取指定score范围内的元素
ZDIFF、ZINTER、ZUNION 求差集、交集、并集

{% note warning no-icon %}
注意:所有的排名默认都是升序,如果要降序则在命令的Z后面添加REV即可,例如:

  • 升序获取sorted set 中的指定元素的排名:ZRANK key member
  • 降序获取sorted set 中的指定元素的排名:ZREVRANK key memeber
    {% endnote %}

{% note info no-icon %}

  • 练习题:
    • 将班级的下列学生得分存入Redis的SortedSet中:
    • Jack 85, Lucy 89, Rose 82, Tom 95, Jerry 78, Amy 92, Miles 76
    127.0.0.1:6379> zadd stu 85 Jack 89 Lucy 82 Rose 95 Tom 78 Jerry 92 Amy 76 Miles
    (integer) 7
    
    • 并实现下列功能:
      • 删除Tom同学
      127.0.0.1:6379> zrem stu Tom
      (integer) 1
      
      • 获取Amy同学的分数
      127.0.0.1:6379> zscore stu Amy
      "92"
      
      • 获取Rose同学的排名
      127.0.0.1:6379> zrank stu Rose
      (integer) 2
      
      • 查询80分以下有几个学生
      127.0.0.1:6379> zcount stu 0 80
      (integer) 2
      
      • 给Amy同学加2分
      127.0.0.1:6379> zincrby stu 2 Amy
      "94"
      
      • 查出成绩前3名的同学
      127.0.0.1:6379> zrange stu 0 2
      1) "Miles"
      2) "Jerry"
      3) "Rose"
      
      • 查出成绩80分以下的所有同学
      127.0.0.1:6379> zrangebyscore stu 0 80
      1) "Miles"
      2) "Jerry"
      

{% endnote %}

Redis的Java客户端

  • 目前主流的Redis的Java客户端有三种
    • Jedis和Lettuce:这两个主要是提供了Redis命令对应的API,方便我们操作Redis,而SpringDataRedis又对这两种做了抽象和封装,因此我们后期会直接以SpringDataRedis来学习。
    • Redisson:是在Redis基础上实现了分布式的可伸缩的java数据结构,例如Map、Queue等,而且支持跨进程的同步机制:Lock、Semaphore等待,比较适合用来实现特殊的功能需求。

Jedis客户端

快速入门

  • 使用Jedis的步骤
    1. 导入Jedis的maven坐标
    <!--jedis-->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.7.0</version>
    </dependency>
    <!--单元测试-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>
    
    1. 建立连接
      新建一个单元测试类
    private Jedis jedis;
    
    @BeforeEach
    void setUp() {
        //1. 建立连接
        jedis = new Jedis("101.42.225.160", 6379);
        //2. 设置密码
        jedis.auth("root");
        //3. 选择库
        jedis.select(0);
    }
    
    1. 测试
    @Test
    void testString(){
        jedis.set("name","Kyle");
        String name = jedis.get("name");
        System.out.println("name = " + name);
    }
    
    @Test
    void testHash(){
        jedis.hset("reggie:user:1","name","Jack");
        jedis.hset("reggie:user:2","name","Rose");
        jedis.hset("reggie:user:1","age","21");
        jedis.hset("reggie:user:2","age","18");
        Map<String, String> map = jedis.hgetAll("reggie:user:1");
        System.out.println(map);
    }
    
    1. 释放资源
    @AfterEach
    void tearDown(){
        if (jedis != null){
            jedis.close();
        }
    }
    

连接池

  • Jedis本身是线程不安全的,并且频繁的创建和销毁连接会有性能损耗,因此我们推荐大家使用Jedis连接池代替Jedis的直连方式。
  • 新建一个com.blog.util,用于存放我们编写的工具类
  • 但后面我们使用SpringDataRedis的时候,可以直接在yml配置文件里配置这些内容
public class JedisConnectionFactory {

    private static JedisPool jedisPool;

    static {
        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(1000);
        // 创建连接池对象,参数:连接池配置、服务端ip、服务端端口、超时时间、密码
        jedisPool = new JedisPool(poolConfig, "101.42.225.160", 6379, 1000, "root");
    }

    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}
  • 之后我们的测试类就可以修改为如下
@SpringBootTest
class RedisTestApplicationTests {

    private Jedis jedis = JedisConnectionFactory.getJedis();

    @Test
    void testString(){
        jedis.set("name","Kyle");
        String name = jedis.get("name");
        System.out.println("name = " + name);
    }

    @Test
    void testHash(){
        jedis.hset("reggie:user:1","name","Jack");
        jedis.hset("reggie:user:2","name","Rose");
        jedis.hset("reggie:user:3","name","Kyle");
        jedis.hset("reggie:user:1","age","21");
        jedis.hset("reggie:user:2","age","18");
        jedis.hset("reggie:user:3","age","18");
        Map<String, String> map = jedis.hgetAll("reggie:user:1");
        System.out.println(map);
    }

    @AfterEach
    void tearDown(){
        if (jedis != null){
            jedis.close();
        }
    }
}

SpringDataRedis客户端

  • SpringData是Spring中数据操作的模块,包含对各种数据库的集成,其中对Redis的集成模块就叫做SpringDataRedis

  • 官网地址:https://spring.io/projects/spring-data-redis

    • 提供了对不同Redis客户端的整合(Lettuce和Jedis)
    • 提供了RedisTemplate统一API来操作Redis
    • 支持Redis的发布订阅模型
    • 支持Redis哨兵和Redis集群
    • 支持基于Lettuce的响应式编程
    • 支持基于JDK、JSON、字符串、Spring对象的数据序列化及反序列化
    • 支持基于Redis的JDKCollection实现
  • SpringDataRedis中提供了RedisTemplate工具类,其中封装了各种对Redis的操作。并且将不同数据类型的操作API封装到了不同的类型中:

API 返回值类型 说明
redisTemplate.opsForValue() ValueOperations 操作String类型数据
redisTemplate.opsForHash() HashOperations 操作Hash类型数据
redisTemplate.opsForList() ListOperations 操作List类型数据
redisTemplate.opsForSet() SetOperations 操作Set类型数据
redisTemplate.opsForzSet() ZSetOperations 操作SortedSet类型数据
redisTemplate 通用的命令

快速入门

SpringBoot已经提供了对SpringDataRedis的支持,使用起来非常简单

  1. 导入依赖,
<!--redis依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--common-pool-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<!--Jackson依赖-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
<!--lombok-->
<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>
  1. 配置Redis
spring:
  redis:
    host: 101.42.225.160
    port: 6379
    password: root
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 100ms
  1. 注入RedisTemplate
    因为有了SpringBoot的自动装配,我们可以拿来就用
@Autowired
private RedisTemplate redisTemplate;
  1. 编写测试方法
@Test
void stringTest(){
    redisTemplate.opsForValue().set("username","David");
    String username = (String) redisTemplate.opsForValue().get("username");
    System.out.println(username);
}

自定义序列化

  • RedisTemplate可以接收任意Object作为值写入Redis
  • 只不过写入前会把Object序列化为字节形式,默认是采用JDK序列化,得到的结果是这样的

\xAC\xED\x00\x05t\x00\x06\xE5\xBC\xA0\xE4\xB8\x89

  • 缺点:

    • 可读性差
    • 内存占用较大
  • 我们可以自定义RedisTemplate的序列化方式,代码如下
    com.blog.config包下编写对应的配置类

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        // 设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        // 返回
        return template;
    }
}
  • 我们编写一个User类,并尝试将其创建的对象存入Redis,看看是什么效果
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private Integer age;
}
  • 测试方法
@Test
void stringTest(){
    redisTemplate.opsForValue().set("userdata",new User("张三",18));
}
  • 这里采用了JSON序列化来代替默认的JDK序列化方式。最终结果如下:
{
  "@class": "com.blog.entity.User",
  "name": "张三",
  "age": 18
}
  • 整体可读性有了很大提升,并且能将Java对象自动的序列化为JSON字符串,并且查询时能自动把JSON反序列化为Java对象。不过,其中记录了序列化时对应的class名称,目的是为了查询时实现自动反序列化。这会带来额外的内存开销。
  • 所以肯定会有更好的方法

StringRedisTemplate

  • 为了节省内存空间,我们可以不使用JSON序列化器来处理value,而是统一使用String序列化器,要求只能存储String类型的key和value。当需要存储Java对象时,手动完成对象的序列化和反序列化。
  • 因为存入和读取时的序列化及反序列化都是我们自己实现的,SpringDataRedis就不会将class信息写入Redis了
  • 这种用法比较普遍,因此SpringDataRedis就提供了RedisTemplate的子类:StringRedisTemplate,它的key和value的序列化方式默认就是String方式。源码如下
public class StringRedisTemplate extends RedisTemplate<String, String> {
    public StringRedisTemplate() {
        this.setKeySerializer(RedisSerializer.string());
        this.setValueSerializer(RedisSerializer.string());
        this.setHashKeySerializer(RedisSerializer.string());
        this.setHashValueSerializer(RedisSerializer.string());
    }
  • 省去了我们自定义RedisTemplate的序列化方式的步骤(可以将之前配置的RedisConfig删除掉),而是直接使用:
@Test
void stringTest() throws JsonProcessingException {
    //创建对象
    User user = new User("张三", 18);
    //手动序列化
    String json = mapper.writeValueAsString(user);
    //写入数据
    stringRedisTemplate.opsForValue().set("userdata", json);
    //获取数据
    String userdata = stringRedisTemplate.opsForValue().get("userdata");
    //手动反序列化
    User readValue = mapper.readValue(userdata, User.class);
    System.out.println(readValue);
}
  • 存入Redis中是这样的
{
  "name": "张三",
  "age": 18
}

Guess you like

Origin blog.csdn.net/qq_33888850/article/details/129770025