首页 > 数据库 >Nginx内置lua版OpenResty拦截转发请求Redis等操作

Nginx内置lua版OpenResty拦截转发请求Redis等操作

时间:2023-08-24 13:56:33浏览次数:41  
标签:set http Nginx local Redis lua proxy ngx

Nginx内置lua版OpenResty拦截转发请求Redis等操作

1 下载并安装OpenResty

http://openresty.org/cn/download.html

2 下载 lua-resty-http-0.17.1 库 以让openresty的lua支持外部http访问能力

lua-resty-http-0.17.1

1 下载 lua-resty-http-0.17.1

2 然后将文件中lua-resty-http-0.17.1\lib\resty 下面的 http.lua放到openresty-1.21.4.2-win64\lualib\resty文件夹中

3 nginx.conf文件位于openresty-1.21.4.2-win64/conf文件夹中,而lua-resty-http库位于openresty-1.21.4.2-win64/lualib/resty目录中,按照以下方式设置lua_package_path指令:

http {
    lua_package_path "./../lualib/?.lua;;";
    ...
}

使用了相对路径./../lualib/?.lua来指定lua-resty-http库的路径。./..表示上一级目录,然后进入lualib目录,然后使用?.lua通配符来匹配所有的Lua文件

3 编写代码逻辑流程

在openresty-1.21.4.2-win64\luaCode文件中新建filterLogin.lua文件,并书写处理逻辑

local redis = require "resty.redis"

local function handleRequest()
    -- 连接到 Redis 服务器
    local red = redis:new()
    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.log(ngx.ERR, "failed to connect to Redis: ", err)
        return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end

    -- 选择 Redis 的 DB1
    ok, err = red:select(1)
    if not ok then
        ngx.log(ngx.ERR, "Failed to select Redis DB: ", err)
        return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end

    -- 判断请求 URL 是否包含 "ssologin" 或 "authToken"
    local request_uri = ngx.var.request_uri
    local auth_token = ngx.var.http_authtoken
    local body_data = ngx.req.get_body_data()

    -- 从 Redis 中获取指定 key 的值
    local client_ip = ngx.var.remote_addr
    local client_ip_str = "ip" .. client_ip
    local value, err = red:get(client_ip_str)

    if request_uri:find("ssologin") or request_uri:find("authToken") or request_uri:find("keepLogin") or request_uri:find("websocket")  or (body_data and body_data:find("authToken")) then
        -- 放行请求
        if request_uri:find("extensionAuthority") then
            -- 将值重新放入 Redis 并设置有效期为 30 分钟
            ok, err = red:setex(client_ip_str, 1800, value)
        end
        return
    end



    if not value then
        ngx.log(ngx.ERR, "failed to get value from Redis: ", err)
        return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end

    -- 判断值是否存在并进行相应处理
    if value == ngx.null then
        -- 转发到 www.baidu.com
        -- return ngx.redirect("http://192.9.100.73:31100/operation/keepLogin/sendLoginOut?ip=" .. client_ip_str)
        -- 构建GET请求的URL
        local http = require("resty.http")

        local httpc = http.new()
        local url = "http://192.9.100.73:31100/operation/keepLogin/sendLoginOut?ip=" .. ngx.escape_uri(client_ip_str)

        local res, err = httpc:request_uri(url, {
            method = "GET",
        })

        if not res then
            ngx.log(ngx.ERR, "failed to send GET request: ", err)
            return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
        end

        if res.status == ngx.HTTP_OK then
            local body = res.body
            -- 处理响应
            -- body 为响应体内容
            -- ...
        else
            ngx.log(ngx.ERR, "failed to send GET request: ", res.status)
            return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
        end
    else
        -- 放行请求
        -- 将值重新放入 Redis 并设置有效期为 30 分钟
        ok, err = red:setex(client_ip_str, 60, value)
        if not ok then
            ngx.log(ngx.ERR, "failed to set value in Redis: ", err)
        end
        return
    end

    -- 关闭与 Redis 的连接
    local ok, err = red:set_keepalive(10000, 100)
    if not ok then
        ngx.log(ngx.ERR, "failed to set Redis keepalive: ", err)
    end
end
handleRequest()

4 nginx.conf里面增加代码处理进行转发处理

openresty-1.21.4.2-win64/conf文件夹中nginx.conf里面进行转发处理

http {
    include       mime.types;
    default_type  application/octet-stream;
    lua_shared_dict redis_cache 100m;
    include mime.types;
    client_max_body_size 200m;
    # 引入lua-resty-http-0.17.1以让openresty的lua支持外部http访问能力
	lua_package_path "./../lualib/?.lua;;";

    sendfile        on;

    keepalive_timeout  65;

    #自定义变量
    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 8 128k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    map $http_user_agent $basePath {
      default '';
    }
    map $http_user_agent $baseUrl {
      default '';
    }

    server {
            listen 31100;

            location ^~ /operation/ {
                 proxy_set_header Host $host;
                 proxy_set_header X-Real-IP $remote_addr;
                 # 让后续可以获取代理前的请求原地址
                 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                 proxy_set_header Connection 'upgrade';
                 proxy_set_header Upgrade $http_upgrade;
                 proxy_pass http://192.9.100.73:7013/;
                 # 表示走此文件的代理逻辑
                 access_by_lua_file ./luaCode/filterLogin.lua;
            }

            location ^~ /zuul/ {
                  proxy_set_header Host $host;
                  proxy_set_header X-Real-IP $remote_addr;
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                  proxy_set_header Connection 'upgrade';
                  proxy_set_header Upgrade $http_upgrade;
                  proxy_pass http://192.9.100.73:7012/;
                  # 表示走此文件的代理逻辑
                  access_by_lua_file ./luaCode/filterLogin.lua;
            }
			
			location ^~ /service/ {
                  proxy_set_header Host $host;
                  proxy_set_header X-Real-IP $remote_addr;
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                  proxy_set_header Connection 'upgrade';
                  proxy_set_header Upgrade $http_upgrade;
                  # 表示走此文件的代理逻辑
                  proxy_pass http://192.9.100.73:7080/;
            }
        }
}

标签:set,http,Nginx,local,Redis,lua,proxy,ngx
From: https://www.cnblogs.com/ideaAI/p/17653951.html

相关文章

  • Nginx-配置WebSocket反向代理
    客户环境因开放端口有限,部署Portainer后默认端口无法访问,故使用nginx做转发,按照正常http协议配置nginx,启动后发现portainer默认的进入容器的功能无法使用,排查后发现报错如下。错误信息为websocket连接问题,需要更改nginx配置为websocket。仅修改http块中的内容即可。map$http_......
  • Redis相关
    redis-pipeline机制pipeline是Redis的一个提高吞吐量的机制,适用于多key读写场景,比如同时读取多个key的value,或者更新多个key的value。因为redis本身是基于Request/Response协议的,在正常情况下,客户端发送一个命令,等待Redis返回结果,Redis接收到命令,处理后响应。如果进行多次的读和......
  • Nginx-配置https证书
    一、说明在有些项目中需要帮客户配置https证书,如果你的服务使用Nginx作为静态服务器并且做为了端口转发,那么可以直接在Nginx中配置https证书证书有好几种格式,不同的格式对应不同server的配置,这里主要使用的是pem/key格式的证书,即公钥私钥文件对(必须要配对,否则无法使用)二......
  • Redis 内存淘汰策略&&过期策略
    学习:https://juejin.cn/post/7243987464297070647?searchId=202308240836335CB2B5EBDCD1879D6FB1https://www.bilibili.com/video/BV1bo4y1E7TK/?spm_id_from=333.337.search-card.all.click&vd_source=46d50b5d646b50dcb2a208d3946b1598......
  • Docker 安装 Nginx 教程
    Docker安装1.拉取镜像PSC:\Users\Administrator>dockerpullnginx2.创建挂载目录PSC:\Users\Administrator>mkdir-p/docker/nginx/confPSC:\Users\Administrator>mkdir-p/docker/nginx/logsPSC:\Users\Administrator>mkdir-p/docker/nginx/con......
  • 随笔(二十九)『docker 3主3从redis配置 』
    1、拉取镜像dockerpullredis:6.0.82、创建并启动容器dockerrun-d--nameredis-node-1--nethost--privileged=true-v/mydata/redis/redis-node-1/data:/dataredis:6.0.8--cluster-enabledyes--appendonlyyes--port6381dockerrun-d--nameredis-node-2--n......
  • 基于Redission的分布式锁
    分布式锁的设计共分为3步定义注解对注解进行扫描使用注解加锁核心逻辑为RLockrLock=redissonClient.getLock(key);//是否加锁成功booleanisLock=rLock.tryLock(timeOut,expireTime,timeUnit);1.定义注解LockActionpackagecom.jwds.app.compont.cache.annotat......
  • springboot之RedisTemplate的访问单机,哨兵,集群模式
    springboot2默认已经使用了lettuce-core,没有使用jedis和Redisson,springboot1使用的是jedis。我使用的springboot版本是2.6.14。(对应的lettuce版本为6.1.10.RELEASE,对应jedis版本为3.7.1)<dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactI......
  • 解密Nginx的高性能魔法:事件驱动与异步非阻塞模型
    在现代的Web服务架构中,Nginx已成为不可或缺的一部分,以其出色的性能和高效的事件驱动异步非阻塞模型而闻名。本文将深入探讨Nginx的工作原理,重点介绍其事件驱动与异步非阻塞模型,以及如何利用这些特性来实现高性能的后端服务。Nginx的事件驱动与异步非阻塞模型事件驱动模型Nginx使用......
  • 要搭建Redis集群高可用
    一.部署因为架构要求,只分配了两台服务器,要搭建Redis集群,为此针对两台服务器搭建了一套特殊的哨兵集群,特殊在不能无限切换,只能抗住1-2次宕机或网络故障,1-2次故障之后,集群切换机制便不能使用,需要人工按后文的步骤修复;1.前期准备准备AB两台服务器部署Redis集群,选择A服务器作为......