Redis Basics
Redis types and common commands and client usage
Table of contents
1.1.1. Structured and unstructured
1.1.2. Associative and non-associative
1.3.2. Upload the installation package and decompress it
1 .3 .5 . Specify configuration to start
1 .3 .6 . Boot up automatically
1 .4 .1 . Redis command line client
1.4.2. Graphical desktop client
2.2.1 Common commands of String
1. Get to know Redis first
Redis is a key-value NoSql database, here are two keywords:
key-value
NoSql
其中键值型,是指Redis中存储的数据都是以key、value对的形式存储,而value的形 式多种多样,可以是字符串、数值、甚至json:
而NoSql则是相对于传统关系型数据库而言,有很大差异的一种数据库。
1 .1 .认识NoSQL
NoSql可以翻译做Not Only Sql (不仅仅是SQL),或者是No Sql (非Sql的)数据 库。是相对于传统关系型数据库而言,有很大差异的一种特殊的数据库,因此也称之为非关系型数据库。
1 .1 .1 .结构化与非结构化
传统关系型数据库是结构化数据,每一张表都有严格的约束信息:字段名、字段数据类 型、字段约束等等信息,插入的数据必须遵守这些约束:
而NoSql则对数据库格式没有严格约束,往往形式松散,自由。
可以是键值型:
也可以是文档型:
甚至可以是图格式:
1 .1 .2 .关联和非关联
传统数据库的表与表之间往往存在关联,例如外键:
非关系型数据库不存在关联关系,要维护关系要么靠代码中的业务逻辑,要么靠数据之间的耦合
{
id: 1 ,
name: "张三 " ,
orders: [
{
id: 1 ,
item: {
id: 10 , title: "荣耀6" , price : 4999
}
},
{
id: 2 ,
item: {
id: 20 , title: "小米11" , price : 3999
}
}
]
}
此处要维护 “张三 ”的订单与商品 “荣耀 ”和 “小米11”的关系,不得不冗余的将这两个商品 保存在张三的订单文档中,不够优雅。还是建议用业务来维护关联关系。
1 .1 .3 .查询方式
传统关系型数据库会基于Sql语句做查询,语法有统一标准;
而不同的非关系数据库查询语法差异极大,五花八门各种各样。
1 .1 .4 .事务
传统关系型数据库能满足事务ACID的原则。
而非关系型数据库往往不支持事务,或者不能严格保证ACID的特性,只能实现基本的一致 性。
1.1.5 . Summary _ _
In addition to the above four points, there are also significant differences in terms of storage methods, scalability, and query performance, as summarized below:
storage method
○ Relational databases are stored based on disks, and there will be a large number of disk IOs , which will have a certain impact on performance
○ 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 data and solve the problem of limited memory size. It's called horizontal scaling .
○ Relational databases have a relationship between tables, so horizontal expansion will bring a lot of trouble to data query
1.2 . Know Redis _
Redis was born in 2009. The full name is Remote Dicition Server, a remote dictionary server,
It is an in-memory key-value NoSQL database.
Features :
Key-value ( key - value ) type, value supports a variety of different data structures, rich in functions
Single thread, 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 address: https: ˌredis.io/
1.3 . Install Redis _
Most enterprises deploy projects based on Linux servers, and Redis does not officially provide a Windows version of the installation package. Therefore, in the course we will install Redis based on the Linux system .
The Linux version selected here is CentOS 7, it is recommended to download a visualization tool, such as FinalShell
1.3.1 . Dependent libraries _
Redis is written based on C language, so you first need to install the gcc dependencies required by Redis :
yum install -y gcc tcl
1.3.2 . Upload the installation package and decompress it
Then upload the Redis installation package provided by the pre-class materials to any directory of the virtual machine:
For example, I put in the /usr/local/src directory:
unzip:
tar -xzf redis-6.2.6.tar.gz
After decompression:
Enter the redis directory:
cd redis-6.2.6
Run the compile command:
make
If you do not install gcc directly, make
an error will be reported:
# means there is no such file
Jemalloc/jemalloc.h
solution:
- Install
gcc
- run
make distclean
- then proceed
make
If there are no errors, the installation should be successful.
The default installation path is in the /usr/local/bin directory:
This directory has been configured as an environment variable by default, so these commands can be run in any directory . in:
redis-cli : is the command line client provided by redis
redis - server : is the redis server startup script
redis-sentinel : is the redis sentinel startup script
1.3.3.Starting _ _ _ _
There are many ways to start redis , for example:
start by default
Specify the configuration to start
boot up
1.3.4 . Start by default
After the installation is complete, enter the redis-server command in any directory to start Redis :
This kind of startup belongs to the foreground startup , which will block the entire session window. When the window is closed or CTRL + C is pressed , Redis will stop . Not recommended.
1 .3 .5 . Specify configuration to start
If you want Redis to start in the background , you must modify the Redis configuration file, which is under the redis installation package we decompressed before ( /usr/local/src/redis-6.2.6 ), the name is redis.conf :
Let's back up this configuration file first: (in case of mistakes)
cp redis.conf redis.conf.bck
Then modify some configurations in the redis.conf file :
# The address allowed to be accessed, the default is 127.0.0.1 , which will result in local access only. If it is changed to 0.0.0.0 , it can be accessed from any IP, and the production environment should not be set to 0.0.0.0
bind 0.0.0.0
# Daemon process, after modifying to yes, it can run in the background
daemonize yes
# Password, you must enter the password to access Redis after setting
requirepass 123321
Other common configurations of Redis :
# Listening port
port 6379
# Working directory, the default is the current directory, that is, the command when running redis-server, logs, persistence and other files will be saved in this directory
dir .
# The number of databases, set to 1, means only 1 library is used, and there are 16 libraries by default, numbered 0~15
databases 1
# Set the maximum memory that redis can use
maxmemory 512mb
# Log file, the default is empty, no log is recorded, you can specify the log file name
logfile "redis.log"
Start Redis :
# Enter the redis installation directory
cd /usr/local/src/redis-6.2.6
# start up
redis-server redis.conf
Out of service:
# Use redis-cli to execute the shutdown command to stop the Redis service, #Because the password was configured before, you need to specify the password through -u
redis-cli -u 123321 shutdown
1 .3 .6 . Boot up automatically
We can also implement boot self-starting through configuration.
First, create a new system service file:
vi /etc/systemd/system/redis.service
The content is as follows
[Unit]
Description=redis-server
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/bin/redis-server /usr/local/src/redis- 6.2.6/redis.conf
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Then reload the system service:
systemctl daemon-reload
Now, we can use the following set of commands to operate redis :
# start up
systemctl start redis
# stop
systemctl stop redis
# restart
systemctl restart redis
# check status
systemctl status redis
Execute the following command to make redis boot up automatically:
systemctl enable redis
1.4 . 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
1.4.1 . 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 be connected , 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
When the commond is not specified , it will enter the interactive console of redis-cli :
At this time, use auth to specify your password
1.4.2 . Graphical desktop client
The great god on GitHub wrote a graphical desktop client for Redis
1.4.3 . Installation _ _
The graphical desktop client of Redis can be found in the pre-class materials :
After decompression, run the installer to install:
After the installation is complete, find the rdm.exe file in the installation directory :
Double click to run:
1.4.4 . Establishing a connection
Click the Connect to Redis Server button in the upper left corner:
Fill in the Redis service information in the pop-up window :
All these information are required to be your own virtual machine address and port, and remember to close the firewall release port in the virtual machine, you can ping your address in cmd to test whether you can connect
After clicking OK, this link will appear in the left menu:
Click to establish a connection.
Redis has 16 warehouses by default, numbered from 0 to 15. The number of warehouses can be set through the configuration file, but not more than
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:
# Select library 0
select 0
2. 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为了方便我们学习,将操作不同数据类型的命令也做了分组,在官网( https: ˌredis.io/commands)可以查看到不同的命令
不同类型的命令称为一个group,我们也可以通过help命令来查看各种不同group的命 令:
2 .1 .Redis通用命令
通用指令是部分数据类型的,都可以使用的指令,常见的有:
KEYS:查看符合模板的所有key
DEL:删除一个指定的key
EXISTS:判断key是否存在
EXPIRE:给一个key设置有效期,有效期到期时该key会被自动删除
TTL:查看一个KEY的剩余有效期
通过help [command] 可以查看一个命令的具体用法,例如:
# 查看keys命令的帮助信息:
127.0.0.1 :6379> help keys
KEYS pattern
summary: Find all keys matching the given pattern
since: 1.0.0
group: generic
2.2 . String type _
String type, that is, string type, is the simplest storage type in Redis .
Its value is a string, but according to the format of the string, it can be divided into three categories:
string : ordinary string
int : Integer type, can do self-increment and self-decrement operations
float : Floating point type, can do self-increment and self-decrement operations
Regardless of the format, the bottom layer is stored in the form of a byte array, but the encoding method is different. The maximum space of string type cannot exceed 512m
2.2.1 . Common commands of String
Common commands for String are:
SET : Add or modify an existing key-value pair of String type
GET : Get the value of String type according to the key
MSET : 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 : Increment an integer key and specify the step size, for example: incrby num 2 Increment the num value by 2
INCRBYFLOAT : Increment a floating-point number and specify the step size
SETNX : Add a key-value pair of String type, provided that the key does not exist, otherwise it will not be executed
SETEX : Add a key-value pair of String type and specify the validity period
2.2.2.Key structure _ _ _ _
Redis does not have a concept similar to the Table in MySQL . How do we distinguish between different types of keys ?
For example, it is necessary to store user and product information in redis . There is a user id that is 1 , and a product id that happens to be 1. At this time, if the id is used as the key , there will be a conflict. What should I do?
We can distinguish them by adding a prefix to the key , but this prefix is not added casually, and there are certain specifications:
The key of Redis allows multiple words to form a hierarchical structure, separated by ':' , in the following format:
Project name: business name: type: id
This format is not fixed, you can also delete or add entries according to your own needs. In this way, we can distinguish different types of data. This avoids key conflicts .
For example, our project name is heima , and there are two different types of data, user and product . We can define key like this :
User related key : heima:user:1
product- related key : heima:product: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 |
home:user:1 |
{"id":1, "name": "Jack", "age": 21} |
home:product:1 |
{"id":1, "name": "小米11", "price": 4999} |
In the Redis desktop client, the same prefix is also used as the hierarchical structure to make the data look hierarchical and clear:
2.3 . Hash type _
Hash type, also called hash, its 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 inconvenient :
The Hash structure can store each field in the object independently, and can do CRUD for a single field :
Common commands for Hash are:
HSET key field value : add or modify the value of the field of the hash type key
HGET key field : Get the value of a hash type key field
HMSET : Batch add the value of multiple fields of hash type key
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
HVALS : Get all the values 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
2.4 . List type _
The List type in Redis is similar to the LinkedList in Java , which can be regarded as a doubly linked list structure. Both forward search and reverse search can be supported.
Traits are also similar to LinkedList :
orderly
elements can be repeated
Fast insertion and deletion
General query speed
It is often used to store an ordered data, for example: circle of friends like list, comment list, etc.
Common commands for List are:
LPUSH key element : Insert one or more elements to the left of the list
LPOP key : Remove and return the first element on the left of the list, or return nil if there is no
RPUSH key element : Insert one or more elements to the right of the list
RPOP key : remove and return the first element on the right side of the list
LRANGE key star end : returns all elements within the range of a corner mark
BLPOP and BRPOP : Similar to LPOP and RPOP , but wait for the specified time when there are no elements, instead of returning nil directly
2.5 . Set type _
The Set structure of Redis is similar to the HashSet in Java , which can be regarded as a HashMap whose value is null . Because it is also a hash table, it has similar characteristics to HashSet :
out of order
Elements cannot be repeated
find fast
Support intersection, union, difference and other functions
Common commands for Set are:
SADD key member : Add one or more elements to the set
SREM key member : Remove the specified element in the set
SCARD key : returns the number of elements in the set
SISMEMBER key member : Determine whether an element exists in the set
SMEMBERS : Get all elements in the set
SINTER key 1 key 2 : find the intersection of key 1 and key 2
SDIFF key1 key2 : Find the difference between key 1 and key 2
.SUNION key 1 key 2 : find the union of key 1 and key 2
For example two collections: s1 and s2:
Intersection: SINTER s1 s2
Find the difference between s1 and s2 : SDIFF s 1 s2
practise:
1. Store the following data with the Set collection of Redis :
Zhang San's friends are: Li Si, Wang Wu, Zhao Liu
Li Si's friends are: Wang Wu, Ma Zi, Er Gou
2. Use the Set command to realize the following functions:
Calculate how many friends Zhang San has
Calculate which friends Zhang San and Li Si have in common
Query who is Zhang San's friend but not Li Si's friend
Query who are the friends of Zhang San and Li Si in total
Determine whether Li Si is Zhang San's friend
Determine whether Zhang San is Li Si's friend
· Remove Li Si from Zhang San's friend list
2.6 . SortedSet type _
Redis 's SortedSet is a sortable set collection, which is somewhat similar to TreeSet in Java , but the underlying data structure is very different. Each element in the SortedSet has a score attribute, which can be based on
The score attribute sorts the elements, and the underlying implementation is a skip list ( SkipList ) plus a hash table.
SortedSet has the following characteristics:
sortable
elements are not repeated
query speed
Because of the sortable feature of SortedSet ( from small to large ), it is often used to implement functions such as leaderboards.
Common commands for SortedSet are:
ZADD key score member : Add one or more elements to the sorted set and update its score value if it already exists
ZREM key member : Delete a specified element in the sorted set
ZSCORE key member : Get the score value of the specified element in the sorted set
ZRANK key member : Get the rank of the specified element in the sorted set
ZCARD key : Get the number of elements in the sorted set
ZCOUNT key min max : Count the number of all elements whose score value is within a given range
ZINCRBY key increment member : Let the specified element in the sorted set auto-increment, and the step size is the specified increment value
ZRANGE key min max : After sorting by score , get the elements within the specified ranking range
ZRANGEBYSCORE key min max : After sorting by score , get the elements within the specified score range
ZDIFF , ZINTER , ZUNION : difference, intersection, union
Note: All rankings are in ascending order by default. If you want to order in descending order, just add REV after Z in the command , for example:
Getthe rank of the specified element in the sorted set in ascending order : ZRANKkeymember
Getthe rank of the specified element in the sorted set in descending order : ZREVRANKkeymemeber
Practice questions:
Store the following student scores for the class into a Redis SortedSet :
Jack 85, Lucy 89, Rose 82, Tom 95, Jerry 78, Amy 92, Miles 76
And implement the following functions:
Delete classmate Tom
Get Amy 's classmate's score
Get the ranking of Rose 's classmates
Query how many students have scores below 80
Add 2 points to classmate Amy
Find out the top 3 students
Find out all students with scores below 80
3. Java Client for Redis _
在Redis官网中提供了各种语言的客户端
其中Java客户端也包含很多:
标记为*的就是推荐使用的java客户端,包括:
Jedis和Lettuce:这两个主要是提供了Redis命令对应的API,方便我们操作
Redis,而SpringDataRedis又对这两种做了抽象和封装,因此我们后期会直接以 SpringDataRedis来学习。
Redisson:是在Redis基础上实现了分布式的可伸缩的java数据结构,例如Map、 Queue等,而且支持跨进程的同步机制: Lock、 Semaphore等待,比较适合用来实 现特殊的功能需求。
3 .1 .Jedis客户端
3 .1 .1 .快速入门
我们先来个快速入门:
1)引入依赖:
<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>
2)建立连接
新建一个单元测试类,内容如下:
private Jedis jedis;
@BeforeEach
void setUp () {
// 1.建立连接
jedis = new Jedis("192.168.150.101 ", 6379);
jedis = JedisConnectionFactory .getJedis();
// 2.设置密码
jedis .auth ( "123321" );
// 3.选择库
jedis .select (0 );
}
3)测试:
@Test
void testString() {
// 存入数据
String result = jedis .set ( "name" , "虎哥 " );
System .out .println("result = " + result );
// 获取数据
String name = jedis .get ( "name" );
System .out .println("name = " + name );
}
@Test
void testHash () {
//插入hash数据
jedis .hset ( "user:1" , "name" , "Jack" );
jedis .hset ( "user:1" , "age" , "21" );
// 获取
Map<String , String> map = jedis .hgetAll ( "user:1" );
System .out .println(map );
}
4)释放资源
@AfterEach
void tearDown () {
if (jedis != null) {
jedis .close ();
}
}
3 .1 .2 .连接池
Jedis本身是线程不安全的,并且频繁的创建和销毁连接会有性能损耗,因此我们推荐大 家使用Jedis连接池代替Jedis的直连方式。
package com .heima .jedis .util;
import redis .clients .jedis .*;
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 ,
"192.168.150.101 " , 6379 , 1000 , "123321" );
}
public static Jedis getJedis() {
return jedisPool .getResource ();
}
}
3 .2 .SpringDataRedis客户端
SpringData是Spring中数据操作的模块,包含对各种数据库的集成,其中对Redis的集成模块就叫做SpringDataRedis,
官网提供了对不同Redis客户端的整合(Lettuce和Jedis)
提供了RedisTemplate统一API来操作Redis
支持Redis的发布订阅模型
Supports Redis Sentinel and Redis Cluster
Support Responsive Programming based on Lettuce
Supports data serialization and deserialization based on JDK , JSON , strings, and Spring objects
Support Redis - based JDKCollection implementation
The RedisTemplate tool class is provided in SpringDataRedis , which encapsulates various operations on Redis . And the operation API of different data types is encapsulated into different types:
3.2.1 . Quick Start _
SpringBoot already provides support for SpringDataRedis , which is very easy to use.
First, create a new maven project, and then follow the steps below:
1 ) Introduce dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.12-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yj</groupId>
<artifactId>Redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Redis</name>
<description>Redis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 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>
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
2 ) Configure Redis application.yaml
Spring:
redis:
host: 192.168.150.101
port: 6379
password: 123321
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 1000ms
3 ) Inject RedisTemplate
Because of SpringBoot 's automatic assembly, we can use it:
@SpringBootTest
class RedisStringTests {
@Autowired
private RedisTemplate redisTemplate;
}
4 ) Write tests
@SpringBootTest
class RedisStringTests {
@Autowired
private RedisTemplate edisTemplate;
@Test
public void testString() {
// 写入一条String数据
redisTemplate .opsForValue ().set ( "name" , "虎哥 " );
//获取string数据
Object name =stringRedisTemplate .opsForValue ().get ( "name" );
System .out .println("name = " + name );
}
}
3.2.2 . Custom serialization _
RedisTemplate can receive any Object as a value and write it to Redis :
It's just that the Object will be serialized into bytes before writing . The default is to use JDK serialization, and the result is as follows :
shortcoming:
poor readability
Large memory usage
We can customize the serialization method of RedisTemplate , the code is as follows:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
//创建RedisTemplate对象
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//设置连接工厂
redisTemplate.setConnectionFactory(connectionFactory);
//创建JSON序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
//设置Key的序列化
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
//设置Value的序列化
redisTemplate.setValueSerializer(jsonRedisSerializer);
redisTemplate.setHashValueSerializer(jsonRedisSerializer);
//返回RedisTemplate对象
return redisTemplate;
}
}
Here, JSON serialization is used instead of the default JDK serialization method. The final result is as follows:
The overall readability has been greatly improved, and Java objects can be automatically serialized into JSON strings, and JSON can be automatically deserialized into Java objects when querying. However, it records the corresponding class name during serialization, in order to achieve automatic deserialization during query. This introduces additional memory overhead.
3 .2 .3 .StringRedisTemplate
In order to save memory space, instead of using the JSON serializer to process the value , we can use the String serializer uniformly , requiring only the key and value of the String type to be stored . When Java objects need to be stored , serialization and deserialization of objects are manually completed .
Because the serialization and deserialization when storing and reading are implemented by ourselves, SpringDataRedis will not write class information into Redis .
This usage is more common, so SpringDataRedis provides a subclass of RedisTemplate :
StringRedisTemplate , the serialization method of its key and value is the String method by default.
The step of customizing the serialization method of RedisTemplate is omitted , but directly used:
@Autowired
private StringRedisTemplate stringRedisTemplate;
// JSON序列化工具
private static final ObjectMapper mapper = new ObjectMapper();
@Test
void testSaveUser () throws JsonProcessingException {
//创建对象
User user = new User ( "虎哥 " , 21 );
// 手动序列化
String json = mapper .writeValueAsString(user );
// 写入数据
stringRedisTemplate .opsForValue ().set ( "user:200" , json);
// 获取数据
String jsonUser =stringRedisTemplate .opsForValue ().get ( "user:200" );
// 手动反序列化
User user1 = mapper . readValue (jsonUser , User .class );
System .out .println("user1 = " + user1 );
}
This is the end of the Redis basics. If it is helpful to you, please leave your praise. There is a PDF version, including the following practical chapters, advanced chapters, and principle chapters. You can receive it for free by private message