nginx代理rabbitmq服务端口

叙述实现的业务要求:
  前提:mq和生产者都在内网服务器上;消费者在外网
  目标:通过nginx代理,实现消费者
了解rabbitmq的协议与nginx的代理协议
Nginx 通常处理的是 HTTP 请求,而 RabbitMQ 则基于 AMQP 或其他消息协议工作。需要进行协议的转换和适配。
使用stream模块原因:
nginx支持stream模块, 使用stream模块,Nginx不会解析AMQP协议,因此可以完整的转换协议。
 nginx容器启动命令:
docker run -p 9002:8009 -p 9003:8099 --name nginx -v D:\nginx\conf\nginx.conf:/etc/nginx/nginx.conf -v D:\nginx\conf\conf.d:/etc/nginx/conf.d -v D:\nginx\log:/var/log/nginx -v D:\nginx\html:/usr/share/nginx/html -d nginx:latest

 

检查当前 Nginx 是否已支持 Stream 模块
nginx -V 2>&1 | grep -o with-stream
输出:
with-stream
with-stream
with-stream

注:输出with-stream代表支持。如果不是需要对nginx进行配置。

 

nginx部署:nginx.conf
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;
 
    #gzip  on;
     server {
        listen       8009;
        server_name  localhost;

        location / {
            proxy_pass http://ip:15672;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

        }
    }
    include /etc/nginx/conf.d/*.conf;

}
 #单独stream模块
stream {

    #gzip  on;
     server {
        listen       8099;
        proxy_connect_timeout 600s;
        proxy_pass ip:5672;
    }
} 

 

消费者脚本:
# _*_ coding: utf-8 _*_

import pika

user = 'xx'  
pwd = 'xxxx' 
net_ip = 'ip'  #
# 连接到RabbitMQ服务器
credentials = pika.PlainCredentials(user, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(net_ip, 9003, '/', credentials))
channel = connection.channel()

# 声明队列;确保这个队列已经被生产者创建
queue_name = 'xxxxx'
# channel.queue_declare(queue=queue_name)

print(f' [*] Waiting for messages in {queue_name}. To exit press CTRL+C')


# 定义回调函数处理消息
def callback(ch, method, properties, body):
    print(f" [x] Received {body}")


# 开始监听队列,并在接收到消息时调用callback函数
channel.basic_consume(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

# 开始消费消息
channel.start_consuming()

 

 
posted @ 2025-04-25 15:39  乔小生1221  阅读(281)  评论(0)    收藏  举报