Introduction to common redis commands

I. Redis command

Redis supports five data (structure) types: string, hash, list, set and Zset

Common command key management

keys  *	: Returns all keys that are satisfied ,Fuzzy matching, for example keys  abc* representative abc initial  key
exists key : Does the specified exist key,Returns 1 if it exists and 0 if it does not exist
expire key second: Set a key The expiration time of is seconds
del key:Delete a key
ttl key: view remaining time,When key If it does not exist, return -2;Returns when the remaining lifetime exists but is not set -1,Otherwise, it returns in seconds key Remaining survival time of.
persist key: Cancel past time
PEXPIRE key milliseconds modify key The expiration time of is milliseconds
select :  The selected database is 0-15(Default (16 databases in total) s
 Designing multiple databases is actually for database security and backup
move key dbindex :  Transfer the data in the current data key Transfer to another database
randomkey: Return one at random key
rename key key2: rename key
echo: Print command
dbsize: View database key quantity
info: View database information
config get * Transmit and store the received request in real time and return the relevant configuration	
flushdb : Empty the current database
flushall : Empty all databases

DEL key

This command is used in key Delete when present key.  

EXISTS key

Check given key Whether it exists. 

EXPIRE key seconds

For given key Set the expiration time in seconds. 

PEXPIRE key milliseconds

set up key Expires in milliseconds.

TTL key

Returns the given in seconds key Remaining lifetime of(TTL, time to live) 

PTTL key

Returns in milliseconds key The remaining expiration time of the.

KEYS pattern

Find all that match the given pattern( pattern)of key .  
keys wildcard     Get all and pattern Matching key,Returns all that match the 
  Wildcard: 
         *  On behalf of all 
         ? Represents a character 

RENAME key newkey

modify Key Name of

MOVE key db

The current database key Move to a given database db among 

TYPE key

return key The type of value stored

Application scenario

EXPIRE key seconds

1. Limited time offer information
2. Website data cache (for some data that needs to be updated regularly, such as leaderboard)
3. Mobile phone verification code
4. Limit the frequency of visitors to the website (e.g. up to 5 visits per second)

Naming suggestions for Key

A single redis key can be stored in 512M

  • 1. The key should not be too long. Try not to exceed 1024 bytes, which will not only consume memory, but also reduce the efficiency of search;

  • 2. The key should not be too short. If it is too short, the readability of the key will be reduced;

  • 3. In a project, it is better to use a unified naming mode for key, such as user:123:password

  • 4.key names are case sensitive

II. Redis data type

String type

brief introduction

string type is the most basic data type of Redis. One key can store 512MB at most.

String data structure is a simple key value type. Value is not only a string, but also a number. It is a special type containing many types,

The string type is binary safe. This means that the redis string can contain any data.
For example, serialized objects are stored, for example, a picture is stored in binary, such as a simple string, value, etc.

String command

Assignment syntax:
  SET KEY_NAME   VALUE: (Description: multiple settings name Will cover) (Redis SET Command to set a given key Value of. If key The value has been stored, SET Overwrites the old value and ignores the type)
  
Command:
  SETNX key1 value:(not exist) If key1 If it does not exist, set the value and return 1. If key1 If it exists, no value is set and 0 is returned;(One of the solutions to distributed locking,Only in key Set when not present key Value of. Setnx(SET if Not eXists) Command in the specified key When it does not exist; otherwise key Specified value)
  
  SETEX key1 10 lx :(expired) set up key1 The value of is lx,The expiration time is 10 seconds. After 10 seconds key1 Clear( key (also clear)
 
  SETRANGE string range value: Replace string
  

 
Value syntax:
 GET KEY_NAME :Redis GET Command to get the specified key Value of. If key Does not exist, return nil . If key The stored value is not of string type and an error is returned.
 GETRANGE key start end :Used to get the information stored in the specified key Substring of the string in. The interception range of the string is determined by start and end Two offsets determine(include start and end included)

GETBIT key offset :yes key Gets the bit at the specified offset from the stored string value(bit)

GETSET Syntax:  GETSET  KEY_NAME  VALUE :Getset The command is used to set the specified key And return key Old value of,When key If it does not exist, return nil 

STRLEN key :return key The length of the stored string value


Delete value syntax:
DEL KEY_Name :Delete the specified KEY,If present, returns the numeric type of the value.

Batch write: MSET k1 v1 k2 v2 ... Write multiple values at once
 Batch read: MGET k1 k2 k3

GETSET name value :One time setting and reading (return the old value and write the new value))

Self increasing/Self subtraction:
INCR KEY_Name :Incr Command will key The numeric value stored in is incremented by 1. If key No, then key The value of is initialized to 0 before execution INCR operation 
 Self increment: INCRBY KEY_Name :Increment value Incrby Command will key The number stored in the plus the specified increment value 
 Self subtraction: DECR KEY_NAME       or    DECYBY KEY_NAME Impairment :DECR Command will key Subtract 1 from the number stored in
 
 :(Pay attention to these key The corresponding must be a numeric string,Otherwise, an error will occur,)

String splicing: APPEND  KEY_NAME VALUE 
 :Append Command for the specified key Append to the ending. If it does not exist, assign a value to it

String length :STRLEN key

Application scenario

  • 1. String is usually used to hold single string or JSON string data
  • 2. Because String is binary safe, you can store the contents of an image file as a String
  • 3. Counter (general key value cache application. General count: number of microblogs and fans)

The INCR and other instructions have the characteristics of atomic operation, so we can use the INCR, INCRBY, DECR, DECRBY and other instructions of redis to realize the effect of atomic counting. If, in a certain scenario, three clients read the value of mynum at the same time (the value is 2), and then add 1 to it at the same time, then the final value of mynum must be 5.
Many websites use this feature of redis to realize the statistical counting requirements of business.

Hash type

brief introduction

Hash Type is String Type field and value Mapping table, or a String Gather. hash It is especially suitable for storing objects. In contrast, storing an object type in Hash Type to store in String Type takes up less memory space and accesses the whole object.
Can be regarded as having KEY and VALUE of MAP Container, which is very suitable for storing the information of value objects, 
For example: uname,upass,age Wait. This type of data takes up very little disk space (compared to JSON). 
Redis Each hash It can store the 32nd power of 2  - 1 Key value pairs (more than 4 billion)

Hash command

Common commands

Assignment syntax: 
 HSET KEY  FIELD VALUE    :For the specified KEY,set up FILD/VALUE  
 HMSET KEY FIELD VALUE [FIELD1,VALUE1]...... :Multiple at the same time field-value (field-value)Set to hash table key Yes. 
 
Value syntax: 
  HGET KEY FIELD   :Get stored in HASH Values in, according to FIELD obtain VALUE
  HMGET KEY field[field1]      :obtain key Values for all given fields 
  HGETALL KEY      :return HASH All fields and values in the table 
	
HKEYS KEY  :Gets the fields in all hash tables
HLEN KEY   :Gets the number of fields in the hash table

Delete syntax: 
   HDEL KEY field1[field2]    :Delete one or more HASH Table field 

Other syntax:
HSETNX key field value :Only in field field Sets the value of the hash table field when it does not exist

HINCRBY key field increment :Is a hash table key The integer value of the specified field in plus the increment increment . 

HINCRBYFLOAT key field increment  :Is a hash table key The floating-point value of the specified field in plus the increment increment . 

HEXISTS key field  :Hash table view key Whether the specified field exists in

Application scenario

Application scenario of Hash: (store an object data)
1. Often used to store an object
2. Why not use string to store an object?

	hash It is the data type closest to the relational database structure. It can convert a record in the database or an object in the program into hashmap Store in redis Yes.
user ID Found for key,Stored value The user object contains name, age, birthday and other information. If you use ordinary key/value There are two main storage methods:
    The first way is to connect users ID As find key,Encapsulate other information into an object and store it in a serialized way. The disadvantage of this way is that it increases serialization/The cost of deserialization, and when one item of information needs to be modified, the whole object needs to be retrieved, and the modification operation needs to protect concurrency CAS And other complex problems.
    The second method is to save as many members as the user information object has key-value Yes, use the user ID+The name of the corresponding attribute is used as the unique identifier to obtain the value of the corresponding attribute. Although the serialization overhead and concurrency problems are eliminated, the user ID For repeated storage, if there is a large amount of such data, the memory waste is very considerable.

Summary:
The Hash provided by Redis solves this problem very well. In fact, the Value stored in Redis's Hash is a HashMap,

It also provides an interface to directly access the Map member

Introduction and comparison of three commonly used redis clients

Jedis api online: http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html

Reisson official website address: https://redisson.org/

redisson git project address: https://github.com/redisson/redisson

Lettuce official website address: https://lettuce.io/

lettuce git project address: https://github.com/lettuce-io/lettuce-core

First, after spring boot2, lettuce is adopted by default for redis connection support. This explains the advantages and disadvantages of lettuce and Jedis to a certain extent.

Concept:

Jedis: It's old-fashioned Redis of Java Implement the client and provide a more comprehensive Redis Command support,
Redisson: It realizes distributed and scalable Java Data structure.
Lettuce: senior Redis The client is used for thread safety, synchronization, asynchrony and response, and supports clustering, Sentinel,Pipes and encoders.

advantage:

Jedis: Relatively comprehensive Redis Operating characteristics of
Redisson: Encourage users to Redis The separation of concerns provides many distributed related operation services, such as distributed locks and distributed collections Redis Support delay queue
Lettuce: be based on Netty The event driven communication layer of the framework, whose method calls are asynchronous. Lettuce of API Is thread safe, so you can operate on a single Lettuce Connect to complete various operations

Scalable:

Jedis: Use blocked I/O,And its method calls are synchronous, and the program flow needs to wait sockets Finished processing I/O Can be executed. Asynchronous is not supported. Jedis The client instance is not thread safe, so it needs to be used through the connection pool Jedis. 
Redisson: be based on Netty The event driven communication layer of the framework, whose method calls are asynchronous. Redisson of API Is thread safe, so you can operate on a single Redisson Connect to complete various operations
Lettuce: be based on Netty The event driven communication layer of the framework, whose method calls are asynchronous. Lettuce of API Is thread safe, so you can operate on a single Lettuce Connect to complete various operations
lettuce Can support redis4,need java8 And above.
lettuce Is based on netty Realized and redis Synchronous and asynchronous communication.

lettuce and jedis comparison:

jedis Make direct connection redis server,If it is non thread safe in a multithreaded environment, only the connection pool can be used at this time jedis Add physical connection to the instance;
lettuce Your connection is based on Netty , connection instance( StatefulRedisConnection)It can be accessed concurrently between multiple threads, StatefulRedisConnection It is thread safe, so a connection instance can meet the concurrent access in multi-threaded environment. Of course, this is also a scalable design. If a connection instance is not enough, you can also add connection instances as needed.
Redisson It realizes distributed and scalable Java Data structures, and Jedis In contrast, the function is relatively simple. It does not support string operation, sorting, transaction, pipeline, partition, etc Redis characteristic. Redisson The purpose of is to promote users' understanding of Redis Separation of concerns, so that users can focus more on processing business logic.

Summary:

priority of use Lettuce,If you need distributed locks, distributed collections and other distributed advanced features, add Redisson Use in combination because Redisson It has poor support for string operation.
In some highly concurrent scenarios, such as second kill, ticket grabbing and rush purchase, there is competition for core resources and commodity inventory. If the control is not good, the inventory may be reduced to a negative number, oversold, or produce the only increase ID,because web For applications that are deployed on more than 1000 machines, it is impossible to add locks for synchronization/s Because of concurrency, the database may change from row lock to table lock, and the performance will degrade severely. Well, relatively speaking, redis Distributed locks, relatively speaking, are a good choice, redis Officially recommended Redisson It provides distributed locks and related services. 

Some Java clients are listed on the official website, including Jedis / Redisson / jredis / JDBC redis, among which Jedis and Redisson are officially recommended. Commonly used Jedis.

Keywords: Java Redis

Added by zypher11 on Fri, 04 Mar 2022 01:09:00 +0200