[Mac/Python] 測試連線到已啟用 TLS 的 RabbitMQ
今天需要測試一下 RabbitMQ 在打開 TLS 功能後,
能不能順利連線,簡單記錄一下吧~
1. 使用 Python
跟 ChatGPT 來回了幾次,寫出了一個可用的測試程式如下:
import ssl import pika # RabbitMQ server information rabbitmq_host = 'rabbitmq.my-rabbitmq.svc.cluster.local' rabbitmq_port = 5671 rabbitmq_username = 'root' rabbitmq_password = 'password' # Path to your certificate files ssl_options = { 'ca_certs': 'rabbit_ca.pem', 'cert_reqs': ssl.CERT_REQUIRED } ssl_context = ssl.create_default_context(cafile=ssl_options['ca_certs']) ssl_context.load_cert_chain('rabbit_client_crt.pem', 'rabbit_client_key.pem') ssl_options = pika.SSLOptions(context=ssl_context, server_hostname=rabbitmq_host) # RabbitMQ connection parameters connection_params = pika.ConnectionParameters( host=rabbitmq_host, port=rabbitmq_port, virtual_host='/', credentials=pika.PlainCredentials(username=rabbitmq_username, password=rabbitmq_password), ssl_options=ssl_options ) # Establish a connection to RabbitMQ connection = pika.BlockingConnection(connection_params) # Create a channel channel = connection.channel() # Declare a queue channel.queue_declare(queue='example_queue') # Publish a message channel.basic_publish(exchange='', routing_key='example_queue', body='Hello, RabbitMQ with TLS!') print(" [x] Sent 'Hello, RabbitMQ with TLS!'") # Close the connection connection.close()
2. 使用 rabbitmq-c CLI
在 Mac 上使用 Homebrew 安裝 rabbitmq-c:
brew install rabbitmq-c
裝好之後,可以在 /usr/local/Cellar/rabbitmq-c/<version>/bin 目錄下,
找到相關的 CLI,像 amqp-get 和 amqp-publish:
$ ll /usr/local/Cellar/rabbitmq-c/0.13.0/bin -r-xr-xr-x 1 testuser admin 54584 Dec 20 15:16 amqp-consume* -r-xr-xr-x 1 testuser admin 53232 Dec 20 15:16 amqp-declare-queue* -r-xr-xr-x 1 testuser admin 53200 Dec 20 15:16 amqp-delete-queue* -r-xr-xr-x 1 testuser admin 53088 Dec 20 15:16 amqp-get* -r-xr-xr-x 1 testuser admin 53632 Dec 20 15:16 amqp-publish*
amqp-get 的使用說明如下:
$ /usr/local/Cellar/rabbitmq-c/0.13.0/bin/amqp-get --help Usage: amqp-get [OPTIONS]... -q, --queue=queue the queue to consume from Connection options -u, --url=amqp://... the AMQP URL to connect to -s, --server=hostname the AMQP server to connect to --port=port the port to connect on --vhost=vhost the vhost to use when connecting --username=username the username to login with --password=password the password to login with --heartbeat=heartbeat heartbeat interval, set to 0 to disable --ssl connect over SSL/TLS --cacert=cacert.pem path to the CA certificate file --key=key.pem path to the client private key file --cert=cert.pem path to the client certificate file
試了幾次,終於試出以下方法可以連上有 TLS 的 RabbitMQ:
/usr/local/Cellar/rabbitmq-c/0.13.0/bin/amqp-get \ --url=amqps://root:password@rabbitmq.my-rabbitmq.svc.cluster.local:5671 \ -q test-queue \ --cacert rabbit_ca.pem \ --cert rabbit_client_crt.pem \ --key rabbit_client_key.pem
可以在 RabbitMQ UI 上,在 queue 裡面加一個 message,
用上面的方式就可以取到 message,也代表連線成功囉~
(本頁面已被瀏覽過 83 次)