Redis allows users to write customized scripts using Lua scripts and run them on the Redis server. Lua is a lightweight scripting language with the advantages of simplicity, efficiency, and scalability. In Redis, Lua scripts can be used for complex data processing, such as data filtering, aggregation, sorting, etc., and can also improve the performance of the Redis server.
Compared with the traditional Redis command method, Lua script has the following advantages:
(2) Reduction Network latency: Consolidate multiple Redis commands into one Lua script, reducing network interaction between the client and the server. At the same time, the Redis server also provides the EVALSHA command, which can cache the SHA1 value of the script in the server. When executing the same script next time, you only need to pass the SHA1 value, which reduces network transmission time.
(2) Atomic operation: Lua script can ensure the atomicity of multiple Redis commands and avoid concurrency problems.
(3) Custom commands: Through Lua scripts, you can expand the Redis command set and implement custom commands.
(1) Complex query: For some complex query requirements, using Lua script can quickly Implemented locally, avoiding the trouble of data processing on the client side.
(2) Calculation logic: For some scenarios that require calculation logic, even if the corresponding calculation command is not provided in Redis, customized calculation logic can be implemented through Lua scripts.
(3) Transaction operation: Lua script can ensure the atomicity of a set of Redis commands, which makes it possible to implement transaction operations on Redis.
(4) Real-time statistics: Lua script can count data in Redis in real time, such as calculating real-time UV, PV and other data.
Redis Lua script can be executed through the EVAL command or EVALSHA command. The specific usage method is as follows:
EVAL script numkeys key [key ...] arg [arg ...] EVALSHA sha1 numkeys key [key ...] arg [arg ...]
Among them, script is the content of the Lua script; numkeys represents the number of key-value pairs that need to be operated in the Lua script; key represents the name of the key value that needs to be operated; arg represents the parameters that need to be operated in the Lua script.
Finally let’s integrate it in java. Here is a simple Lua script Demo that integrates Redis with Spring Boot and implements basic CRUD operations.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
# Redis数据库地址 spring.redis.host=127.0.0.1 # Redis端口 spring.redis.port=6379 # Redis密码(如果没有密码不用填写) spring.redis.password=
Using Lua scripts in Redis requires defining the script first. There are two in Spring Boot Lua scripts can be defined in three ways:
Use string definition in code
Definition in RedisTemplate
Here we use the definition method in RedisTemplate and add the following code to the bean of RedisTemplate:
@Bean public RedisScript<Long> redisScript() { RedisScript<Long> redisScript = new DefaultRedisScript<>(); redisScript.setLocation(new ClassPathResource("lua/RedisCRUD.lua")); redisScript.setResultType(Long.class); return redisScript; }
Among them, RedisCRUD.lua is the Lua script we want to define. This script is used to implement basic CRUD operate.
Next we need to implement RedisService to operate Redis, inject RedisTemplate and redisScript into RedisService, and then implement basic CRUD operations. The following is sample code:
@Service public class RedisServiceImpl implements RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private RedisScript<Long> redisScript; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.delete(key); } public Boolean exists(String key) { return redisTemplate.hasKey(key); } public Long hset(String key, String field, Object value) { return redisTemplate.opsForHash().put(key, field, value); } public Object hget(String key, String field) { return redisTemplate.opsForHash().get(key, field); } public void hdelete(String key, String... fields) { redisTemplate.opsForHash().delete(key, fields); } public Boolean hexists(String key, String field) { return redisTemplate.opsForHash().hasKey(key, field); } public Long eval(String script, List<String> keys, List<Object> args) { return redisTemplate.execute(RedisScript.of(script), keys, args.toArray()); } public Long eval(List<String> keys, List<Object> args) { return redisTemplate.execute(redisScript, keys, args.toArray()); } }
Here we use some methods in RedisTemplate to implement basic CRUD operations, and the eval method to execute custom Lua scripts.
Finally, we need to write the RedisCRUD.lua script. This script is used to implement basic CRUD operations. The following is the sample code:
-- set if KEYS[1] and ARGV[1] then redis.call('SET', KEYS[1], ARGV[1]) return 1 end -- get if KEYS[1] and not ARGV[1] then return redis.call('GET', KEYS[1]) end -- delete if KEYS[1] and not ARGV[1] then redis.call('DEL', KEYS[1]) return 1 end -- exists if KEYS[1] and not ARGV[1] then if redis.call('EXISTS', KEYS[1]) == 1 then return true else return false end end -- hset if KEYS[1] and ARGV[1] and ARGV[2] and ARGV[3] then redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]) redis.call('EXPIRE', KEYS[1], ARGV[3]) return 1 end -- hget if KEYS[1] and ARGV[1] and not ARGV[2] then return redis.call('HGET', KEYS[1], ARGV[1]) end -- hdelete if KEYS[1] and ARGV[1] and not ARGV[2] then redis.call('HDEL', KEYS[1], ARGV[1]) return 1 end -- hexists if KEYS[1] and ARGV[1] and not ARGV[2] then if redis.call('HEXISTS', KEYS[1], ARGV[1]) == 1 then return true else return false end end
In this script, we define 8 operations:
set: set key-value
get: get the value corresponding to the key
delete: delete key-value
exists: determine whether the key exists
hset: set A field-value in the hash
hget: Get the value corresponding to a field in the hash
hdelete: Delete a field in the hash -value
hexists: Determine whether a field exists in the hash
@RunWith(SpringRunner.class) @SpringBootTest public class RedisServiceImplTest { @Autowired private RedisService redisService; @Test public void test() { //第一种方式:执行string的lua redisService.eval("redis.call('SET', KEYS[1], ARGV[1])",Collections.singletonList(hashKey), Collections.singletonList(hashValue)); //第二种方式:执行lua脚本 String key ="key"; String value ="value"; redisService.eval(Collections.singletonList(hashKey), Collections.singletonList(hashValue)); }
The above is the detailed content of What are the Lua script implementation methods and application scenarios in Redis?. For more information, please follow other related articles on the PHP Chinese website!