Lua: Getting Started with Redis users

Source: Internet
Author: User
Tags redis hosting redis server

Transferred from: http://www.oschina.net/translate/intro-to-lua-for-redis-programmers

You may have heard of a scripting language embedded in Redis, but haven't you tried it yourself? This introductory tutorial will let you learn to use the powerful Lua language on your Redis server.

Hello, lua!.

Our first Redis Lua script simply returns a string without interacting with redis in any meaningful way.

Local msg = "Hello, world!" Return msg

This is very simple, the first line of code defines a local variable msg stores our information, and the second line of code indicates that the value of MSG is returned from the Redis server to the client. Save this file to Hello.lua, like this to run:

REDIS-CLI EVAL "$ (cat Hello.lua)" 0

Running this code will print "hello,world!", eval in the first parameter is our LUA script, which we use the Cat command to read our script content from the file. The second parameter is the numeric number of the key of the Redis that this script needs to access. Our simple "Hello Script" does not access any keys, so we use 0

access keys and Parameters

Suppose we want to set up a URL shorthand server. We're going to store each incoming URL and return a unique value so that it can be accessed later by this value.

We will use the Lua script to get a unique identity ID from Redis using Incrand immediately, with this identity ID as the key value stored in a hash of the URL:

Local link_id = Redis.call ("INCR", Key[1]) redis.call ("Hset", keys[2], link_id, argv[1]) return link_id

We'll use the call () function to access Redis for the first time. The call () parameter is the command to Redis: First incr <key>, and then Hset <key> <field> <value>. These two commands will be executed in turn--Redis will not do anything when the script executes, it will run very quickly.

We will visit two LUA tables: Keys and argv. Forms are the only LUA mechanism for associative arrays and structured data. For our intentions, you can think of them as an array of any language you are familiar with, but remind two of the two LUA rule that are easy to get to the novice:

    • The table is based on 1, which means that the index starts with a value of 1. So the first element in the table is mytable[1], and the second one is mytable[2] and so on.
    • The table must not have a nil value. If there is [1, Nil, 3, 4] in an action table, then the result will be [the 1]--table will be truncated at the first nil.

When this script is called, we also need to pass the keys and argv table values:

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 that need to be passed in, followed by the two keys that need to be passed in, and the last pass is the value of argv. When executing a LUA script in Redis, REDIS-CLI checks the number of keys passed in, unless the command is passed in exactly.

To explain more clearly, the following list replaces the key and argv script:

Local link_id = Redis.call ("INCR", "Links:counter") Redis.call ("Hset", "Links:urls", link_id, "/HTTP/ Malcolmgladwellbookgenerator.com ") return link_id
When writing Lua scripts for Redis, each key is specified through the keys table. The argv table is used to pass parameters, in this case argv is used to pass in the URL.
Logical conditions: Increx and Hincrex

The previous example saves the link as a short URL, wants to know the number of clicks on the link, and adds a hash counter to the Redis. When a user with a link tag accesses it, we check that it exists and, if present, need to add 1 to the counter:

If Redis.call ("Hexists", Keys[1], argv[1]) = = 1 Thenreturn redis.call ("HINCR", Keys[1], argv[1]) Elsereturn nilend
Each time someone clicks on a short URL, we run this script to track this link being shared again. We use Eval to invoke the script, pass in Inlinks:visits (Keys[1]) and the link identifier returned by the previous script (Argv[1]).

This script will check for the existence of the same hash, plus 1 for this standard Redis key if it exists.

If Redis.call ("EXISTS", keys[1]) = = 1 Thenreturn redis.call ("INCR", Keys[1]) Elsereturn nilend
Script Loading and registration execution

Note that when Redis is running the Lua script, nothing else can be done! The script is best to simply extend Redis for smaller atomic operations and simple logic control needs, bugs in Lua scripts can trigger an entire Redis server lock-it's best to keep the script short and easy to debug.

Although these scripts are generally short, we do not want to use the full Lua script every time we execute it, but we can actually register the Lua script (or register it at the time of your deployment) in the development process step-by-step (application boots translation is difficult). The call is then made using the SHA-1 identity generated after registration.

REDIS-CLI SCRIPT LOAD "Return ' Hello World '" = "5332031c6b470dc5a0dd9b4bf2030dea6d65de91" Redis-cli Evalsha 5332031c6b470dc5a0dd9b4bf2030dea6d65de91 0=> "Hello World"

The call to script load is usually unnecessary and is implicitly loaded when a program executes Eval. The program will try Eavalsha first, and will call Eval when the script is not found.

For Ruby developers, take a look at Shopify's Wolverine, which simply loads and stores LUA scripts for Ruby applications. For PHP developers, Predis supports the loading of LUA scripts as regular Redis commands (you need to inherit the Predis\command\scriptedcommand base class and register the command). If you use these or other tools to standardize your interaction with LUA, let me know that I am interested in knowing something outside of this article.

When to use Lua

Redis supports blocks such as watch/multi/exec, can perform a set of operations, and can commit execution together, seemingly overlapping with Lua. How should you choose? All operations in the mult block are independent, but in Lua, the subsequent operations can depend on the execution result of the preceding operation. The use of Lua scripting also avoids the situation where the client's response slows after the race condition after watch is used.

In Redisgreen, a foreign service provider that specializes in Redis hosting, we see that many applications use LUA as well as multi/exec, but they are not alternative relationships. Many of the successful LUA scripts are small, implementing only one of your application needs and the Redis command does not have a single function.

Access Library

Redis's LUA interpreter loads seven libraries: base,table,string, Math, Debug,cjson, and Cmsgpack. The first few are standard libraries that allow you to use any language for basic operations. The next two can enable Redis to support JSON and messagepack-, which is a very useful feature, and I also wonder why this usage is often not seen.

Web applications often use JSON as an API to return data, and you might also be able to store a bunch of JSON data in a Redis key. When you want to access some JSON data, you first need to save to a hash, and using Redis's JSON support will be very convenient:

If Redis.call ("EXISTS", keys[1]) = = 1 Thenlocal payload = Redis.call ("GET", Keys[1]) return Cjson.decode (payload) [argv[1] ]elsereturn Nilend

Here we check to see if the key exists and returns nil if it does not exist. If present, obtain the JSON value from Redis, parse it with Cjson.decode (), and return the requested content.

Redis-cli set apple ' {' Color ': ' Red ', ' type ': ' fruit '} ' = ' = OK redis-cli eval ' $ (cat Json-get.lua) "1 apple type=>" Fruit
Load this script into your Redis server and save the JSON data to Redis, usually hash. Although we must parse every time we visit, the operation is actually very fast as long as your object is small.

If your API is only available internally, you usually need to consider the efficiency problem, messagepack is a better choice than using JSON, it is smaller, faster, in Redis (and more so), Messagepack is a better alternative to JSON.

If Redis.call ("EXISTS", keys[1]) = = 1 then  local payload = Redis.call ("GET", Keys[1])  return Cmsgpack.unpack ( payload) [Argv[1]]else  return Nilend
numeric conversions

Lua and Redis each have their own set of types, so it is important to understand the change in value that Redis and Lua call each other at the boundary. A decimal point that comes back to the Redis client when number is returned to integer-is cleared:

Local INDIANA_PI = 3.2return indiana_pi
When you run the script, Redis returns an integer of 3, missing a useful fragment from PI. It looks simple, but you need to be more careful when you start to interact with the intermediate scripts in Redis. For example:
Local INDIANA_PI = 3.2redis.call ("SET", "PI", Indiana_pi) return Redis.call ("GET", "PI")

The result of execution is a string: "3.2", which is why? There is no proprietary numeric type in Redis, and when we first call set, Redis has saved it as a string, and when Lua initializes it, it is lost as the type information for a floating-point number. So when we get this value back, it becomes a string.

In Redis, in addition to INCR and DECR, the data accessed by other Get,set operations is treated as strings. INCR and DECR are operations that are specific to numeric values, and are actually returned as integers (integer) replies (maintaining and storing adherence to numeric rules), but the Redis internal save type is actually a string value.

Summarize:

The following are common errors when using LUA in Redis:

    • The table is an expression in Lua that differs from many popular languages. The first element in keys is keys[1], and the second is keys[2] (not 0 start)
    • Nil is the Terminator of the table, [1,2,nil,3] will automatically change to [+], so 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.
    • Lua numbers will be converted to integers, and the decimal points sent to Redis will be lost and converted to string types before they are returned.
    • Make sure that all keys used in Lua are in the key table, otherwise your script will be at risk of not being well supported in future Redis editions.
    • Lua scripts, like other Redis operations, do not run when the script executes. Consider using a script to protect your Redis server capabilities, but keep it short and useful.
    • Supplementary readings

      Here are a lot of good online resources for Lua and Redis, and this article is just a few of the things I've used:

      • Lua Reference Manual
      • Lua Tutorial Directory
      • EVAL Docs
      • evalsha.com-occasionally have spam, but the content is very good (there are a lot of LUA scripts in the Evalsha way, great, hope to you useful.) )

Lua: Getting Started with Redis users

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.