Home >Database >Redis >Introduction to advanced features of redis

Introduction to advanced features of redis

王林
王林forward
2021-01-13 10:11:342118browse

Introduction to advanced features of redis

Redis (Remote Dictionary Server), the remote dictionary service, is an open source log-type, Key- Value database and provides APIs in multiple languages.

(Learning video sharing: redis video tutorial)

1.redis publish and subscribe mode

In addition to providing message queues like list, Redis mode, also provides a set of commands to implement the publish/subscribe mode. For example, Weibo, public accounts, etc. can all be realized through this.

Introduction to advanced features of redis

1.2 Subscription to Channel

The publisher needs to send the message to a place where subscribers can subscribe to the message. This place is the channel. Subscribers can subscribe to one or more channels, and all subscribers to this channel will receive this message.

Open two clients for testing

客户端1 订阅channel1
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1

客户端2 发布一则消息
127.0.0.1:6379> publish channel1 test
(integer) 1

客户端1 订阅消息
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "test"

1.2 Subscribe by rules

Supported? and * placeholders. ? represents one character, * represents 0 or more characters.

Start four redis-cli, one as the publisher of the message, and the other three as subscribers.
Subscriber 1: Subscribe to sports related

psubscribe *sport

Subscriber 2: Subscribe to news related

psubscribe news*

Subscriber 3: Subscribe to weather related

psubscribe new weather*

Publisher:

publish news-sport Kobe
publish news-music jaychou
publish news-weather rain

At this time, subscriber 1 will receive Kobe, subscriber 2 will receive all information, and subscriber 3 will receive rain.

Introduction to advanced features of redis

2.redis transaction

2.1 Why use transaction

We all know that a single command of redis is atomic, but If you need to use multiple commands as an inseparable sequence of operations, you need to use transactions.
For example, using setnx to implement distributed locks, we usually set it first, and then set expire on the key to prevent the lock from being released when an exception occurs in del. After the business is processed, we want these three operations to be used as a set of commands in del. implement.
Redis transactions have two characteristics:

  • Execution in the order of entering the queue

  • will not be affected by other client requests

Redis' transaction design has four commands: multi (start transaction), exec (execute transaction), dicard (cancel transaction), watch (monitor)

2.2 Usage of transaction

Transfer scenario A and B each have 100 yuan, A transfers 10 yuan to B, A subtracts 10 yuan, and B adds 10 yuan

127.0.0.1:6379> set A 100
OK
127.0.0.1:6379> set B 100
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby A 10
QUEUED
127.0.0.1:6379> incrby B 10
QUEUED
127.0.0.1:6379> exec
1) (integer) 90
2) (integer) 110
127.0.0.1:6379> get A
"90"
127.0.0.1:6379> get B
"110"

Open the transaction through the multi command. Transactions cannot be nested. Multiple multi commands have the same effect
After using multi to start a transaction, the client sends multiple commands to the server. These commands will not be executed immediately, but will be placed in a queue. After the exec command is called, the commands in the queue will be executed.
We can use discard to clear the transaction queue.

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 1
QUEUED
127.0.0.1:6379> set k2 2
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> get k1
(nil)
127.0.0.1:6379> get k2
(nil)

When a problem occurs when we execute a transaction, will it be rolled back?

An error occurred before exec (such as command syntax error)

127.0.0.1:6379> clear
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set name test
QUEUED
127.0.0.1:6379> hset user lisi
(error) ERR wrong number of arguments for 'hset' command
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get name
(nil)

An error occurred after exec (using commands of different data types for the same key)

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 1
QUEUED
127.0.0.1:6379> hset k1 a b
QUEUED
127.0.0.1:6379> exec
1) OK
2) (error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> get k1
"1"

Through the above operations, We can know that when an error occurs in a transaction before exec, all operations will be rolled back; if an error occurs after exec, only the wrong command will not be executed.
Why does redis not roll back when there is an error in a transaction?
We can see from the above operation that redis only rolls back when the instruction syntax is wrong, and instruction operation errors are bugs caused by developers. For example: you perform 1 on an int type, and then accidentally 2, Or perform 1 on a string type, rollback is not applicable

2.3 watch instruction

It can provide CAS optimistic locking operation for Redis transactions, that is, multiple threads update a certain variable At this time, the old value will be compared with the memory address. If they are equal, it will be updated to the new value.
We can use watch to monitor one or more keys. If after starting a transaction, at least one of the monitored keys is modified before exec is executed, the entire transaction will be cancelled.

First, client 1 executes watch to monitor the key money, and starts a transaction to increase money by 100

127.0.0.1:6379> set money 1000
OK
127.0.0.1:6379> watch money
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> incrby money 100
QUEUED

Before the transaction ends, client 2 decreases money by 100

127.0.0.1:6379> decrby money 100
(integer) 900

At this time, client 1 ends the transaction, and the value of money has not been increased, but decreased, indicating that the modification of the transaction has failed

127.0.0.1:6379> exec
(nil)
127.0.0.1:6379> get money
"900"

3. Lua script

Lua script is a lightweight script Language, written in C language, is somewhat similar to stored procedures. Why use lua script?

Send multiple commands at one time to reduce network overhead. Redis will execute the script as a whole to ensure atomicity (transactions can be replaced in this way) and script reuse, making it easier for multiple clients to complete the same logic.

3.1 Using

we can use the following command to call the lua script

eval script numkeys [key1 key2 key3 ....] [arg1 arg2 arg3 ....]

eval executes the lua script

script represents the content of the lua script

numkeys key number

[key1 key2 key3 ....] 键名参数,表示在脚本中所用到的那些 Redis 键(key),这些键名参数可以在 Lua 中通过全局变量 KEYS 数组,用 1 为基址的形式访问( KEYS[1] , KEYS[2] ,以此类推)。

[arg1 arg2 arg3 ....] 全局变量,可以在 Lua 中通过全局变量 ARGV 数组访问,访问的形式和 KEYS 变量类似( ARGV[1] 、 ARGV[2] ,诸如此类)

来个简单的例子

127.0.0.1:6379> eval "return {KEYS[1],ARGV[1],KEYS[2],ARGV[2]}" 2 key1 key2 val1 val1
1) "key1"
2) "val1"
3) "key2"
4) "val1"
127.0.0.1:6379> eval "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 val1 val1
1) "key1"
2) "key2"
3) "val1"
4) "val1"

在lua脚本如何调用redis命令呢?
我们可以使用 redis.call(command, key [param1, param2…])进行操作

commond redis的命令,如set,get等key 被操作的键[param1, param2…]表示给key的参数

127.0.0.1:6379> eval "redis.call('mset',KEYS[1],ARGV[1],KEYS[2],ARGV[2])" 2 name age lisi 18
(nil)
127.0.0.1:6379> mget name age
1) "lisi"
2) "18

以上命令等价于 mset name lisi age 18, key的数量为2,2 后面两个值为key,在之后就是args

直接在redis-cli中写lua脚本不够方便,通常我们会把脚本放在文件中,然后执行这个文件
我们在一个目录下新建一个test.lua的脚本,填写以下内容后执行。

root@VM-0-5-centos src]# mkdir testlua
[root@VM-0-5-centos src]# cd testlua/
[root@VM-0-5-centos testlua]# ll
total 0
[root@VM-0-5-centos testlua]# touch test.lua
[root@VM-0-5-centos testlua]# vim test.lua
redis.call('set',KEYS[1],ARGV[1])
return redis.call('get',KEYS[1])
[root@VM-0-5-centos testlua]# redis-cli --eval test.lua 1 myname , Armin
"Armin"

值得注意的是key和arg之间需要加上空格逗号空格(myname , Armin)

3.2 缓存lua脚本

之所以需要缓存lua脚本,这是因为每次调用的时候都将整个脚本传给redis服务端,会产生较大的网络开销。为了解决这个问题,Redis提供了evalsha命令,让开发人员通过脚本内容的SHA1摘要执行脚本。

那么怎么将生成这个SHA1并将脚本内容加载到缓存呢,这就用到script load命令去计算脚本的SHA1摘要并记录脚本到缓存中,执行evalsha时,redis会根据提供的摘要去脚本缓存找到对应脚本内容,如果找到则执行,否则返回错误提示: “NOSCRIPT No matching script. Please use EVAL”

127.0.0.1:6379> script load "return 'Hey boy'"
"3760855b303510c83f0be2e8acfb0be64113ae6e"
127.0.0.1:6379> evalsha 3760855b303510c83f0be2e8acfb0be64113ae6e 0
"Hey boy"
127.0.0.1:6379> script exists 3760855b303510c83f0be2e8acfb0be64113ae6e //判断是否存在
1) (integer)

Redis还给lua脚本的执行提供了超时时间,默认的超时时间为5s,超过5s之后redis会接受其他命令但是会返回一个"BUSY"的错误
可在redis.conf中修改指定参数

lua-time-limit 5000

Redis提供了个script kill的命令来终止正在运行的脚本

127.0.0.1:6379> set name lisi
(error) BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.
127.0.0.1:6379> script kill
OK
127.0.0.1:6379> set name lisi
OK

如果数据进行了修改操作,将无法使用script kill终止脚本,因为违反了原子性。此时只能通过shutdown nosave来强行终止redis。
shutdown nosave 和 shutdown 的区别在于 shutdown nosave 不会进行持久化 操作,意味着发生在上一次快照后的数据库修改都会丢失。

相关推荐:redis数据库教程

The above is the detailed content of Introduction to advanced features of redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete