https://openresty.org/en/下载地址Howtoinstallanddeploy不是本节内容。在实际项目中,遇到重构或者新版本发布时,如何高效地在新旧系统之间切换,目前的答案是Gateway。有很多开源网关KongApisix,这里教大家自己实现一个api网关。Openresty基于Nginx开发,使用Lua使程序更加灵活。Lua基于C语言开发,脚本语言原生协程,性能强。看一眼lua的语法,我们就开始上手了。网关实现的思路其实很简单。请求来到openresty然后通过lua脚本解析相关route/queryParmes/Body内容,然后做出想要的结果,比如我要/abc返回{"msg":"helloworld"}或者GET返回1,POST返回2,因为luaJit比较耗时,代码会使用redis实现访问指定路由然后请求新item,如果没有则访问旧itemlocalre_uri=ngx.var.request_uri//获取请求urilocalre_method=ngx.var.request_method//获取请求的方式ifre_method=="GET"then//这里判断是不是get请求,判断是否有传递的参数,去掉后面的参数,因为它只需要保存urilocalcat_len=string.find(re_uri,"?")--ngx.say(type(cat_len))iftype(cat_len)=="number"andcat_len>0thenre_uri=string.sub(re_uri,0,cat_len-1)endend//开始连接redislocalfunctionclose_redis(redis_instance)ifnotredis_instancethenreturnendlocalok,err=redis_instance:关闭();如果不行,那么ngx.say("closerediserror:",err);endend--连接redislocalredis=require("resty.redis");--创建redis对象localredis_instance=redis:new();redis_instance:set_timeout(1000)localok,err=redis_instance:connect('127.0.0.1',6379)ifnotokthenngx.say("connectrediserror:",err)returnclose_redis(redis_instance);end--Redisauthenticationlocalauth,err=redis_instance:auth("");//如果没有密码,可以把这段代码注释掉ifnotauththenngx.say("failedtoauthenticate:",err)end--连接成功localresp,err=redis_instance:set("lua","helloworld")//连接成功写入luahelloworldifnotrespthenngx.say("setmsgerror:",err)returnclose_redis(redis_instance)end--获取是否是API存在于本地resp,err=redis_instance:get("gateway:"..re_uri)ifnotrespthenngx.say("getmsgerror:",err)returnclose_redis(redis_instance)end//如果不存在,然后访问旧项目如果resp==nil然后ngx.exec("@old");endifresp=="1"thenngx.exec("@new");//如果存在则访问新项elsengx.exec("@old");endclose_redis(redis_instance)//在结束闭包之后Redis连接配置openrestylua脚本写完后需要在openresty配置中添加,因为是基于nginx开发的,配置类似于nginxvimnginx.conflocation/{//访问路由时加载lua脚本add_header内容类型应用程序/json;content_by_lua_file/www/lua/gateway.lua;}location@old{//旧项目try_files$uri=404;fastcgi_passunix:/tmp/php-cgi-72.sock;fastcgi_indexindex.php;包括fastcgi.conf;包括路径信息.conf;}location@new{//新项目proxy_http_version1.1;proxy_set_header连接“保持活动状态”;proxy_set_header主机$host;proxy_set_headerX-Real-IP$remote_addr;proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;主机$remote_addr;proxy_passhttp://127.0.0.1:13001;}reload配置openrestyreloadendscurlhttp://localhost/helloOpenResty本文由博客发布平台OpenWrite发布!
