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

Redis Learning Notes (1): commands for string, hash, and list of Redis commonly used data types

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Weixin Official Accounts

Redis is the most common non-relational database in daily development. It can be said that as long as it is a project, it will basically be used. It is often used for data caching, distributed locking, and so on. The basic installation of redis will not be mentioned (in the previous blog build series there is a mention of redis installation, if you can not see), the latter update will talk about the main configuration information in its configuration file.

Redis commonly used data types str, hash, list, set, zset, but the most commonly used should be the first three, this article is used to record and explain the first three data types commonly used commands. Although these commands are rarely used during actual development, understanding them is more conducive to understanding and using redis related APIs.

Redis, why fast?

Why redis is so fast, this is a common interview question, but also the reason why it is used in the project.

redis is written in C language, closer to the underlying programming language redis based on memory storage data, access and storage data are in memory redis single-threaded processing, no lock competition, reduce performance consumption, although it is single-threaded, processing speed is not slow, because it is based on memory to do processing, there is no cumbersome read and write IO process between disks (specific redis single-threaded principle, later will update blog details) redis data type str

String types are the most common, and many simple small projects that cache data may only use this data type.

frequently used commands

set key value [ex seconds] [px milliseconds] [nx| xx]: Store data, key is unique, value is string type, used to store real data information, ex and px indicate the effective time of setting, corresponding units are seconds and milliseconds respectively, nx and xx indicate whether the stored data can be overwritten, if key already exists, return 0, indicating that the setting is not successful, if key does not exist, return 1, indicating that the setting is successful, xx is the default storage mode of set command, which can be overwritten

###directly store data set name joker###plus valid time of 10 seconds set name joker ex 10###plus valid time of 10000 milliseconds set name joker px 10000###not overwritten + valid time set name itcrud ex 10 nx

Note here that when using nx or xx, there needs to be a valid time in front. If you only need to use nx, you don't need to set the valid time, but the command is different. See the setnx command below.

get key: get value according to key

get name

mset keys values: mass storage of key data. If the client has a large amount of data to store at the same time, each data is connected to redis once, which will increase the resource consumption of the connection process and greatly reduce the efficiency. In this case, mass storage can be used.

##Set three pieces of data at the same time, keys are: name, age, blog, values are: joker, 30, blog.itcrud.commset name joker age 30 blog blog.itcurd.com

mget keys: Enter the batch key to get the batch value. Multiple keys can be separated by spaces.

mget name age blog

incr key: key corresponds to value value increasing by 1 operation, such as voting when commonly used, value must be an integer can be

incr age

incrby key increment: the value corresponding to key increases by the specified value, value should also be an integer

incrby age 3

decr key: key corresponds to value minus 1, value must be an integer

decr age

decrby key reduction: key corresponds to value minus the value specified by reduction, value must be an integer

decrby age 1

incrbyfloat key increment: The value corresponding to key is incremented by the specified value. Value can be an integer or a floating point number.

incrbyfloat score 1.1

setnx key value: setting value that cannot be overwritten. When the key already exists, setnx returns 0, indicating that the setting is not successful. If the key does not exist, it returns 1, indicating that the setting is successful.

setnx name joker

strlen key: Get the length of the value corresponding to the key

strlen name

getrange key start end: intercepts a string containing start and end

##The string obtained is "it"set name itcrudgerange name 0 1redis hash of data type

The hash structure is as shown in the figure:

The hash type is well suited for storing some object information. Change field to field name, change field value to value corresponding to filed, where the unique identifier of the data is placed above key.

frequently used commands

hset key field value: setting value

hset user:1 name joker

hmset key fields values: batch setting values

hmset user:1 name joker age 30 blog blog.itcrud.com

hget kye field: Get a single value

hget user:1 name

hmget key fileds: Get values in batches

hget user:1 name age blog

hgetall key: Get all key-value pairs under key

hgetall user:1

hdel key fields: Delete a key-value pair under key, support batch deletion, specify multiple fields

hdel user:1 name age

hlen key: Get the number of key pairs under the current key

hlen user:1

exists key field: Query whether the specified field exists under key,

hexists user:1 name

hkeys key: Get a list of all fileds under key

hkeys user:1

hvals key: Get a list of all values under key

hvals user:1

hincrby key field increment: increment the value corresponding to the field of key. The value added is the value specified by increment. Only integers are supported.

hincrby user:1 age 2

hincrbyfloat key field increment: increment the value corresponding to the field of the key. The increment value is the value specified by increment. It can be an integer or floating point number.

hincrbyfloat user1 score 1.1redis list of data types

List is most commonly used as a queue, a key can store an ordered string queue, a single queue can store 2 to the 32nd power minus 1 element. The basic data structure diagram is as follows:

frequently used commands

push key values: push elements from the right, you can push multiple elements at the same time

##Push it crud a b c from the right

lpush key values: Push elements from the left, you can push multiple elements at the same time

##Push it crud a b c from the left

lrange key start end: Get elements in the specified range according to index, including elements of start and end

##Get the full element, 0 means the first element from the left,-1 means the first element from the right lrange itcrud 0 -1

linsert key before| after pivot value: inserts an element before or after the specified element

##Insert new element mlinsert itcrud before b m

index key: Get the element at the specified index position

lindex itcrud -2

len key: Get the length of the list

llen itcrud

lpop key: pop element from left

lpop itcrud

rpop key: pop element from the right

rpop itcrud

Note: The index of the list still needs to be said, when the index count is from left to right, it starts from 0. But index counts from right to left, starting at-1. As shown below:

summary

All three data types have been described, but there is still a need to add a content here, which is the habit of using redis in our projects and the comparison of other major usage habits.

Three schemes to realize user information storage

Store directly in the form of character strings (decentralized storage), as follows:

set user:1:name jokerset user:1:age 30set user:1:gender male

The disadvantage of this storage is that there are too many redundant keys. We all know that redis is stored in memory. Memory space is very precious. This storage is too wasteful. In addition, this storage is too scattered and is not conducive to use. The disadvantages and advantages are relative, so the storage is more intuitive. But in reality, this advantage is useless.

Serialize objects into strings and store them as follows:

##Serialize user to json string: jsonUserset user:1 jsonUser

Advantages: Simple programming, reasonable serialization, high memory utilization

Disadvantages: There is some overhead in deserializing serialization and establishing connections between client and server. If you only want to modify a field in the user, you need to go through query, deserialize, modify the value, serialize, and reset the setting value.

hmset user:1 name joker age 30 gender male

Advantages: simple and intuitive, compared to serialization memory consumption will be higher, each modification only needs to establish a connection, easy to operate

Disadvantages: to control ziplist and hashtable two encoding conversion, and hashtable will consume more memory

Three ways each have advantages and disadvantages, can be compared to use, there is no absolute advantage, there is no absolute disadvantage, look at the actual project requirements, we use the second way in the project, serialize the object, because json conversion object is very convenient. If the third method is used, the conversion process between data and objects will be more complicated.

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

Internet Technology

Wechat

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

12
Report