Use ngx_lua to build highly concurrent applications

Source: Internet
Author: User
: This article describes how to use ngx_lua to build high-concurrency applications. For more information about PHP tutorials, see. This article mainly discusses how to use ngx_lua to perform non-blocking communication with backend memcached and redis.

1. Memcached

Accessing Memcached in Nginx requires the support of the module. HttpMemcModule is used here. this module can communicate with the backend Memcached for non-blocking communication. We know that Memcached is officially provided. this module only supports get operations, while Memc supports most Memcached commands.

The Memc module uses entry variables as parameters for transmission. all variables prefixed with $ memc _ are Memc entry variables. Memc_pass points to the backend Memcached Server.

Configuration:

[Plain] view plaincopyprint?

  1. # Use HttpMemcModule
  2. Location =/memc {
  3. Set $ memc_cmd $ arg_cmd;
  4. Set $ memc_key $ arg_key;
  5. Set $ memc_value $ arg_val;
  6. Set $ memc_exptime $ arg_exptime;
  7. Memc_pass '2017. 0.0.1: 100 ';
  8. }

Output:

[Plain] view plaincopyprint?

  1. $ Curl 'http: // localhost/memc? Cmd = set & key = foo & val = Hello'
  2. $ STORED
  3. $ Curl 'http: // localhost/memc? Cmd = get & key = foo'
  4. $ Hello

This enables access to memcached. The following describes how to access memcached in lua.

Configuration:

[Plain] view plaincopyprint?

  1. # Access Memcached in Lua
  2. Location =/memc {
  3. Internal; # internal access only
  4. Set $ memc_cmd get;
  5. Set $ memc_key $ arg_key;
  6. Memc_pass '2017. 0.0.1: 100 ';
  7. }
  8. Location =/lua_memc {
  9. Content_by_lua'
  10. Local res = ngx. location. capture ("/memc ",{
  11. Args = {key = ngx. var. arg_key}
  12. })
  13. If res. status = 200 then
  14. Ngx. say (res. body)
  15. End
  16. ';
  17. }

Output:

[Plain] view plaincopyprint?

  1. $ Curl 'http: // localhost/lua_memc? Key = Foo'
  2. $ Hello

Access memcached through lua, mainly through sub-requests using a method similar to function call. First, a memc location is defined for communication through the backend memcached, which is equivalent to memcached storage. Because the entire Memc module is non-blocking, ngx. location. capture is also non-blocking, so the entire operation is not blocking.
2. Redis

Access to redis requires the support of HttpRedis2Module. It can also be non-congested with redis. However, the response of redis2 is the native response of redis. Therefore, this response needs to be resolved when used in lua. LuaRedisModule can be used to construct native redis requests and parse the native responses of redis.

Configuration:

[Plain] view plaincopyprint?

  1. # Access Redis in Lua
  2. Location =/redis {
  3. Internal; # internal access only
  4. Redis2_query get $ arg_key;
  5. Redis2_pass '2017. 0.0.1: 100 ';
  6. }
  7. Location =/lua_redis {# LuaRedisParser required
  8. Content_by_lua'
  9. Local parser = require ("redis. parser ")
  10. Local res = ngx. location. capture ("/redis ",{
  11. Args = {key = ngx. var. arg_key}
  12. })
  13. If res. status = 200 then
  14. Reply = parser. parse_reply (res. body)
  15. Ngx. say (reply)
  16. End
  17. ';
  18. }

Output:

[Plain] view plaincopyprint?

  1. $ Curl 'http: // localhost/lua_redis? Key = Foo'
  2. $ Hello

Similar to accessing memcached, you need to provide a redis storage dedicated for querying redis, and then call redis through sub-requests. 3. when accessing Redis, redis Pipeline may need to query multiple keys at the same time. We can use ngx. location. capture_multi to send multiple sub-requests to redis storage, and then parse the response content. However, there is a limit. The Nginx kernel requires that the number of subrequests that can be initiated at a time cannot exceed 50. Therefore, this solution is no longer applicable when the number of keys is greater than 50.

Fortunately, redis provides the pipeline mechanism to execute multiple commands in one connection, which can reduce the round-trip latency of multiple commands. After the client sends multiple commands through pipeline, redis receives and executes these commands sequentially, and then outputs the command results in order. To use pipeline in lua, you need to use redis2_raw_queries of the redis2 module to query native redis requests.

Configuration:

[Plain] view plaincopyprint?

  1. # Access Redis in Lua
  2. Location =/redis {
  3. Internal; # internal access only
  4. Redis2_raw_queries $ args $ echo_request_body;
  5. Redis2_pass '2017. 0.0.1: 100 ';
  6. }
  7. Location =/pipeline {
  8. Content_by_lua 'conf/pipeline. lua ';
  9. }

Pipeline. lua

[Plain] view plaincopyprint?

  1. -- Conf/pipeline. lua file
  2. Local parser = require ('redis. parser ')
  3. Local reqs = {
  4. {'GET', 'one'}, {'GET', 'two '}
  5. }
  6. -- Construct a native redis query, get one \ r \ nget two \ r \ n
  7. Local raw_reqs = {}
  8. For I, req in ipairs (reqs) do
  9. Table. insert (raw_reqs, parser. build_query (req ))
  10. End
  11. Local res = ngx. location. capture ('/redis? '.. # Reqs, {body = table. concat (raw_reqs ,'')})
  12. If res. status and res. body then
  13. -- Parse the native response of redis
  14. Local replies = parser. parse_replies (res. body, # reqs)
  15. For I, reply in ipairs (replies) do
  16. Ngx. say (reply [1])
  17. End
  18. End

Output:

[Plain] view plaincopyprint?

  1. $ Curl 'http: // localhost/pipeline'
  2. $ First
  3. Second

4. Connection Pool

In the previous example of accessing redis and memcached, each time a request is processed, a connection is established with the backend server. after the request is processed, the connection is released. In this process, there will be three handshakes, timewait and other expenses, which is intolerable for high-concurrency applications. The connection pool is introduced here to eliminate this overhead.

The connection pool must be supported by the HttpUpstreamKeepaliveModule module.

Configuration:

[Plain] view plaincopyprint?

  1. Http {
  2. # HttpUpstreamKeepaliveModule
  3. Upstream redis_pool {
  4. Server 127.0.0.1: 6379;
  5. # Connection pools that can accommodate 1024 connections
  6. Keepalive 1024 single;
  7. }
  8. Server {
  9. Location =/redis {
  10. ...
  11. Redis2_pass redis_pool;
  12. }
  13. }
  14. }

This module provides the keepalive command, and its context is upstream. We know that upstream is used for reverse proxy using Nginx. the actual upstream refers to "upstream", which can be redis, memcached, mysql, and other servers. Upstream can define a virtual server cluster, and these backend servers can enjoy load balancing. Keepalive 1024 defines the size of the connection pool. when the number of connections exceeds this value, subsequent connections will automatically degrade to short connections. The connection pool is easy to use. simply replace the original ip address and port number.

Someone once tested that, without using the connection pool, the access to memcached (using the previous Memc module), rps is 20000. After the connection pool is used, rps hits 140000. In actual situations, such a big improvement can not be achieved, but the improvement of 100-200% is still possible.

5. Summary

Here is a summary of access to memcached and redis.

1. nginx provides a powerful programming model. location is equivalent to a function, and sub-requests are equivalent to function calls. location can also send sub-requests to itself to form a recursive model, therefore, this model is used to implement complex business logic.

2. Nginx IO operations must be non-blocking. if Nginx is blocked, the performance of Nginx will be greatly reduced. Therefore, in Lua, you must use ngx. location. capture to send a subrequest to delegate these IO operations to the Nginx event model.

3. use the connection pool whenever possible when a tcp connection is required. This eliminates the overhead of establishing and releasing connections.

The above describes how to use ngx_lua to build a high-concurrency application, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

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.