Ngx_lua Configuration and application

Source: Internet
Author: User

I. Description

There is no introduction to the LUA language itself and its compiler runtime environment, and all of the following prerequisites are known about LUA.

ii. introduction of Ngx_luaprinciple

Ngx_lua embeds LUA into Nginx, allowing Nginx to execute LUA scripts and handle requests with high concurrency and non-blocking. Lua built-in, so that it is good to change the asynchronous back to the form of sequential calls. Ngx_lua IO operations in Lua are delegated to Nginx's event model for non-blocking calls. Developers can write the program in a serial way, Ngx_lua will automatically interrupt the blocking IO operation, save the context, and then delegate the IO operation to the Nginx event processing mechanism, after the IO operation is completed, Ngx_lua resumes the context, the program continues to execute, These actions are transparent to the user program.

Each nginxworker process holds a LUA interpreter or Luajit instance, which is shared by all requests processed by the worker. The context of each request is segmented by the LUA lightweight process, ensuring that individual requests are independent.

Ngx_lua uses the "one-coroutine-per-request" processing model, for each user request, the Ngx_lua wakes up a process that is used to execute the user code processing request and the process is destroyed when the request processing is complete. Each coprocessor has a separate global environment (variable space) that inherits from the globally shared, read-only "Comman data". Therefore, any variable injected into the global space by user code does not affect the processing of other requests, and these variables are freed after the request processing is complete, so that all user code is run in a sandbox, which has the same life cycle as the request.

Thanks to the support of the LUA coprocessor, Ngx_lua only requires very little memory to handle 10,000 concurrent requests. According to the test, Ngx_lua only needs 2KB of memory to process each request, and less if you use Luajit. So Ngx_lua is ideal for implementing scalable, high-concurrency services.

Co-process

The association is similar to a multi-threading, and the difference between multithreading is:

    1. The process is not an OS thread, so creating and switching costs are smaller than threads.
    2. The process has its own stack, local variables, and so on, but the stack of the threads is simulated in the user processes space, so the cost of creating and switching is very small.
    3. multithreaded programs are executed concurrently by multiple threads, that is, there are multiple control flows executing at a moment. And the process is to emphasize a multi-process collaboration between the relationship, only when one of the process actively abandons the execution, the other can get execution, so in a moment, there is only one in a number of processes running.
    4. Because there is only one running on multiple processes, access to the critical section does not require locking, and the multithreading situation must be locked.
    5. Multi-threaded programs have multiple control flows, so the behavior of the program is not controllable, and the execution of multiple threads is defined by the developer and therefore controllable.

Nginx Each worker process is on the event model such as Epoll or kqueue, encapsulated into a coprocessor, each request has a process to handle. This is exactly the same as the LUA model, so even if Ngx_lua needs to execute LUA, the relative C has some overhead, but it can still guarantee high concurrency.

Second, Ngx_lua installation

Nginx installation Ngx_lua need to install Luajit,ngx_devel_kit,ngx_lua and other installation files, we use the openresty here, the internal integration Ngx_lua, no need to install any modules.

iii. usage of Ngx_lua

Nested LUA scripts

location /lua {set $test "hello, world";content_by_lua ‘ ngx.header.content_type = "text/plain"; ngx.say(ngx.var.test);‘;}

$ Curl ' Http://134.32.28.134:8888/lua ', Output Hello, world.

Include Lua file

The script file method for include Lua in Nginx, such as:

 location /mytest { content_by_lua_file conf/alcache.lua; }

Where you write Lua scripts in Alcache.lua.

Iv. processing of sessions using LUA combined with distributed cache in practice

Here the Redis and memcache support is not called Nginx's own Redis and Memcache module, is called Openresty internal integration of the third-party module

nginx.conf Partial configuration

location /login { content_by_lua_file conf/alcache.lua; }

Alcache.lua Configuration

LocalKey=Tostring(Ngx.Var.Arg_username)LocalVal=Tostring(Ngx.Var.Arg_password)LocalPasslogin=Tostring(Ngx.Var.Arg_passloginflag)Localflog==Tostring(Ngx.Var.Arg_flagsOr 0)LocalExptime=Tostring(Ngx.Var.Arg_exptimeOr 0)LocalSessionId=Tostring(Ngx.Var.Cookie_jsessionid)Ngx.Say("SessionId:",SessionId)Ngx.Say("Key:",Key)Ngx.Say("Val:",Val)If (Key== Nil andVal== Nil) Then Return End--If (Passlogin== Nil OrSessionId== Nil) Then Return EndLocalMemcached= Require("Resty.memcached")--LocalRedis= Require("Resty.redis") LocalCache,Err=Memcached:New()--LocalCache,Err=Redis.New()If NotCacheThenNgx.Say("Failed to instantiate cache:",Err) ReturnEndCache:Set_timeout(1000)LocalOk,Err=Cache:Connect("134.32.28.134",11211)--LocalOk,Err=Cache:Connect("134.32.28.134",6379)If NotOkThenNgx.Say("Failed to connect:",Err) ReturnEndLocalRes,flog=,Err=Cache:Get(Key)IfErrThenNgx.Say("Failed to get",Key," : ",Err) ReturnEndIfResandTostring(Res) ~=SessionIdThenCache:Delete(Key)Cache:Set(Key,SessionId,Exptime,Flags)ElseCache:Set(Key,SessionId,Exptime,flog=)EndLocalOk,Err=Cache:Close() If not OK then Ngx.say (, err< Span class= "pun" >)  return end local URL = Ngxvar. URI local res = Ngx.< Span class= "PLN" >location. ( "/proxy"       

Ngx_lua Configuration and application

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.