Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the general commands of Redis

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what are the general commands of Redis". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the general commands of Redis.

What is Redis?

Redis is an open source, in-memory data structure storage system that can be used as database, cache, and messaging middleware. It supports many types of data structures, such as string strings, hash hashes, list lists, set sets, ordered set sorted sets and range query, bitmaps, hyperloglogs and geospatial (geospatial) index radius query.

Redis also has built-in replication (replication), LUA script (Lua scripting), LRU driven event (LRU eviction), transaction (transactions) and different levels of disk persistence (persistence), and provides high availability (high availability) through Redis Sentinel (Sentinel) and automatic partitioning (Cluster).

Well, yes, this is the introduction on the official Chinese website of redis, concise and clear.

What is NoSQL?

We know that redis is a non-relational database NoSQL. And why NoSQL? What is NoSQL?

The age of stand-alone database

When there is not a lot of visits to a website, we can use a database to deal with traffic requests.

Cache + split

With the increase of visits, a database can no longer meet our needs. For higher performance, we add a cache layer in the middle and cluster the database, optimize the structure, and separate read and write.

The cache here is NoSQL, and of course caching is only a function of NoSQL, just like Redis does not just have the function of caching. For example, it can also achieve simple message queues, solve Session sharing, counters, rankings, friendship processing and other functions, it can be seen that Redis is a very powerful tool, let's learn it!

Redis general command

First of all, let's put aside the data types and talk about the general commands about Redis.

Manipulate key and value

Redis is a cached database stored by key value, and all data has its own unique key.

Here, for the convenience of demonstration, I use string-related setting commands

Keys [pattern] gets all the key that meets the requirements. The time complexity is O (n), which is generally not used in production environments, because Redis is single-threaded, and executing time-consuming tasks blocks other tasks. The scan command is generally used instead (non-blocking).

Dbsize gets the number of data currently stored.

Exists key determines whether the key exists or not

Del key deletes specified data

Type key gets the data type of the specified key

Rename key newkey renaming

Expiration time

A lot of data in Redis is used as cached data, and as a cache requires expiration time, which provides a powerful expiration time setting function in Redis.

Expire key seconds sets the expiration time for a key.

Ttl key looks at the remaining time of a key and returns a positive number for the remaining time,-1 for permanent, and-2 for expired or non-existent.

Five basic data types of Redis

I mentioned a lot of other functions that Redis can achieve as a cache, such as counters, rankings, friendships, etc., which are based on the data structure of Redis. There are five basic data structures in the whole Redis (and some advanced data structures will be discussed later). They are the string strings, the hash hashes, the list lists, the collection sets, and the ordered collection sorted sets.

String string

String string types are available in most programming languages and are essential for Redis as a database.

Set key value setting valu

Get key gets the value of a key

Mset key1 value1 key2 value2 is set in batch and is atomic, so it can be used to reduce network time consumption.

Mget key1 key2 is acquired in batch and is atomic, so it can be used to reduce network time consumption.

Incr key increments the value of the specified key

Decr key subtracts the value of the specified key

Incrby key value increments the specified value

Decrby key value subtracts the specified value

Incrbyfloat key floatvalue increases the specified floating point number, and the first few operations can be used to implement the function of the counter.

If the key does not exist in setnx key value, it can be set successfully, otherwise it will fail, plus the expiration time limit, it is a way for redis to implement distributed locks (mentioned later).

On the contrary, set key value xx is set successfully if it exists, otherwise it fails (equivalent to an update operation)

Hash

In fact, we can understand that hash is a small Redis. Redis is similar to HashMap in Java in the underlying implementation, using the two-dimensional structure of array + linked list.

The difference is that dictionary values can only be strings in Redis, and they rehash in a different way, using progressive rehash in Redis.

The old and new hash dictionaries will be retained during rehash. During data migration, the contents of the old dictionary will be migrated to the new dictionary bit by bit, and two hash dictionaries will be queried at the same time. The new dictionary will not be replaced until all the data has been migrated.

Let's take a look at the basic operations of hash.

Hset key field value sets the value of a key in the dictionary

Hsetnx key field value sets the value of a key in the dictionary (does not exist)

Hmset key field1 value1 field2 value2... Batch setup

Hget key field gets the value of a key in the dictionary

Hmget key field1 field2 batch acquisition

Hgetall key gets all

Hdel key field deletes a key

Hexists key field judges whether it exists or not.

Hlen key gets the number of storage in the dictionary corresponding to the specified key

Hvals key returns all value

Hkeys key returns all key

Hincrby key field increValue increases the value of a value (you can also increase a negative number)

Hincrbyfloat key field floatValue increases the value of a value (floating point)

List

The list in Redis is equivalent to the LinkedList (two-way linked list) in Java, that is, the underlying layer is implemented through linked lists, so insert and delete operations are fast for list, but index positioning is very slow.

Redis provides many operations for list, such as out, in, etc., you can make full use of them to implement a stack or queue.

Let's take a look at the basic operations of list.

Lpush key item1 item2 item3... Enter the stack from the left

Rpush key item1 item2 item3... Enter the stack from the right

Lpop key exit the stack from the left

Rpop key exit the stack from the right

Lindex key index gets the element O (n) of the specified index with caution

Lrange key start end gets the specified range of elements O (n) use with caution

Linsert key before | after item newitem adds a new element before or after the specified element

Lrem key count value deletes an element with a specified value of value

Count = 0: delete all elements with a value of value

Count > 0: delete elements with count value of value from left to right

Count < 0: delete from right to do | count | elements with a value of value

Ltrim key start end retains the specified range of elements

Lset key index newValue updates the value of an index

Blocking if blpop key timeout is not available (timeout specifies that a blocking time of 0 means permanent)

Blocking without brpop key timeout (timeout specifies a blocking time of 0 for permanent) these two can be used to implement consumer producers.

To sum up, we can use left in and out or right in left out to implement the queue, left in left out or right in right out to implement the stack.

Set

The set in Redis is equivalent to the HashSet (unordered set) in Java, in which the elements can not be repeated, we can use it to achieve some deduplication functions. We also have several sets to take intersection, take and merge and other operations, these operations can get common friends between different users, common interests and so on.

Let's take a look at some basic operations about set.

Sadd key value add element

Sdel key value deletes an element

Sismember key value determines whether it is an element in a collection

Srandmember key count randomly gets a specified number of elements (does not affect the collection structure)

Spop key count randomly pops elements from the collection (destroys the binding structure)

Smembers key gets the O (n) complexity of all elements of the set

Scard key gets the number of collections

Sinter set1 set2... Get the intersection in all collections

Sdiff set1 set2... Get the difference sets in all collections

Sunion set1 set2... Get the union in all collections

Zset

Zset in Redis is an ordered collection, through which you can achieve many interesting functions, such as student performance rankings, video playback rankings, and so on.

Jump tables are used in zset, and we know that only continuous spaces like arrays can be quickly located using binary lookups, while linked lists are not allowed. The jump list saves a lot of time when looking up the linked list (using the jump way to traverse the index for orderly insertion). If you don't know about the jump list, you can do some tutoring.

Transactions and pipes in Redis

Pipeline Pipeline

In some scenarios, we may need to execute multiple commands in one operation, but if we only execute one command, it will waste a lot of network time, and if we transfer the command to Redis at once and then execute it, it will reduce a lot of overhead time.

However, it is important to note that commands in pipeline are not executed atomically, which means that commands in pipes may be interspersed with other commands when they arrive at the Redis server.

Business

Relational database has ACID characteristics, Redis can guarantee A (atomicity) and I (isolation), D (persistence) depends on whether there are configured RDB or AOF persistence operations, but can not guarantee consistency, because Redis transactions do not support rollback.

We can simply understand that the transaction in Redis has only one more atomic operation than Pipeline, that is, it will not be divided by other commands, as shown in the figure above.

Flag for the start of a multi transaction

Exec transaction execution

Discard clears all commands that are queued in this transaction, that is, to release the entire transaction.

Watch key monitors an element before the transaction starts, and if the value of the element is changed by another client when the transaction is committed, the transaction will fail.

Unwatch key relieves monitoring

Thank you for your reading, the above is the content of "what are the general commands of Redis". After the study of this article, I believe you have a deeper understanding of what the general commands of Redis have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report