## TCP 代理配置 upstream backend{ server 127.0.0.2:1101;# 爱写啥写啥 反正下面的代码也给你改了 balancer_by_lua_block { -- 初始化balancer local balancer = require "ngx.balancer" local host = "" local port = 0 host = ngx.ctx.proxy_host port = ngx.ctx.proxy_port -- 设置 balancer local ok, err = balancer.set_current_peer(host, port) if not ok then ngx.log(ngx.ERR, "failed to set the peer: ", err) end } }
server { preread_by_lua_block{
local redis = require("resty.redis") --创建实例 local redis_instance = redis:new() --设置超时(毫秒) redis_instance:set_timeout(3000) --建立连接,请在这里配置Redis 的 IP 地址、端口号、密码和用到的 Key local rhost = "123.45.67.89" local rport = 6739 local rpass = "abcdefg" local rkey = "proxy:pool" local ok, err = redis_instance:connect(rhost, rport) ngx.log(ngx.ERR, "1111111 ", ok, " ", err)
-- 如果没有密码,移除下面这一行 local res, err = redis_instance:auth(rpass) local res, err = redis_instance:hkeys(rkey) if not res then ngx.log(ngx.ERR,"res num error : ", err) return redis_instance:close() end math.randomseed(tostring(ngx.now()):reverse():sub(1, 6)) local proxy = res[math.random(#res)] local colon_index = string.find(proxy, ":") local proxy_ip = string.sub(proxy, 1, colon_index - 1) local proxy_port = string.sub(proxy, colon_index + 1) ngx.log(ngx.ERR,"redis data = ", proxy_ip, ":", proxy_port); ngx.ctx.proxy_host = proxy_ip ngx.ctx.proxy_port = proxy_port redis_instance:close() } # 下面是本机的端口,也就是爬虫固定写死的端口 listen 0.0.0.0:9976; #监听本机地址和端口,当使用keeplived的情况下使用keeplived VIP proxy_connect_timeout 3s; proxy_timeout 10s; proxy_pass backend; #这里填写对端的地址 } }