当前位置:网站首页>Redis Lua script detailed explanation of lua script high frequency interview questions
Redis Lua script detailed explanation of lua script high frequency interview questions
2022-04-21 19:23:00 【A program exception】
Form writing habits together ! This is my participation 「 Nuggets day new plan · 4 Yuegengwen challenge 」 Of the 6 God , Click to see the event details .
Redis stay 2.6 Launched the script function , have access to Lua Language script to Redis perform .
Advantages of scripting :
- Reduce network overhead : Originally 5 Number of network requests , You can use a request to complete , original 5 The second request logic is sent to redis The server completes . Reduce network round-trip delay , This is similar to a pipe .
- Atomic manipulation :Redis The entire script is executed as a whole , The middle is not inserted by other commands .
- replace Redis The transaction function of :Redis The built-in transaction function is very weak , and redis Of lua Scripts implement almost normal transaction functions , It is officially recommended that if you want to use redis The transaction function of can be considered as lua replace .
Script instructions
Through the built-in lua Interpreter , have access to EVAL Command to Lua Script job search , The command format is as follows :
# Script format
EVAL script numkeys key [key ...] arg [arg ...]
# Example
127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 k1 k2 a1 a2
1) "k1"
2) "k2"
3) "a1"
4) "a2"
Copy code
Parameter description :
first script The argument is a segment Lua Script program , He will be run in redis Server context , This script is not necessary ( Should not be ) Define as a lua function .
the second numkeys Parameter is used to specify the number of key name parameters .
Start with the third parameter ( The key parameters key ), Represents those used in scripts Redis key (key), These key name parameters can be found in Lua Through the global variable array KEYS from 1 Start access as base address KEYS[1],KEYS[2].
At the end of the order , Additional parameters that are not key name parameters arg [arg ...] , Can be in lua Through global variables ARGV Array , Subscripts are also derived from 1 Start .
stay Lua You can use redis.call() Function to execute redis command .
Jedis Deduction inventory case call example :
try (Jedis jedis = jedisPool.getResource()) {
// Initialize product id by 100 Inventory of
jedis.set("product_stock_100", "10000");
// @formatter:off
String script = "local count = redis.call('get',KEYS[1]) " +
"local a = tonumber(count) " +
"local b = tonumber(ARGV[1]) " +
"if a >= b then " +
"redis.call('set',KEYS[1],a-b) " +
"return 1 " +
"end " +
"return 0";
// @formatter:on
Object decrResult = jedis.eval(script, Arrays.asList("product_stock_100"), Arrays.asList("100"));
System.out.println(decrResult);
}
Copy code
** Be careful :** Not in lua There are dead loops and time-consuming operations in the script , otherwise **redis It will block **, No other commands will be accepted , Therefore, the above situation shall not occur during use .
Redis Is a single process single thread execution script , The pipe will not block redis .
Redis LUA Will script execution commands roll back ?
Use lua A script can execute a string of redis On command , Achieve certain atomicity (lua During the execution of multiple instructions in the script, new instructions will not be inserted ), however It is not possible to roll back the previous results when there is an error in command execution .
We use the following code snippet to verify , Let's clear it before we execute the code redis data .
127.0.0.1:6379> FLUSHALL
OK
127.0.0.1:6379> KEYS *
(empty array)
Copy code
Then execute the following code , Full code for official account Exception of a program Send keywords LUA obtain .
try (Jedis jedis = jedisPool.getResource()) {
// @formatter:off
String script = " redis.call('SET', 'success','100') "
// simulation redis An exception message appears ,-1 Index in bitmap There is no error reporting
+ " redis.call('SETBIT', 'bit_test','-1','1') "
+ " redis.call('SET', 'fail','100') "
+ " return 1";
// @formatter:on
Object eval = jedis.eval(script);
System.out.println(eval);
}
Copy code
View after execution redis The data in :
127.0.0.1:6379> KEYS *
1) "success"
127.0.0.1:6379> get success
"100"
Copy code
Conclusion : Use lua A script can execute a string of redis On command , Achieve certain atomicity (lua During the execution of multiple instructions in the script, new instructions will not be inserted ), however It is not possible to roll back the previous results when there is an error in command execution .
版权声明
本文为[A program exception]所创,转载请带上原文链接,感谢
https:https://yzsam.com/html/zmsrlb.html
边栏推荐
- APM industry awareness series - III
- 《数字电子技术基础》5.1 触发器概述、5.2 SR锁存器
- Analytic robot intelligent reasoning planning
- Sleuth + Zipkin link tracking
- pfSense使用证书认证配置IPsec站点到站点隧道指南
- Connection of Navicat Mysql to MySQL under Linux and 2003 error resolution
- DVWA-Brute Force
- To deal with doget & dopost Chinese garbled code
- detectron2 中yacs的使用解读
- APM industry awareness series - eight - 25 advantages of Devops
猜你喜欢

What are the factors affecting VPS website optimization?

Robot framework log output Chinese garbled code

Pytoch convolution

自动控制原理第5章——频率法(思维导图)

MySQL de duplication query

Can the stadium system be connected to other intelligent devices

Stm32cupeide / stm32cupemx USB link w25qxx as USB flash disk

使用mRemoteNG工具管理所有远程连接

DVWA-Brute Force

Shandong University project training (IV) adding click events to multiple point markers
随机推荐
Mysql database index interview questions (latest version)
C语言快速排序问题
MKL library matrix multiplication
关系型数据库与非关系型数据库概述,Redis简介、常用命令及优化
大佬们分析一下,为什么这种方式调用函数会慢10倍?
【手部姿态估计】【论文解读】3D Human Pose Estimation in RGBD Images for Robotic Task Learning
STM32cubeide/STM32cubeMX USB链接W25QXX做U盘
APM industry awareness series - III
Research Report on the development of auction industry in 2021
邮件在Exchange中的路由过程
Instructions of crystal Chem mouse glucose detection kit
Apache Doris creates dynamic partitions
Rk3399 - add USB to serial driver
Connection of Navicat Mysql to MySQL under Linux and 2003 error resolution
分布式事务基础
Delete Nan data in matrix or vector in MATLAB
Flitter Xcode packaging and publishing failed error ninety thousand one hundred and sixty-five
Analyzing the practical process of maker Education
Pytoch convolution
Interpretation of Chinese ner using lattice LSTM paper