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

How to call lua script and print debug information to redislog through redisTemplate by SpringBoot

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how SpringBoot calls lua scripts through redisTemplate and prints debugging information to redislog. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Write the Lua script for the first time, and call the script through springboot's redisTemplate to interact with the application. Unfamiliarity has really been going through for a long time. Now let's sum up the learning process:

The first time I finished writing lua, I thought of how to debug the script when I applied the calling script. After searching the Internet, very few of them can be found.

One way is to debug the script by executing the redis command, invoking the redis client, loading the lua script, and then entering the debug command through an interactive interface based on command line debugging. As follows:

Enter the command at the terminal: redis-cli.exe-- ldb-- eval LimitLoadTimes.lua 1 mykey, myargv

-- necessary parameters for ldb:redis-cli.exe to debug commands

-- eval: tell the redis client to load the Lua script, followed by the path to the lua script (I put it directly in the redis directory)

1: the number of key passed to the Lua script, which I tested as 1

-- mykey: a key value passed by yourself, corresponding to the previous number of 1

-- myargv: parameters passed by yourself except key, which can be multiple.

Note that the comma in the command cannot be ignored, and there should be a space before and after it.

Enter, such as the picture above, was supposed to enter debugging, but after waiting for a long time, there was no interactive command line interface. After looking for it for a long time, I still couldn't find a way, so I had to pause first (if there is a great god in this situation, kneel and solve). In a different way, type the debugging information on the redis log.

Here is how I print debug information when I call the script myself. If there is a better way, please do not hesitate to comment.

1. Select redisTemplate serialization method

First of all, create a redisTemplate, not to mention the specific code, this is relatively simple. Note that you need to set the serialization mode of redisTemplate, and springBoot is java jdk-based serialization by default. If the serialized parameters are passed to the Lua script, they cannot be printed to the redis log normally, and garbled will occur, and it is not convenient to parse the parameters if they are passed as a Map or List. And this serialization takes up a lot of bytes. So change it to JSON serialization and implement it with FastJson.

Paste the redis serialization code below:

Public class FastJsonRedisSerializer implements RedisSerializer {public static final Charset DEFAULT_CHARSET = Charset.forName ("UTF-8"); private Class clazz; public FastJsonRedisSerializer (Class clazz) {super (); this.clazz = clazz;} @ Override public byte [] serialize (T) throws SerializationException {return ofNullable (t) .map (r-> JSON.toJSONString (r, SerializerFeature.WriteClassName) .getBytes (DEFAULT_CHARSET)) .orElseGet ()-> new byte [0]) @ Override public T deserialize (byte [] bytes) throws SerializationException {return Optional.ofNullable (bytes) .map (t-> JSON.parseObject (new String (t, DEFAULT_CHARSET), clazz)) .orElseGet (()-> null);}}

2. Load the script on the application side and set the delivery parameters

In springboot, the DefaultRedisScript class is used to load the script, and the corresponding data type is set to receive the data returned by the lua script. This generic class sets the type of generic type when used, and the result returned by the script is received by what type. Note that this class only receives four types of return types. I didn't notice it before, and I wonder why something went wrong. You can only know by looking at the source code. The screenshot is as follows:

In the lua script, there are two global variables that are used to receive the key values and other parameters passed by the redis application, namely KEYS and ARGV.

It is a list of arrays when passed to KEYS on the application side, and the values in the array are indexed in the lua script.

On the application side, the parameters passed to ARGV can be multiple independent parameters, but corresponding to the Lua script, it is uniformly received by the array ARGV, and the acquisition method is also obtained through the array subscript.

The test code of the application side is affixed below:

@ Service ("luaScriptService") public class LuaScriptServiceImpl implements LuaScriptService {@ Autowired private RedisTemplate redisTemplate1; private DefaultRedisScript getRedisScript; @ PostConstruct public void init () {getRedisScript = new DefaultRedisScript (); getRedisScript.setResultType (List.class); getRedisScript.setScriptSource (new ResourceScriptSource (new ClassPathResource ("luascript/LimitLoadTimes.lua"));} @ Override public void redisAddScriptExec () {/ * List set lua's KEYS * / List keyList = new ArrayList (); keyList.add ("count"); keyList.add ("rate.limiting:127.0.0.1") / * set Lua's ARGV with Mpa [1] * / Map argvMap = new HashMap (); argvMap.put ("expire", 10000); argvMap.put ("times", 10); / * invoke the script and execute * / List result = redisTemplate1.execute (getRedisScript,keyList, argvMap); System.out.println (result);}}

The code sent two key, and a map wrapped argv, when passed to the Lua script, KEYS and ARGV received the object string, so we have to use lua library to do related decoding, we send is serialized with json, using Lua library cjson can be converted into json object. Paste the Lua script code below:

-- get KEYlocal key1 = KEYS [1] local key2 = KEYS [2]-- get ARGV [1], which corresponds to a List.-- on the application side. Note, the string is received here, so it needs to be decoded into table type local receive_arg_json = cjson.decode (ARGV [1]) with csjon library-- returned variable local result = {}-- print log to reids-- note, print log level here Redis.log (redis.LOG_DEBUG,key1) redis.log (redis.LOG_DEBUG,key2) redis.log (redis.LOG_DEBUG, ARGV [1], # ARGV [1])-- get the parameters in ARGV and print local expire = receive_arg_json.expirelocal times = receive_arg_json.timesredis.log (redis.LOG_DEBUG,tostring (times)) redis.log (redis.LOG_DEBUG) Tostring (expire))-- set the value redis.call ("set", key1,times) redis.call ("incr", key2) redis.call ("expire", key2,expire) to redis-- use a temporary variable to store local jsonRedisTemp= {} jsonRedisTemp [key1] = redis.call ("get", key1) jsonRedisTemp [key2] = redis.call ("get", key2) jsonRedisTemp ["ttl"] = redis.call ("ttl") that json,json is to be put into the array to be returned Key2) redis.log (redis.LOG_DEBUG,cjson.encode (jsonRedisTemp)) result [1] = cjson.encode (jsonRedisTemp)-springboot redistemplate receives List. If the returned array content is a json object, you need to convert the json object into a string before the client can receive result [2] = ARGV [1]-return the source parameter content to redis.log (redis.LOG_DEBUG,cjson.encode (result))-print the returned array result If you return here, you need to return return result in characters.

3. Set the log level

In the code, the redis.log () function outputs information to the operation log. Note here that the log level set in the function must be the same as the log level set in the redis.conf configuration file before it can be printed to the file normally. Here I set it to the deubg level. There are four levels that can be set here, which are as follows:

Redis.LOG_DEBUG redis.LOG_VERBOSE redis.LOG_NOTICE redis.LOG_WARNING

On the application side, we set the data type returned by the receiver to be List, so in the Lua script, the returned type corresponds to it with table, and the content in the table variable must be a string before the application can be deserialized and parsed normally. The following figure shows the print information of the return value of the output lua:

At this point, the end, I hope it can also be helpful to the friends who encounter the same problems.

About how SpringBoot calls lua scripts through redisTemplate and prints debugging information to redislog to share here, I hope the above content can be of some help to you, you can learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report