(Transfer) Lua: get started with redis users

Source: Internet
Author: User
Tags redis version redis server
Maybe you have heard of the script language embedded in redis, but haven't you tried it yourself? This tutorial will help you learn how to use the powerful Lua language on your redis server.

Hello, Lua!

Our first redis Lua script returns only one string, instead of interacting with redis in any meaningful way.
1 Local MSG = "Hello, world! "

View Source
Print?

1 Local link_id = redis. Call ("incr", key [1])

2 Redis. Call ("hset", keys [2], link_id, argv [1])

3 Return link_id


 

We will use the call () function to access redis for the first time. The call () parameter is the command sent to redis: First incr <key>, then hset <key> <field> <value>. These two commands will be executed in sequence-when the script is executed, redis will not do anything and it will run very quickly. We will access two Lua tables: keys and argv. Form is the unique mechanism of Lua for correlated arrays and structured data. For our intentions, you can think of them as an equivalent array of any language you are familiar with, but remind two Lua rules that are easily plagued by beginners:

 

  • The table is 1-based, that is, the index starts with a value of 1. Therefore, the first element in the table is mytable [1], and the second element is mytable [2.
  • The table cannot have nil values. If an operation table contains [1, nil, 3, 4], the result will be [1] -- the table will be truncated in the first nil.
When calling this script, we also need to pass the values of the keys and argv tables:
1 Redis-cli eval "$ (cat incr-and-stor.lua)" 2 links: Counter links: URLs http://malcolmgladwellbookgenerator.com/


 

In the eval statement, 2 indicates the number of keys to be passed in, followed by the two keys to be passed in, and finally the argv value. When executing a Lua script in redis, redis-cli checks the number of incoming keys unless all commands are passed in. To make it clearer, the script with the replaced key and argv is listed below: View Source
Print?

1 Local link_id = redis. Call ("incr", "Links: Counter ")

View Source
Print?

1 If redis. Call ("exists", keys [1]) = 1 then

2 Return redis. Call ("incr", keys [1])

3 Else

4 Return Nil

5 End
  Script Loading and registration executionNote: When redis is running the Lua script, nothing else can be done! It is best to simply extend redis to perform small atomic operations and simple logic control. Bugs in Lua Scripts may cause the entire redis server lock-it is best to keep the script short and easy to debug. Although these scripts are generally short, we still hope that we do not use the complete Lua script every time we execute it. In fact, it is difficult to translate the program step by step) register The Lua script during development (or register it during deployment), and then use the generated SHA-1 ID for calling. View Source
Print?

1 Redis-cli script load "Return 'Hello world '"

 
3

 



Script Loading and registration executionNote: When redis is running the Lua script, nothing else can be done! It is best to simply extend redis to perform small atomic operations and simple logic control. Bugs in Lua Scripts may cause the entire redis server lock-it is best to keep the script short and easy to debug. Although these scripts are generally short, we still hope that we do not use the complete Lua script every time we execute it. In fact, it is difficult to translate the program step by step) register The Lua script during development (or register it during deployment), and then use the generated SHA-1 ID for calling. View Source
Print?

1 Redis-cli script load "Return 'Hello world '"

 
3

 


When to use LuaRedis supports blocks such as watch/Multi/exec. It can perform a group of operations and submit and execute them together, which seems to overlap with Lua. How should I choose? All operations in the mult block are independent, but in Lua, subsequent operations can depend on the execution results of the previous operations. At the same time, the Lua script can avoid slow client response caused by the competition conditions of watch. In redisgreen (a foreign service provider dedicated to providing redis hosts), we can see that many applications use Lua and multi/exec, but they are not an alternative. Many successful Lua scripts are small and only need to be implemented for your application. redis commands do not have a single function.
Access Library
Redis Lua interpreter loads seven databases: Base, table, String, math, debug, cjson, and cmsgpack. The first few are standard databases, allowing you to perform basic operations in any language. The next two functions enable redis to support JSON and messagepack-this is a very useful feature, and I also want to know why this is often not seen. Web applications often use JSON as an API to return data. You may also save a pile of JSON data to the redis key. To access some JSON data, you must first save the data to a hash. It is very convenient to use the JSON support of redis: View Source
Print?

1 If redis. Call ("exists", keys [1]) = 1 then

2 Local payload = redis. Call ("get", keys [1])

3 Return cjson. Decode (payload) [argv [1]

4 Else

5 Return Nil

6 End



Check whether the key exists. If the key does not exist, return nil quickly. If yes, obtain the JSON value from redis, parse it with cjson. Decode (), and return the request content.
1 Redis-cli set Apple '{"color": "red", "type": "Fruit "}'

2 => OK

3

 
Load this script into your redis server and save the JSON data to redis, which is usually hash. Although we have to parse each access, as long as your object is small, this operation is actually very fast. If your API is provided only internally, you usually need to consider efficiency issues. messagepack is a better choice than JSON. It is smaller and faster, messagepack is a better alternative to JSON in redis (also in more cases. View Source
Print?

1 If redis. Call ("exists", keys [1]) = 1 then

2 Local payload = redis. Call ("get", keys [1])

3 Return cmsgpack. Unpack (payload) [argv [1]

4 Else

5 Return Nil

6 End



Numerical ConversionLua and redis have their own set of types. Therefore, it is very important to understand the value changes caused by mutual conversions between redis and Lua at the boundary call. When a number from Lua is returned to the redis client, it becomes an integer-the decimal point after any number is cleared: View Source
Print?

1 Local indiana_pi = 3.2

2 Return indiana_pi



When you run this script, redis returns an integer 3, missing useful segments in pi. It looks simple, but you need to be more careful when you start interacting with redis and intermediate scripts. For example:
1 Local indiana_pi = 3.2

2 Redis. Call ("set", "Pi", indiana_pi)

3 Return redis. Call ("get", "Pi ")



The execution result is a string: "3.2". Why? There is no proprietary value type in redis. When we call set for the first time, redis has saved it as a string, when Lua is initialized, it is lost as the type information of a floating point number. So when we extract this value, it becomes a string. In redis, except for incr and decr, the data accessed by other get and set operations are processed as strings. Incr and decr are special operations on values. In fact, the return value is an integer response (maintenance and storage follow the numerical rules), but the internal storage type of redis is actually a string value.
Summary:The following are common errors when using Lua in redis:
  • A table is an expression in Lua, which is different from many popular languages. The first element in keys is keys [1], and the second element is keys [2)
  • Nil is the table Terminator. [1, 2, nil, 3] is automatically changed to [1, 2]. Therefore, do not use nil in the table.
  • Redis. Call will trigger an exception in Lua. redis. pcall will automatically capture all detected errors and return the error content in the form of a table.
  • All Lua numbers will be converted to integers, And the decimal points sent to redis will be lost. convert them to string type before return.
  • Make sure that all keys used in Lua are in the key table. Otherwise, your scripts will not be well supported in the future redis version.
  • The Lua script is the same as other redis operations. When the script is executed, nothing else can be run. Consider using scripts to protect redis server capabilities, but keep them short and useful.
Additional books Additional booksThere are a lot of good online resources for Lua and redis. This article is only a small part of what I use: Lua reference manuallua tutorial directoryeval docsevalsha.com-occasionally spam, but the content is good: there are a lot of Lua scripts available in evalsha mode. They are awesome and hope to be useful to you .)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.