Article directory
- 1 Overview
- 2. Basic use cases
- 3.Redis Java client
1 Overview
Summary of notes:
- NoSQL: Non-relational database, NoSQL database provides a different data storage and query model.
- Redis features:
- Key-value type, value supports a variety of different data structures and has rich functions
- Single thread , each command is atomic ( the network part in Redis6.0 is multi-threaded )
- Low latency, fast ( memory based , IO multiplexing, good encoding).
- Support data persistence
- Support master-slave cluster and shard cluster
- Support multi-language clients
- Redis new features:
- Redis Funcitons
- Client-eviction
- ACL v2
- Muti-part AOF
- ……
1.1NoSQL
NoSQL (Not Only SQL) is a broad database classification that represents a group of non-relational database management systems. Compared with traditional relational databases (such as SQL databases), NoSQL databases provide a different data storage and query model.
illustrate:
- Relational databases store structured data and can add constraints and other conditions to each tuple or field.
- Non-relational databases store unstructured data, usually in the form of key-value pairs. The data stored is diverse and can be documents or pictures.
illustrate:
- Data stored in a relational database can be related through a third table
- Data stored in non-relational databases are not related to each other
illustrate:
- The data stored in the relational database can be added, deleted, modified and checked through SQL statements.
- The data stored in non-relational databases each have their own way of storing data, and the storage rules are different.
illustrate:
- Relational databases support the ACID characteristics of transactions, including Atomicity, Consistency, Isolation, and Durability.
- Non-relational database storage does not have transactions
In general, the difference between SQL and NoSQL can be summarized in a table:
1.2 Meaning
Redis was born in 2009. Its full name is RemoteDictionaryServer , a remote dictionary server. It is a memory-based key-value NoSQL data.
feature:
- Key-value type, value supports a variety of different data structures and has rich functions
- Single thread , each command is atomic (the network part in Redis6.0 is multi-threaded)
- Low latency, fast (memory based, IO multiplexing, good encoding).
- Support data persistence
- Supports master-slave clusters and sharded clusters
- Support multi-language clients
1.3 New features of Redis
Redis Funcitons
illustrate:
Redis function, a new way to extend Redis through server-side scripts, is stored together with the data itself. In short, redis itself is going to steal the jobs of Lua scripts
Client-eviction
illustrate:
The number of people connected to Redis and performance become configurable
Muti-part AOF
illustrate:
Asynchronous reading and writing is no longer a pain point
ACL v2
illustrate:
Refined permission management, you can configure passwords for the cluster, etc.
listpack
illustrate:
listpack is a new data structure used to replace ziplist. There is no ziplist configuration in version 7.0 (only some data types are used as a transitional stage in version 6.0)
2. Basic use cases
Summary of notes:
Install and run
In windows…
In Docker container
sudo docker run --restart=always --log-opt max-size=100m --log-opt max-file=2 -p 6379:6379 --name myredis -v /home/redis/myredis/myredis.conf:/etc/redis/redis.conf -v /home/redis/myredis/data:/data -d redis redis-server /etc/redis/redis.conf --appendonly yes --requirepass qweasdzxc
Using the graphical interface...
Common commands
- String type:
- 添加:SET、GET、MSET(mulitiple set)、MGET
- 修改:INCR(increase)、INCRBY(increase by)、INCRBYFLOAT(increase by float)、SETNX(set if not exist)、SETEX(set if expire)
- Hash type:
- Addition: HSET, HGET, HMSET (hash multitiple set)
- 修改:HINCRBY(hash increase)、HSETNX(hash set if not exist)
- Query: HMGET (hash muitiple get), HGETALL, HKEYS, HVALS
- List type:
- Added: LPUSH, RPUSH
- Delete: LPOP, RPOP, BLPOP and BRPOP: similar to LPOP and RPOP, except that it waits for the specified time when there are no elements, instead of returning nil directly
- Query: LRANGE
- Set type:
- Addition: SADD (set addition)
- Delete: SREM (set remove member)
- 修改:SINTER (set intersection)、SUNION(set union) 、SDIFF(set different)
- 查询:SCARD (set cardinality)、SISMEMBER(set is member)、SMEMBERS(set members)
- SortedSet type, BitMap type, HyperLogLog type, Stream type, GEO type: please check for details
2.1 Install and run
2.1.1 In Windows system
Step 1: Unzip
illustrate:
After installation, the following files will be generated
Startup example:
Step 2: Start the server
redis-server.exe redis.windows.conf
illustrate:
- When starting the server, you need to specify the redis configuration file
- If no configuration items are added, an error will be reported.
Notice:
Need to add conf configuration items
Step 3: Start the client
1. Start the client
illustrate:
If the redis server is started, but the prompt "Running in standalone mode" does not appear, you need to open the client and perform a shutdown operation.
# 通过cmd打开客户端 redis-cli.exe # 关闭客户端 shutdown
Now restart the server
2. Restart the server
redis-server.exe redis.windows.conf
illustrate:
- Successful after restarting
2.1.2 In Docker container
Step 1: Pull the Docker image
sudo docker pull redis
Step 2: Start the server
sudo docker run --restart=always --log-opt max-size=100m --log-opt max-file=2 -p 6379:6379 --name myredis -v /home/redis/myredis/redis.conf:/etc/redis/redis.conf -v /home/redis/myredis/data:/data -d redis redis-server /etc/redis/redis.conf --appendonly yes --requirepass qweasdzxc
Description: Parameter explanation
sudo docker run
: A command to run a Docker container.--restart=always
: Set the container to automatically restart on exit.--log-opt max-size=100m
: Set the maximum size of container log files to 100MB.--log-opt max-file=2
: Set the maximum number of log files retained by the container to 2.-p 6379:6379
: Map the container's Redis service port to the host's 6379 port.--name myredis
: Specify the name of the container as "myredis".-v /home/redis/myredis/redis.conf:/etc/redis/redis.conf
: Mount the Redis configuration file on the host to/etc/redis/redis.conf
the path in the container.-v /home/redis/myredis/data:/data
: Mount the data directory on the host to/data
the path in the container for persisting Redis data.-d redis
: Specify the container image to be run as "redis", which is the image officially provided by Redis.redis-server /etc/redis/redis.conf
: Specify the Redis service to run when the container starts, and pass the Redis configuration file path.--appendonly yes
: Turn on the AOF (Append Only File) persistence mode of Redis and append the write operation to the file on the disk.--requirepass qweasdzxc
: Set the password of the Redis server to "qweasdzxc", that is, a password is required to access the Redis service.
Notice:
If you need to enable the remote access service of Redis, you need to set a password for Redis.
Step 3: Start the client
redis-cli [options] [commonds]
redis-cli -h 127.0.0.1 -p 6739 -a qweasdzxc
Description: Parameter explanation
-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 for redis
Replenish:
ping
: Do a heartbeat test with the redis server, and the server will return normally.pong
2.1.3 Run the graphical interface client
Step 1: Download the client
URL; lework/RedisDesktopManager-Windows: RedisDesktopManager Windows version (github.com)
Description: result
Step 2: Install
illustrate:
The installation failed. You need to install the runtime library to run Visual C++.
Step 3: Run
2.2 Common commands
2.2.1 Overview
Redis is a key-value database. The key is generally of type String, but the types of value are diverse:
illustrate:
There are many data types in redis. Now we will introduce the commands of each type in turn.
In order to facilitate our learning, Redis also groups the commands for operating different data types. You can view different commands on the official website ( https://redis.io/commands ):
2.2.2 Common commands
General instructions are instructions that can be used for some data types. Common ones include:
- KEYS: View all keys that match the template. It is not recommended to use on production environment equipment.
- DEL: delete a specified key
- EXISTS: Determine whether the key exists
- EXPIRE: Set the validity period for a key. The key will be automatically deleted when the validity period expires.
- TTL: View the remaining validity period of a KEY
illustrate:
It is not
keys
recommended to use it on production environment equipment because Redis is single-threaded. If there are many Key values to be found, it will cause thread blocking.
Replenish:
- You can view the specific usage of a command through help [command], for example:
2.2.3String type
2.2.3.1 Overview
The String type, also known as the string type, is the simplest storage type in Redis.
Its value is a string, but depending on the format of the string, it can be divided into three categories:
- string: ordinary string
- int: Integer type, can perform auto-increment and auto-decrement operations
- float: floating point type, can perform auto-increment and auto-decrement operations
No matter which format it is, the bottom layer is stored in the form of byte array, but the encoding method is different. The maximum space of string type cannot exceed 512m.
illustrate:
In the String type, the bottom layer of Redis can be divided into three types for storage, namely, strings will be converted into bytes for storage, and numbers and floating point numbers will be converted into binary for storage.
2.2.3.2 Common commands
1. Add
- SET: Add or modify an existing String type key-value pair
- GET: Get the value of String type based on key
- MSET (multiple set): Add multiple String type key-value pairs in batches
- MGET (multiple get): Get multiple String type values based on multiple keys
illustrate:
- The above command is set successfully
2. Self-growth
- INCR (increase): Let an integer key increase by 1
- INCRBY (increase by): Let an integer key increase by itself and specify the step size. For example: incrby num 2 makes the num value increase by 2.
- INCRBYFLOAT (increase by float): Let a floating-point type number increase by itself and specify the step size
illustrate:
- When using auto-increment, the number will increase as needed
3.Combined commands
- SETNX (set if not exist): Add a String type key-value pair, provided that the key does not exist, otherwise it will not be executed.
- SETEX (set if expire): Add a String type key-value pair and specify the validity period
illustrate:
- If the key already exists in Redis, the setting fails.
2.2.3.3Key structure
Redis key allows multiple words to form a hierarchical structure. Multiple words are separated by ':'. The format is as follows:
项目名:业务名:类型:id
illustrate:
This format is not fixed, and entries can be deleted or added according to your own needs.
For example, our project name is heima, and there are two different types of data: user and product. We can define the key like this:
user相关的key:heima:user:1 product相关的key:heima:product:1
If Value is a Java object, such as a User object, the object can be serialized into a JSON string and stored:
KEY | VALUE |
---|---|
home:user:1 | ’ {“id”:1, “name”: “Jack”, “age”: 21} ’ |
home:product:1 | ' {"id":1, "name": "Xiaomi 11", "price": 4999} ' |
illustrate:
- After using the Redis
:
grouping method, you can see the visualization tools and create groups for us.
2.2.4Hash type
2.2.4.1 Overview
Hash type, also called hash, its value is an unordered dictionary, similar to the HashMap structure in Java. The String structure is to serialize the object into a JSON string and store it. It is very inconvenient when you need to modify a certain field of the object:
The Hash structure can store each field in the object independently, and can do CRUD for a single field:
2.2.4.2 Common commands
1. Add
- 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(hash multitiple set): Batch add the values of fields of multiple hash type keys
illustrate:
HMSET
will be deleted because the effect isHSET
similar to
2. Self-growth
- HINCRBY (hash increase): Let the field value of a hash type key increase automatically and specify the step size
illustrate:
- You can see the age value and growth here
3.Combined commands
- HSETNX (hash set if not exist): Add a field value of a hash type key, provided that the field does not exist, otherwise it will not be executed.
illustrate:
- The key value here
ljtxy:product"1
already has the filed field of age, so the setting fails
4.Query
- HMGET (hash multitiple get): 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 fields in a hash type key
- HVALS: Get all values in a hash type key
2.2.5List type
2.2.5.1 Overview
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 .
The characteristics are also similar to LinkedList:
- orderly
- Elements can be repeated
- Fast insertion and deletion
- General query speed
Commonly used to store ordered data, such as: circle of friends like list, comment list, etc.
2.2.5.2 Common commands
1. Add
- LPUSH key element … : Insert one or more elements to the left of the list
- RPUSH key element … : Insert one or more elements to the right of the list
Description: result
2.Delete
-
LPOP key: removes and returns the first element on the left side of the list, or returns nil if there is none
-
RPOP key: Remove and return the first element on the right side of the list
-
BLPOP and BRPOP: Similar to LPOP and RPOP, but wait for the specified time when there are no elements, instead of returning nil directly
illustrate:
- Similar to waiting for the specified delay time, if it times out, it returns nil
3. Query
- LRANGE key star end: returns all elements within the range of a corner mark
Description: result
2.2.6Set type
2.2.6.1 Overview
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 :
- disorder
- Elements cannot be repeated
- Find fast
- Supports intersection, union, difference and other functions
2.2.6.2 Common commands
1. Add
- SADD (set addtion) key member ... : Add one or more elements to the set
2.Delete
- SREM (set remove member) key member … : Remove the specified element in the set
3. Cross and difference
- SINTER (set intersection) key1 key2 ... : Find the intersection of key1 and key2
- SUNION (set union) key1 key2 ...: Find the union of key1 and key2
- SDIFF (set different) key1 key2 … : Find the difference between key1 and key2
illustrate:
4.Query
- SCARD (set cardinality) key: Returns the number of elements in the set
- SISMEMBER (set is member) key member: determine whether an element exists in the set
- SMEMBERS (set members): Get all elements in the set
2.2.7SortedSet type
2.2.7.1 Overview
Redis's SortedSet is a sortable set collection, which is somewhat similar to the TreeSet in Java, but the underlying data structure is very different. Each element in SortedSet has a score attribute, and the elements can be sorted based on the score attribute. The underlying implementation is a skip list (SkipList) plus a hash table.
SortedSet has the following properties:
- Sortable
- Elements are not repeated
- Query speed is fast
Because of the sortable nature of SortedSet, it is often used to implement functions such as rankings.
2.2.7.2 Common commands
1. Add
- ZADD key score member [score member]: Add one or more elements to the sorted set, and update its score value if it already exists
illustrate:
- new value
2.Delete
- ZREM key member: delete a specified element in the sorted set
illustrate:
- Delete value
3. Cross and difference
- ZDIFF, ZINTER, ZUNION: find difference, intersection, union
3. Query
- 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 increase by the specified increment value.
- ZRANGE key min max: After sorting by score, get the elements within the specified ranking range
illustrate:
- range means returning the corresponding elements
- ZRANGEBYSCORE key min max: After sorting by score, get the elements within the specified score range
illustrate;
- rangbyscore gets the sorted elements within the specified range
2.2.7.3 Application scenarios
2.2.8BitMap type
2.2.8.1 Overview
A statistical binary state data type implemented using the String type as the underlying data structure. Bitmap is essentially an array, which is a bit-wise operation based on the String data type. The array consists of multiple binary bits, each of which corresponds to an offset (we call it an index). The maximum number of bits supported by Bitmap is 2 32 bits, which can greatly save storage space. It can store up to 4.29 billion bytes of information using 512M memory (2 32= 4294967296)
2.2.8.2 Common commands
1. Add
- setbit key offset value: Add an element to the value of the specified position
illustrate:
- new value
2. Query
Get the specified element value
- getbit key offset: Get the value of the specified position of the specified element
illustrate:
- Query value
Get the storage bytes of the specified element
- strlen key: Get the number of bytes stored in the specified element
illustrate:
- Query occupied space
- bitcount key: Get the number of 1's in the specified element
illustrate:
- Query the number of 1
Get the bit storage of multiple specified elements :
- BITOP operation destkey key [key…]: Get elements in multiple bits
illustrate:
Replenish:
BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN
, perform logical union on one or more keys, and save the result to destkey.BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN
, perform logical OR on one or more keys, and save the result to destkey.BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN
, perform logical XOR on one or more keys, and save the result to destkey.BITOP NOT destkey srckey
, perform logical negation on the given key and save the result to destkey.
2.2.8.3 Application scenarios
Count the number of user check-ins
2.2.9HyperLogLog type
2.2.9.1 Overview
Redis HyperLogLog is an algorithm used for cardinality statistics . The advantage of HyperLogLog is that when the number or volume of input elements is very large, the space required to calculate the cardinality is always fixed and very small.
In Redis, each HyperLogLog key only needs 12 KB of memory to calculate the cardinality of nearly 2^64 different elements. This is in stark contrast to collections where more elements consume more memory when computing cardinality.
2.2.9.2 Common commands
1. Add
- PFADD (Probabilistic Fixed Add) key element [element...]: Add the specified element to HyperLogLog
illustrate:
- new element
2.Modify
- PFMERGE (Probabilistic Fixed Merger) destkey sourcekey [sourcekey...]: Merge multiple HyperLogLogs into one HyperLogLog
illustrate:
- merge base
3. Query
- PFCOUNT key [key …]: Returns the cardinality estimate for the given HyperLogLog
illustrate:
- Obtain the basic number after deduplication
2.2.9.3 Application scenarios
Count the UA (number of user visits) of commercial websites
2.2.10Stream type
2.2.10.1 Overview
Stream is a new data type introduced in Redis 5.0, which can implement a very complete message queue.
2.2.10.2 Common commands
1. Add
- XADD key ID field value [field value ...]: Use XADD to add a message to the queue, if the specified queue does not exist, create the queue
illustrate:
- View Results
- XGROUP [CREATE key groupname id-or-$]: Create consumer group
illustrate:
- Create consumer group g1 with key s1 and retain data
- XGROUP [CREATECONSUMER key groupname consumername]: Add the consumer specified in the consumer group
illustrate:
- Specify the key and consumer group and add consumers to it
- XPENDING key group [[IDLE min-idle-time] start end count [consumer]]: Displays information about pending messages
illustrate:
- Return all confirmed messages
2.Delete
- XGROUP [DESTROY key groupname]: Use XGROUP DESTROY to delete consumer groups
illustrate:
- Specify key and consumer group name
- XGROUP [DELCONSUMER key groupname consumername]: Delete the specified consumer in the consumer group
illustrate:
- To be tested
3.Update
- XACK key group ID [ID …]: Mark message as "processed"
illustrate:
- Specify the key and group name and ID of the queue to be processed
4.Query
- XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key …] id [id …]: Use XREAD to get a list of messages in a blocking or non-blocking way
illustrate:
- query element
- Blocking read latest news
- XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] [NOACK] STREAMS key [key …] ID [ID …]: Read messages in the consumer group
illustrate:
2.2.11GEO type
2.2.11.1 Overview
GEO is the abbreviation of Geolocation, which represents geographical coordinates. Redis added support for GEO in version 3.2, allowing us to store geographic coordinate information and help us retrieve data based on longitude and latitude.
2.2.11.2 Common commands
1. Add
- GEOADD key [NX | XX] [CH] longitude latitude member: Add a geospatial information, including: longitude (longitude), latitude (latitude), value (member)
illustrate:
- Parameter explanation:
GEOADD 键 精度 维度 值
- GEOPOS key [member [member ...]]: returns the coordinates of the specified member
illustrate:
- Parameter explanation:
GEOPOS 键 成员
2.Modify
- GEODIST key member1 member2 [M | KM | FT | MI]: Calculate the distance between the two specified points and return
illustrate:
- Parameter explanation:
GEODIST 键 值1 值2
- GEOSEARCH key <FROMMEMBER member | FROMLONLAT longitude latitude> <BYRADIUS radius <M | KM | FT | MI> | BYBOX width height <M | KM | FT | MI>> [ASC | DESC] [COUNT count [ANY]] [WITHCOORD ] [WITHDIST] [WITHHASH]: Search for members within the specified range, sort them by their distance from the specified point, and return them. The range can be circular or rectangular. 6.2.New features
illustrate:
- Parameter explanation:
GEODIST 键 指定经纬度 画圆 举例 返回距离
- GEOHASH key [member [member …]]: Convert the coordinates of the specified member into hash string form and return
illustrate:
- Parameter explanation:
GEOHASH 键 成员
3.Redis Java client
Summary of notes:
- Overview: Redis official website provides clients in various languages, address: https://redis.io/clients
- Basic use of Jedis: Jedis itself is thread-unsafe, and frequent creation and destruction of connections will cause performance losses.
- Jedis connection pool: At this time, Jedis connection pool is used instead of Jedis direct connection method to reduce frequent creation and destruction of connections.
- SpringDataRedis usage: SpringData is a module for data operations in Spring, including integration of various databases
- RedisSerializr serialization: Custom serialization method makes Redis storage resources more memory-saving
- Use of StringRedisTemplate: In order to save memory space, we do not use the JSON serializer to process the value, but 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, the serialization and deserialization of the objects is done manually .
3.1 Overview
Clients in various languages are provided on the Redis official website, address: https://redis.io/clients
illustrate:
There are many excellent client usages in the Java client. It is recommended to learn Jedis and Lettcuce.
Spring integrates Jedis and lettuce operations on the Java client, called Spring Data Redis. Learn Spring Data Redis at this time
3.2 Basic use case - Jedis usage
3.2.1 Overview
Jedis’ official website address: https://github.com/redis/jedis
3.2.2 Basic use cases
Step 1: Import dependencies
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.4.1</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Step 2: Demonstration
public class JedisTest {
public Jedis jedis;
@Before
public void setUp() {
// 1.建立连接
jedis = new Jedis("10.13.164.55", 6379);
// 2.设置密码
jedis.auth("qweasdzxc");
// 3.选择库
jedis.select(0);
}
@Test
public void testSet() {
String set = jedis.set("yueyue2", "玥玥");
System.out.println(set);
String s = jedis.get("yueyue2");
System.out.println(s);
}
@After
public void setDown() {
if (Objects.isNull(jedis)) {
jedis.close();
}
}
}
illustrate:
Create Jedis objects, test methods, and close resources
3.2.3Jedis connection pool
3.2.3.1 Overview
Jedis itself is thread-unsafe, and frequent creation and destruction of connections will cause performance losses. Therefore, we recommend that you use Jedis connection pool instead of Jedis direct connection.
3.2.3.2 Basic use cases
Step 1: Create a factory
/**
* 获取Jedis连接池工厂
*/
public class JedisConnectionFactory {
private static final JedisPool jedisPool;
static {
// 配置连接池
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大连接
jedisPoolConfig.setMaxTotal(8);
// 最大空闲连接,当有连接时,最多准备8个连接点
jedisPoolConfig.setMaxIdle(8);
// 最小空闲连接,当没有连接时,会释放所有连接点
jedisPoolConfig.setMinIdle(0);
// 设置最长等待时间,ms
jedisPoolConfig.setMaxWait(Duration.ofMillis(200));
// 创建连接此对象
jedisPool = new JedisPool(jedisPoolConfig, "10.13.164.55", 6379, 2000, "qweasdzxc");
}
// 获取Jedis对象
public static Jedis getJedis() {
return jedisPool.getResource();
}
}
Step 2: Demonstration
public class JedisTest {
public Jedis jedis;
@Before
public void setUp() {
// 1.建立连接
// jedis = new Jedis("10.13.164.55", 6379);
// 2.设置密码
// jedis.auth("qweasdzxc");
jedis = JedisConnectionFactory.getJedis();
// 3.选择库
jedis.select(0);
}
@Test
public void testSet() {
String set = jedis.set("yueyue2", "玥玥");
System.out.println(set);
String s = jedis.get("yueyue2");
System.out.println(s);
}
@After
public void setDown() {
if (Objects.isNull(jedis)) {
jedis.close();
}
}
}
3.3 Basic use cases - SpringDataRedis usage
3.3.1 Overview
SpringData is a data operation module in Spring, including the integration of various databases. The integration module for Redis is called SpringDataRedis. The official website address: https://spring.io/projects/spring-data-redis
- Provides integration of different Redis clients (Lettuce and Jedis)
- Provides RedisTemplate unified API to operate Redis
- Support Redis publish-subscribe model
- Supports Redis Sentinel and Redis Cluster
- Supports reactive programming based on Lettuce
- Supports data serialization and deserialization based on JDK, JSON, strings, and Spring objects
- Supports JDKCollection implementation based on Redis
3.3.2 Basic Use Cases
Description: Common command operations
API Return value type illustrate redisTemplate.opsForValue() ValueOperations Manipulate String type data redisTemplate.opsForHash() HashOperations Manipulate Hash type data redisTemplate.opsForList() ListOperations Manipulate List type data redisTemplate.opsForSet() SetOperations Manipulate Set type data redisTemplate.opsForZSet() ZSetOperations Manipulate SortedSet type data redisTemplate common commands
Step 1: Import dependencies
<dependencies>
<!--SpringDataRedis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</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>
</plugin>
</plugins>
</build>
illustrate:
This experiment operates in SpringBoot, so import SpringBoot dependencies
Step 2: Add configuration
spring:
redis:
host: 10.13.164.55
port: 6379
password: qweasdzxc
lettuce: # redis默认使用lettuce客户端进行连接
pool:
max-active: 8 # 最大连接
min-idle: 0 # 最小空闲
max-idle: 8 # 最大空闲
max-wait: 200 # 连接等待时间
illustrate:
Configure the Redis configuration file to facilitate SpringBoot automatic assembly
Step 3: Demo
@SpringBootTest
class SpringDataRedisDemoApplicationTests {
@Autowired
RedisTemplate redisTemplate;
@Test
void contextLoads() {
redisTemplate.opsForValue().set("yueyue", "玥玥大美女");
Object o = redisTemplate.opsForValue().get("yueyue");
System.out.println(o.toString());
}
}
illustrate:
Need to use
@Autowired
annotations to implement dependency injection
Notice:
RedisTemplate can receive any Object as a value and write it to Redis, but it will serialize the Object into byte form before writing. The default is to use JDK serialization. The result is as follows
This will make readability worse and take up more memory.
Looking at the source code, I found that the underlying layer uses the ObjectOutputStream object to convert Java objects into bytes.
3.3.3 RedisSerializr serialization
3.3.3.1 Overview
Because the serialization method of SpringDataRedis uses the default JDK serialization, which cannot achieve the way we store data and get what we see and get, so we use custom serialization here.
illustrate:
There are many ways to implement custom serialization. The serialization method of SpringDataRedis uses
JdkSerializationRedisSerializer
serialization by default. It is recommended to use two serialization methods here, one is the serialization method that converts string to stringStringRedisSerializer
, and the other is the method that converts Json to string and vice versa.GenericJackson2JsonRedisSerializer
3.3.3.2 Basic use cases
Step 1: Custom serialization
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
// 创建Template
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// 设置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer =
new GenericJackson2JsonRedisSerializer();
// key和 hashKey采用 string序列化
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
// value和 hashValue采用 JSON序列化
redisTemplate.setValueSerializer(jsonRedisSerializer);
redisTemplate.setHashValueSerializer(jsonRedisSerializer);
return redisTemplate;
}
illustrate:
- At this point, complete the dependency injection of RedisTemplate and rewrite your own logic.
- Connection factory, the SpringBoot framework will automatically complete the injection for us, so the connection factory is used directly here.
Step 2: Demonstration
@SpringBootTest
class SpringDataRedisDemoApplicationTests {
@Autowired
RedisTemplate<String, Object> redisTemplate;
@Test
void testString() {
redisTemplate.opsForValue().set("yueyue", "玥玥,大美女");
Object o = redisTemplate.opsForValue().get("yueyue");
System.out.println(o.toString());
}
@Test
void testObject() {
redisTemplate.opsForValue().set("yueyue", new User("玥玥", 17, "大美女"));
Object o = redisTemplate.opsForValue().get("yueyue");
System.out.println(o.toString());
}
}
illustrate:
- The testString method results are as follows
- The testObject method results are as follows
Notice:
Every time an object value is stored, SpringDataRedis will add a long string of full path class names in order to achieve automatic serialization and deserialization, so it will take up a lot of memory space.
3.3.4StringRedisTemplate usage
3.3.4.1 Overview
In order to save memory space, we will not use JSON serializer to process value, but will use String serializer uniformly, which requires that only String type keys and values can be stored. When Java objects need to be stored, the serialization and deserialization of the objects is done manually .
illustrate:
Manually completing the serialization and deserialization of objects is troublesome, but it can save memory space
3.3.4.2 Basic use cases
Step 1: Import dependencies
<!--SpringDataRedis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.33</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Step 2: Demonstration
@SpringBootTest
class SpringDataRedisDemoApplicationTests2 {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
void testString() {
stringRedisTemplate.opsForValue().set("yueyue", "玥玥,大美女");
Object o = stringRedisTemplate.opsForValue().get("yueyue");
System.out.println(o.toString());
}
@Test
void testObject() {
User user = new User("玥玥", 17, "大美女");
String jsonString = JSON.toJSONString(user); // 此处使用fastJson工具进行对象的序列化与反序列化
stringRedisTemplate.opsForValue().set("yueyue", jsonString);
String result = stringRedisTemplate.opsForValue().get("yueyue");
User resultUser = JSON.parseObject(result, User.class);
System.out.println(resultUser);
}
}
illustrate:
The testString method results are as follows
The testObject method results are as follows