您的位置:首页 > 运维架构 > Nginx

【nginx+lua高性能web应用开发(二):开发评论模块(ssi+mysql)】

2017-07-12 14:15 323 查看
开发这个模块,是为了解决项目中的实际问题,思考设计的 。

本文原文连接: http://blog.csdn href="http://lib.csdn.net/base/dotnet" target=_blank>.NET/freewebsys/article/details/16944917 转载请注明出处!


前言:

参考了下ngx_lua,Node.js,PHP三个进行的压测对比。
http://bluehua.org/demo/php.node.lua.html

ngx_lua   Time per request: 3.065 [ms]
Node.js   Time per request: 3.205 [ms]
PHP
     Time per request: 5.747 [ms]

从各种性能测试来说ngx_lua似乎在CPU和内存上更胜一筹,同时
ngx_lua出奇的资源消耗比较稳定,不像php那样波动比较大。
ngx_lua和Node.js几乎比php快接近1倍。
同时ngx_lua模型也是单线程的异步的事件驱动的,工作原理和nodejs相同,
代码甚至比nodejs的异步回调更好写一些。
对于ngx的运维和配置相对比nodejs来说更加熟悉和有经验。


1,总体设计思路

完全基于nginx层实现,nginx要开启ssi。
(Server Side Includes:http://wiki.nginx.org/HttpSsiModule
以最快的速度展示页面,使用ssi直接读取数据,不是ajax返回。
服务端使用lua读取数据库内容并显示。

对应用的评论,使用mysql分区,按照itme_id进行hash。
设置成1024个分区,以后方便进行拆库。保证每一个表的数据都不是很大。
(1024)是mysql能设置的最大分区数量。

流程:

ningx 请求 /blog/201311/127.html(博客内容已经静态化了。)



使用ssi将url里面的参数获得调用lua评论模块



lua评论模块,读取数据库。(如果压力大,可以进行拆库,做cache)


2,主要代码

local mysql= require("resty.mysql")  

--评论查询.  

local function query_mysql(sql)  

    local db = mysql:new()  

    db:connect{  

        host = "127.0.0.1",  

        port = 3306,  

        database = "test",  

        user = "root",  

        password = "root"  

    }  

    local res, err, errno, sqlstate = db:query(sql)  

    --使用数据库连接池。保持连接.  

    db:set_keepalive(0, 100)  

    return res  

end  

  

local comment_li = [[  

  

<li id="cmt_" class="row_1">  

    <table width=""><tr>  

        <td class="portrait">  

            <a href="" name="rpl_277051035" class="ShowUserOutline"><img src="http://www.oschina.net/img/portrait.gif"></a>  

        </td>  

        <td class="body">  

            <div class="r_title">  

                %s楼:<b>%s</b>  发表于%s  

            </div>  

            <div class="r_content TextContent">%s</div>  

        </td></tr>  

    </table>  

</li>  

  

]]  

  

--设置顶部内容.  

local comment_html = [[  

  

<div class="Comments" id="userComments">  

<h2>  

    <a name="comments" href="#" class="more">回到顶部</a>  

    <a href="#CommentForm" class="more" style="margin-right:10px;color:#ff3;">发表评论</a>  

    网友评论,共 %s条  

</h2>  

<ul>  

%s  

</ul>  

    <ul class="pager">  

        %s  

    </ul>  

</div>  

  

]]  

  

--设置循环li  

local page_li = [[  

<li class="page %s"><a href="?start=%s#comments">%s</a></li>  

]]  

--输入参数 count start limit ,总数,开始,分页限制  

local function page(count,start,limit)  

    --print(count,start,limit)  

    local page = math.ceil(count/limit)  

    local current_page = math.floor(start/limit) + 1  

    --判断当前页面不超出分页范围.  

    current_page = math.min(current_page,page)  

    current_page = math.max(current_page,1)  

    local is_first = ( current_page == 1 )  

    local is_last = ( current_page == page )  

    --打印页数,开始,结束.  

    local page_offset = 3  

    local start_page = math.max(current_page - page_offset ,1)  

    local end_page = math.min(current_page + page_offset ,page)  

    local page_html = ""  

    if not is_first then  

        page_html = page_html..[[<li class="page prev"><a href="?start=]]  

        page_html = page_html..(current_page-2)*limit  

        page_html = page_html..[[#comments"><</a></li>  

        ]]  

    end  

    for i = start_page , end_page  do  

        local tmp_current = ""  

        if current_page == i then  

            tmp_current = "current"  

        end  

        local tmp_div = string.format(page_li,tmp_current,(i-1)*limit,i)  

        page_html = page_html..tmp_div  

    end  

    if not is_last then  

        page_html = page_html..[[<li class="page next"><a href="?start=]]  

        page_html = page_html..current_page*limit  

        page_html = page_html..[[#comments">></a></li>  

        ]]  

    end  

    return page_html  

end  

  

--接收参数。  

local uri = ngx.var.arg_uri  

--使用正则过滤url中的参数。  

local year,item_id = string.match(uri,"/blog/(%d+)/(%d+).html")  

local start = string.match(uri,"start=(%d+)") or "0"  

  

start = tonumber(start)--将字符串转换成数字。  

local limit = 10  

--拼接sql。  

  

local count_sql = " select count(*) as count from comment where item_id = "..item_id  

local count = query_mysql(count_sql)  

  

if count and #count > 0 then  

    --对数据进行赋值.  

    count  = count[1].count  

else  

    count = "0"  

end  

count = tonumber(count)--将字符串转换成数字。  

  

local sql = " select id,uid,content,create_time from comment where item_id = "..item_id.." limit "..start..","..limit  

local res = query_mysql(sql)  

  

local comment_lis = ""  

for key,val in pairs(res) do  

    local id = val["id"]  

    local uid = val["uid"]  

    local content = val["content"]  

    local create_time = val["create_time"]  

    --拼接字符串.  

    comment_lis = comment_lis..string.format(comment_li,key,uid,create_time,content)  

end  

  

local page_lis = page(count,start,limit)  

local html = string.format(comment_html,count,comment_lis,page_lis)  

ngx.say(html)  

代码将功能实现了。后续可以拆分成多个模块。其中生成分页部分比较复杂。

运行效果:使用了oschina的页面样式。

其中/blog/201311/127.html是静态html页面。

速度超级快。




3,nginx配置

参考:
http://wiki.nginx.org/HttpSsiModule
http://wiki.nginx.org/HttpCoreModule

    gzip  on;  

    ssi on;  

    root /data/comment;  

location /blog/list_comment {  

default_type 'text/html';  

content_by_lua_file '/data/comment/list_comment.lua';  

    }  

location /blog/save_comment {  

default_type 'text/html';  

content_by_lua_file '/data/comment/save_comment.lua';  

    }  

在静态页面中增加ssi代码,这样就可以把uri当做参数传递了。
<!--# include virtual="/blog/list_comment?uri=$request_uri" -->


4,mysql修改打开文件数

因为开启了分区,所以读取文件数量肯定会多。
用ulimit -n查看打开文件数量。如果是1024,修改配置:

/etc/security/limits.conf 然后重启系统

* soft    noproc  65536

* hard    noproc  65536

* soft    nofile  65536

* hard    nofile  65536

然后修改my.conf配置文件:

vi /etc/my.cnf 

[mysqld]

datadir=/var/lib/MySQL

socket=/var/lib/mysql/mysql.sock

user=mysql

symbolic-links=0
open_files_limit=65536

重启mysql生效,查看参数:

mysql> show variables like 'open%';

+------------------+-------+

| Variable_name    | Value |

+------------------+-------+

| open_files_limit | 65536 |

+------------------+-------+

1 row in set (0.00 sec)

数据库表,按照设计成分区表。将数据分散。

CREATE TABLE `comment` (  

  `id` int(11) NOT NULL auto_increment COMMENT '主键',  

  `item_id` int(11) NOT NULL COMMENT '评论项id',  

  `uid` int(11) NOT NULL default '0' COMMENT '评论用户',  

  `content` text NOT NULL COMMENT '内容',  

  `create_time` datetime NOT NULL  COMMENT '创建时间',  

  PRIMARY KEY  (`item_id`,`id`)  

) ENGINE=MyISAM DEFAULT CHARSET=utf8  

PARTITION BY HASH (`item_id`)  

PARTITIONS 1024;  

插入测试数据:
insert into comment(`item_id`,content,create_time) values(127,CONCAT("conent test ",RAND()*1000),now());

源代码放到github上了。

https://github.com/luapkg/comment/

继续完善评论模块。

本文原文连接: http://blog.csdn href="http://lib.csdn.net/base/dotnet" target=_blank>.net/freewebsys/article/details/16944917 转载请注明出处!

来源:http://blog.csdn.net/freewebsys/article/details/16944917
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: