Integrate lua to develop web services in nginx

Source: Internet
Author: User
: This article describes how to integrate lua to develop web services in nginx. For more information about PHP tutorials, see. Background

During project development, a previously handled service stores the generated data in redis, and the client obtains the specific data in redis through the specific key. In the previous development, nginx + wsgi + python architecture was used. Python can also be used to quickly implement projects and push them to the test environment.
As time passes, I gradually think about the project and find that this implementation method also has some drawbacks. Because there is no complicated logic for the service, nginx receives the request and forwards it to the backend python service. then, the python service obtains the specific request to redis to retrieve the data and return it to the client for calling. The entire process is actually relatively simple and clear. there is no need to add a layer of python service between nginx and redis. Therefore, we are thinking about whether the implementation scheme of this architecture can be optimized.

Nginx and lua

Later, nginx + redis was searched to find some nginx + lua + openresty-related keywords. The next step is to start research on openresty. According to relevant documents, openresty is a project set that integrates the nginx core module and various third-party modules. If openresty is used, you can avoid installing any third-party packages. all of them are inherited into the installation package. This is definitely a good choice for lazy people.

Lua introduction

Lua is a scripting language and also known as the glue language. It is a very small language that can be easily coupled with other languages. Using lua's own features, coupled with the language of his attachment, the features of using the two languages in a service are certainly not very powerful. We can see that some of niub's games are using lua as a glue-type functional language.
However, through simple use, it is found that lua is not powerful enough to process strings, because it directly uses the C library, and its processing of strings is only the interface provided by the C library, no additional enrich or supplement is made to the interface. In many scenarios, you need to implement some common interfaces, such as split.

Integrate lua and ngxin

Because we can see that lua is a glue language, can lua be directly coupled in nginx? The answer is yes. Lua can run directly in nginx to perform logic processing and log control. Therefore, we can consider using nginx + lua to develop a web service to meet our needs, so as to achieve convenient and rapid development that cannot be completed by other server languages.
In addition to the experience mentioned above, what are the advantages of nginx + lua:
1. reduce a layer of forwarding and use other service languages to develop services. a protocol is certainly used for direct communication between nginx and the server. For example, cgi, fcig, and wsgi. If you use lua because lua runs directly in nginx, it is necessary to perform an additional nginx forwarding.
2. event-based response. because lua is the runtime environment for directly running nginx, lua inherits all the features of nginx. In general, nginx provides services based on events, such as select or epoll. The performance will certainly be quite poor.
Start nginx + lua for the above reasons. Because the lazy directly uses the entire openresty installation policy, you can also install nginx separately, then install lua, and then nginx_lua_module. After openresty is installed, a simple test is started. In fact, there are also related examples on openresty github. you can directly perform some simple test and development on the examples.
After completing the first step of installation and test example writing, lua + nginx indicates that the integration has been successful, and the next step is to develop your own business logic. Note that openresty is actually integrated with nginx, so running two nginx servers on one server may cause problems. Therefore, after openresty is installed, the existing nginx on the machine may be affected.

Upgrade original service

The development environment has been configured, and the next step is to directly develop the business logic, that is, accept the request to access redis, read the data and return the client request. Because lua can be directly written in the nginx configuration file, this is not a good policy. Although lua is directly coupled with other languages, the degree of coupling must also consider issues related to software engineering. For example, the maintainability of the later code and the readability of the nginx configuration file.
For the above reason, we recommend that you write the lua function into a separate file, and then inform nginx of loading and running through declaration in the nginx configuration file. On the basis of implementing functions, try to avoid coupling and code maintainability.
In the specific implementation, the whole service is handled by two files, of course, because the service itself is simple.
-Redis. conf# Redis host and port
-Init. lua# Initialize the configuration file
The nginx shared memory concept is used in implementation.

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

Here, you need to read redis. conf during nginx startup. Therefore, you need to add a configuration in nginx to inform nginx that init. lua needs to be executed during nginx startup. In addition, the nginx shared memory config must be declared, so the nginx configuration is as follows:

lua_shared_dict config 1m;init_by_lua_file 'lua/init.lua';

The first step has been completed, that is, the reading of redis-Related configurations, the declaration and initialization of shared memory, then the specific logic implementation, dozens of lines of code done in minutes.

     location  /vector{                content_by_lua '                        local redis = require "resty.redis"local server = redis:new()                        local conf = ngx.shared.config                         local ok, err = server:connect(conf:get("host"), conf:get("port"))                        ngx.header.content_type = "text/plain"ifnot ok then                                ngx.log(ngx.ERR, err)                                ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)                        endlocal x = ngx.var.arg_x;                        local y = ngx.var.arg_y;                        local z = ngx.var.arg_z;                        if x == nil or y == nil or z == nil then                                ngx.say("{\\\"ret\\\": -1}")                                ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)                        endlocal key = z.."_"..x.."_"..y                        local data = server:get(key)                ';        }

Copyright Disclaimer: This article is an original article by the blogger. For more information, see the source.

The above introduces how to integrate lua to develop web services in nginx, including some content. I hope to help some 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.