Integrated LUA development Web service in Nginx

Source: Internet
Author: User
Background introduction

In project development, one of the services previously handled was to store the generated data in Redis and the client to obtain specific data from Redis with specific keys. In the previous development, the Nginx+wsgi+python architecture Scheme was adopted. Python can also be used to quickly implement projects, and push to test environments are always in use.
As time passed, slowly thinking about the project, found that in fact, this way of implementation also has some drawbacks. Because there is no complicated logic for the service, Nginx accepts the request to forward to the background Python service, and then the Python service takes the specific request to the Redis to fetch the data and return it to the client call. The whole process is simple and clear, there is no need to add a layer of Python service in the middle of nginx and Redis, so it is not possible to optimize the implementation of this architecture.

Nginx and Lua

Later, after a simple search Nginx+redis found some nginx+lua+openresty related keywords. The next step is to start research on Openresty. View related documents Discovery, Openresty is a project set with an integrated Nginx core module and a variety of third-party modules. If you use Openresty, you avoid the addition of a variety of third-party packages, all of which are inherited into its installation package. This is definitely a good choice for lazy people.

About LUA

Lua is a scripting language, and there is another salutation-glue language. It is a very small language that can be very easily coupled with other languages. With Lua's own features, and his attached language, the features of the two languages in a service are certainly not generally powerful. See some Cow B games in the use of Lua to do a glue-based functional language.
However, by simply using it, it is found that LUA does not handle strings sufficiently, because it uses the C library directly, and its processing of strings is only the interface provided by the C library, and there is no additional enrichment or addition to the interface. In many scenarios, you need to implement some common interfaces, such as split.

Integrated LUA and Ngxin

Since you see LUA as a type of glue, can lua be directly coupled to Nginx? The answer is very positive. Lua can be run directly in Nginx, do some logical processing, log control. Then we can consider using Nginx+lua to develop a Web service to meet the needs, to complete the convenience and rapid development that other service-side languages cannot accomplish.
In addition to the above-mentioned ergodic nature, Nginx+lua will also bring advantages:
1, reduce one layer of forwarding, use other service language to develop services, will certainly use a protocol in Nginx and the server directly to communicate. such as CGI, FCIG, Wsgi and so on. If you are using LUA, because LUA is running directly in Nginx, it is necessary to do an additional nginx forwarding.
2, the event-based response, because LUA is directly running the NGINX runtime environment, then LUA inherits all the features of Nginx. In general, Nginx is an event-based service, select or Epoll. In the performance will certainly be gray often give force.
Based on the above reasons open to engage in Nginx+lua. As lazy people directly adopt the entire Openresty strategy, of course you can also install Nginx alone, then install LUA, and then Nginx_lua_module. After installing the Openresty, we started to write simple tests, in fact, on the openresty GitHub There are also relevant examples, you can directly do some simple test development of the example.
After completing the first step of the installation and the test sample writing, Lua+nginx said that the integration was successful, and then the development of its own business logic. Note here is because the openresty is actually integrated nginx, so on a machine running two nginx may have the corresponding problem, so after installing Openresty, the machine has an existing nginx may have some impact.

Upgrade the original service

The

Development environment is already configured, and the next step is to develop the business logic directly, which is to accept requests to access Redis and read the data back to the client request. Because Lua can be written directly in the Nginx configuration file, but this is not a good strategy. Although Lua is directly coupled with other languages, the degree of coupling also takes into account software engineering-related issues. such as the maintainability of the late code, nginx configuration file readability.
In view of the above reasons, it is also recommended that Lua's functionality be written to a separate file and then declared in the Nginx configuration file to tell Nginx to load and run. On the basis of implementing the function, the degree of coupling and the maintainability of code should be avoided as much as possible.
in a specific implementation, two files take care of the entire service, but also because the service itself is simple.
-redis.conf #redis的host, Port
-init.lua #初始化配置文件
took advantage of the concept of nginx shared memory in the implementation.

--redis.confhost:127.0.0.1port:6379--init.luatmp = {}forin io.lines("lua/redis.conf"doforinstring"([^:]+)"do                table.insert(tmp, i)        endendngx.shared.config:set(tmp[1], tmp[2])ngx.shared.config:set(tmp[3], tmp[4])

Here need to be in the Nginx boot time to redis.conf read, so in Nginx need to add a configuration to inform Nginx startup need to execute Init.lua. In addition, the Nginx Shared memory config is also declared, so the Nginx configuration is as follows

lua_shared1m;init_by_lua_file 'lua/init.lua';

The first step has been completed, is the Redis related configuration read, shared memory declaration and initialization, then the specific logic implementation, dozens of lines of code in minutes.

location/vector{Content_by_lua 'LocalRedis = Require"Resty.redis"LocalServer = Redis:new ()Localconf = Ngx.shared.configLocalOK, err = server:connect (conf:Get("Host"), Conf:Get("Port")) Ngx.header.content_type ="Text/plain"if notOk ThenNgx.Log(NGX. Err, err) ngx.Exit(NGX. http_service_unavailable)EndLocalx = ngx.var.arg_x;Localy = ngx.var.arg_y;Localz = ngx.var.arg_z;ifx = Nilory = Nilorz = = Nil ThenNgx.say("{\\\" ret\\\ ":-1}") Ngx.Exit(NGX. http_service_unavailable)EndLocalKey = Z.."_".. X.."_".. YLocaldata = Server:Get(key)        '; }

Copyright NOTICE: This article is for bloggers original articles, reproduced please indicate the source.

The above describes the Nginx integrated LUA development Web services, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.