openresty正向代理搭建

image.png

1、需求

图里是需求,爬虫写死,更换代理不由它去做处理。自动会更换。

2 方案选型

  • 1、之前有个Python版本的正向代理。忘了叫啥了。因为项目建立和写文章不是同时期,所以找不到了。内存占用什么的特别大,速度也不是很快。所以选择了方案2
  • 2、openresty:通过nginx做正向代理。lua脚本更换代理,代理由redis读出来。

3、实践

安装openresty
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
yum install openresty

或者下面这种装法(任选其一)

wget https://openresty.org/package/centos/openresty.repo
sudo mv openresty.repo /etc/yum.repos.d/
sudo yum check-update
sudo yum install -y openresty

mac安装:

brew install openresty/brew/openresty
编写配置文件

新建nginx_redis.conf

redis单机版
worker_processes  16;        #nginx worker 数量
error_log /data/logs/openresty/error.log;   #指定错误日志文件路径
events {
    worker_connections 1024;
}




stream {
    ## TCP 代理日志格式定义
    log_format tcp_proxy '$remote_addr [$time_local] '
                         '$protocol $status $bytes_sent $bytes_received '
                         '$session_time "$upstream_addr" '
                         '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
    ## TCP 代理日志配置
    access_log /data/logs/openresty/tcp-access.log tcp_proxy;
    open_log_file_cache off;
 
    ## TCP 代理配置
    upstream backend{  
        server 127.0.0.2:1101;# 爱写啥写啥  反正下面的代码也给你改了
        balancer_by_lua_block {   
            -- 初始化balancer
            local balancer = require "ngx.balancer"
            local host = "127.0.0.3"
            local port = 3888   # 这是代理机的代理端口
            host = ngx.ctx.proxy_host
            -- 设置 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)
            --建立连接
            local rhost = "10.8.181.1"
            local rport = 6379
            local ok, err = redis_instance:connect(rhost, rport)
            local oke, err = redis_instance:select(15)
            if not oke then
                ngx.log(ngx.ERR,"connect to redis error : ", err)
                return redis_instance:close()
            end
            local res, err = redis_instance:rpoplpush("vps","vps")
            -- ngx.log(ngx.ERR,"res num error : ", res)
            if not res then
                ngx.log(ngx.ERR,"res num error : ", err)
                return redis_instance:close()
            end
            -- ngx.log(ngx.ERR,"redis data = ",res..":3888");
            ngx.ctx.proxy_host = res
            redis_instance:close()   
        }
        #  下面是本机的端口,也就是爬虫固定写死的端口
       listen 0.0.0.0:3889; #监听本机地址和端口,当使用keeplived的情况下使用keeplived VIP
       proxy_connect_timeout 3s;
       proxy_timeout 10s;
       #set_by_lua_file $backend set.lua;
       #proxy_pass $backend; #这里填写对端的地址
       proxy_pass backend; #这里填写对端的地址
    }

}

redis集群版
worker_processes  16;        #nginx worker 数量
error_log /data/logs/openresty/error-pa-redis.log;   #指定错误日志文件路径
events {
    worker_connections 1024;
}

stream {
    ## TCP 代理日志格式定义
    log_format tcp_proxy '$remote_addr [$time_local] '
                         '$protocol $status $bytes_sent $bytes_received '
                         '$session_time "$upstream_addr" '
                         '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
    ## TCP 代理日志配置
    access_log /data/logs/openresty/tcp-access-pa-redis.log tcp_proxy;
    open_log_file_cache off;
 
    ## TCP 代理配置
    upstream backend{  
        server 127.0.0.2:11201;
        balancer_by_lua_block {   
            -- 初始化balancer
            local balancer = require "ngx.balancer"
            local host = "127.0.0.3"
            local port = 3888
            host = ngx.ctx.proxy_host
            -- 设置 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 
        }   
    } 

    lua_shared_dict redis_cluster_slot_locks 100k;

    server {
        

        preread_by_lua_block{
            local config = {
                name = "mengmugai",             --rediscluster name
                serv_list = {                  --redis cluster node list(host and port),
                    { ip = "10.8.181.1", port = 16379 },
                    { ip = "10.8.181.2", port = 16379 },
                    { ip = "10.8.181.3", port = 16379 },
                    { ip = "10.8.181.4", port = 16379 }
                },
                keepalive_timeout = 60000,              --redis connection pool idle timeout
                keepalive_cons = 1000,                  --redis connection pool size
                connect_timeout = 1000,              --timeout while connecting
                read_timeout = 1000,           --timeout while reading
                send_timeout = 1000,           --timeout while sending
                max_redirection = 5,           --maximum retry attempts for redirection,
                max_connection_attempts = 1,      --maximum retry attempts for connection
                auth = "renzhengmima"         --set password while setting auth
            }

            local redis_cluster = require "rediscluster"
            local red_c = redis_cluster:new(config)

            local res, err = red_c:rpoplpush("vps","vps")
            if err then
                ngx.log(ngx.ERR, "pa redis err: ", err)
            else
                ngx.log(ngx.ERR,"redis data = ",res..":3888");
            end 
            ngx.ctx.proxy_host = res
            red_c:close()   
        }

       listen 0.0.0.0:3889; #监听本机地址和端口,当使用keeplived的情况下使用keeplived VIP
       proxy_connect_timeout 3s;
       proxy_timeout 10s;
       #set_by_lua_file $backend set.lua;
       #proxy_pass $backend; #这里填写对端的地址
       proxy_pass backend; #这里填写对端的地址
    }

}

运行

如果是单机版的话

直接/usr/local/openresty/nginx/sbin/nginx -c /data/openresty-proxy/conf/nginx_redis.conf
就行了。具体文件路径 还有代码里的日志路径自己去抉择

如果是集群版的话

连接redis集群需要用到 lua-resty-redis-cluster模块

github地址https://github.com/cuiweixie/lua-resty-redis-cluster

下载之后,需要用2个文件rediscluster.lua和redis_slot.c 都在lib里面

复制包中的 redis_slot.c和rediscluster.lu 到openresty安装目录的lualib下

.c文件无法在Nginx配置文件中引入,需要编译成.so文件,编译命令

# 安装gcc、c++编译器以及内核文件
yum -y install gcc gcc-c++ kernel-devel
# centos自带lua需要执行此命令再编译,自己安装过lua不需要
yum install lua-devel

#编译命令
gcc redis_slot.c -fPIC -shared -o libredis_slot.so

#查看结果
img

直接/usr/local/openresty/nginx/sbin/nginx -c /data/openresty-proxy/conf/nginx_redis.conf就行了

最后

爬虫写好代理试一下ip:3889试试就行了。文章可能因为脱敏有点改乱了

参考:
https://blog.csdn.net/qq_22494169/article/details/109357667
https://blog.csdn.net/zyt425916200/article/details/78113547
https://github.com/openresty/lua-resty-redis#connect

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容