OpenResty应用-数据库访问

发布于:2022-12-29 ⋅ 阅读:(555) ⋅ 点赞:(0)

OpenResty应用

OpenResty是一个基于Ngin与Lua的高性能Web平台,集成了大量Lua库、第三方模块及大多数依赖项,可以方便地搭建能够处理超高并发、扩展性极高的动态Web应用、Web服务和动态网关。

访问Mysql

参考:http://t.zoukankan.com/forezp-p-9852101.html

数据库ddd_cargo表中数据:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yYE0nLsX-1661495522973)(E:\pic\image-20220826101932706.png)]

Lua脚本askmysql.lua如下:

local function close_db(db)
		if not db then
				return
			end
			db:close()
		end	

local mysql = require("resty.mysql")  
local db, err = mysql:new()  
if not db then  
    ngx.say("new mysql error : ", err)  
    return  
end  
db:set_timeout(1000)
local props = {  
    host = "127.0.0.1",  
    port = 3306,  
    database = "sq-test",  
    user = "root",  
    password = "123456"  
}  
local res, err, errno, sqlstate = db:connect(props)
if not res then  
   ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
   return close_db(db)  
end    
local select_sql = "select id,description from ddd_cargo"
res, err, errno, sqlstate = db:query(select_sql)

if not res then	
	ngx.say("select rows error:",err,",errno:",errno,",sqlstate:",sqlstate)
	return close_db(db)
end
for i, row in ipairs(res) do  
   for name, value in pairs(row) do  
     ngx.say("row details-", i, " : ", name, ":", value)  	 
   end  
   ngx.say("<br/>")
end   
close_db(db)

在nginx.conf中配置访问地址:

http {
    include       mime.types;
    default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;

# test demon by sunquan
 server {
    listen       9090;
	location /test1 {
			default_type text/html;
			charset utf-8;
			#content_by_lua 'ngx.say("<p>Hello,World!</p>")';
			content_by_lua_file testcode/askmysql.lua;
		}
	
	}
	.....

访问地址:http://localhost:9090/test1,可以看到数据库中的数据已经能够正常返回

在这里插入图片描述

针对上述的打印完善一下,

for i, row in ipairs(res) do  
   ngx.say("row details-",i)
   for name, value in pairs(row) do  
     ngx.say(name, ":", value,"\t")  	 
   end  
   ngx.say("<br/>")
end  

nginx.exe -s stop 并重启OpenResty

在这里插入图片描述

其它应用场景

http://www.gosanye.com/post/10951.html
https://www.jianshu.com/p/b2dcd5d02e76
https://blog.csdn.net/chundian0058/article/details/100820145
https://www.w3cschool.cn/openresty1/openresty-%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF.html

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到