OpenResty - Redis

场景:

请求到达openresty,openresty从redis获取白名单,然后判断请求地址是否再白名单,在白名单转到192.168.189.132服务否则转到192.168.189.131服务

 

1、在openresty根目录创建目录gray(作为工作空间),在gray目录创建conf(存放nginx配置文件nginx.conf)、logs(存放日志文件)、lua(存放lua脚本)

2、配置nginx:

user root;
worker_processes 1;
error_log logs/error.log;

events {
    worker_connections 1024;
}

http {  #添加;;标识默认路径下的lualib
  lua_package_path "$prefix/lualib/?.lua;;";
  lua_package_cpath "$prefix/lualib/?.so;;";

  upstream prod1 {
    server 192.168.189.131:8080;
  }

  upstream prod2 {
    server 192.168.189.132:8080;
  }

  server {
    listen 80;
    server_name localhost;
    location / {      #为每个请求执行gray.lua脚本
      content_by_lua_file lua/gray.lua;
    }
    location @prod1 {
      proxy_pass http://prod1;
    }
    location @prod2 {
      proxy_pass http://prod2;
    }
    
  }

}

3、配置gray.lua

local redis=require "resty.redis";

local red=redis:new();

red:set_timeout(1000);
--redis连接
local ok,err=red:connect("192.168.189.130", 6379);

if not ok then
  ngx.say("failed to connect redis ",err);
  return;
end
--获取请求ip
local local_ip = ngx.req.get_headers()["X-Real-IP"];
if local_ip == nil then
   local_ip = ngx.req.get_headers()["x_forwarded_for"];
end
if local_ip == nil then
   local_ip = ngx.var.remote_addr;
end


local_ip=ngx.var.remote_addr;
--redis中获取白名单
local ip_lists=red:get("gray");
--判断是否在白名单然后转到对应服务
if string.find(ip_lists,local_ip) == nil then
  ngx.exec("@prod1");
else
  ngx.exec("@prod2");
end

local ok,err=red:close();

redis配置注释掉bind 127.0.0.1、设置protected-mode 为no;否则通过lua连接redis出错。redis 设置 gray 键。

4、启动openresty

在openresty/nginx/sbin执行:./nginx -p /root/data/program/openresty/gray  (-p表示指定空间)

 

转自:https://www.cnblogs.com/ph7seven/p/9941189.html

 

posted on 2022-03-04 17:41  TrustNature  阅读(657)  评论(0编辑  收藏  举报