RabbitMQ 是否能够将消息传递给特定客户端?或者我必须在客户端执行这些检查吗?
我的软件在我的网络周围的一堆客户端上运行。我一直在使用 RabbitMQ 作为在每个客户端之间传递消息的解决方案。
我的测试代码是这样的:
#!/usr/bin/python2
import pika
import time
connection = pika.AsyncoreConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
def callback(ch, method, properties, body):
# send messages back on certain events
if body == '5':
channel.basic_publish(exchange='',
routing_key='test',
body='works')
print body
channel.queue_declare(queue='test')
channel.basic_consume(callback, queue='test', no_ack=True)
for i in range(0, 8):
channel.basic_publish(exchange='',
routing_key='test',
body='{}'.format(i))
time.sleep(0.5)
channel.close()
将其想象为一种“聊天程序”。每个客户端都需要不断监听消息。有时,客户端需要将消息发送回服务器。
这段代码有效,但我遇到了一个问题。当下面的代码发送消息 works
时,它会再次从 RabbitMQ 队列中检索该消息。有没有办法告诉我的客户端(生产者和消费者)没有收到刚刚发送的消息?
我看不到 RabbitMQ 中内置的此功能,所以我想我应该以以下形式发送消息:
body='{"client_id" : 1, "message" : "this is the message"}'
然后我可以解析该字符串并检查 client_id
。然后客户端可以忽略所有不是发给它的消息。
有更好的办法吗?我应该寻找 RabbitMQ 的替代品吗?
I have my software running on a bunch of clients around my network. I've been playing around with RabbitMQ as a solution for passing messages between each client.
My test code is this:
#!/usr/bin/python2
import pika
import time
connection = pika.AsyncoreConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
def callback(ch, method, properties, body):
# send messages back on certain events
if body == '5':
channel.basic_publish(exchange='',
routing_key='test',
body='works')
print body
channel.queue_declare(queue='test')
channel.basic_consume(callback, queue='test', no_ack=True)
for i in range(0, 8):
channel.basic_publish(exchange='',
routing_key='test',
body='{}'.format(i))
time.sleep(0.5)
channel.close()
Picture this as kind of a 'chat program'. Each client will need to constantly listen for messages. At times, the client will need to send messages back to the server.
This code works, but I've ran into an issue. When the code below sends out the message works
, it then retreives that again from the RabbitMQ queue. Is there a way to tell have my client, a producer and a consumer, not receive the message it just sent?
I can't see this functionality built into RabbitMQ so I figured I'd send messages in the form of:
body='{"client_id" : 1, "message" : "this is the message"}'
Then I can parse that string and check the client_id
. The client can then ignore all messagess not destined to it.
Is there a better way? Should I look for an alternative to RabbitMQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
RabbitMQ 中可以有任意多个队列。为什么不为发送到服务器的消息建立一个队列,并为每个客户端建立一个队列?
You can have as many queue in RabbitMQ. Why not have a queue for messages to the server as well as a queue for each client?