我正在尝试使用RabbitMQ的小应用程序,其中我的发送器是用Spring AMQP xml配置编写的,接收器是用python用PIKA编写的。 如果我的方法是正确的,请告诉我。
这是我的发件人文件 -
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAMQPRabbitSender {
private final static String SENDER_XML = "springamqp-rabbit-sender-context.xml";
public static void main(String[] args) throws Exception {
AmqpTemplate amqpTemplate = (AmqpTemplate)(new ClassPathXmlApplicationContext(SENDER_XML)).getBean("amqpTemplate");
int messagCount = 0;
while (messagCount < 10){
amqpTemplate.convertAndSend("tp.routingkey.1", "Message # " + messagCount++);
}
System.out.println( messagCount + " message(s) sent successfully.");
}
}
这是我的springamqp-rabbit-sender-context.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
<rabbit:connection-factory id="connectionFactory"
host="localhost" username="guest" password="guest"/>
<rabbit:admin connection-factory="connectionFactory"/>
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
exchange="tpExchange"/>
</beans>
现在这是我的python接收器 -
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParamet(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='tpExchange',
exchange_type='topic')
channel.queue_declare(queue = "tpQueue")
key = "tp.routingkey.1"
channel.queue_bind(exchange='tpExchange',
queue="tpQueue",
routing_key="tp.routingkey.1")
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (key, body))
channel.basic_consume(callback,
queue="tpQueue",
no_ack=True)
channel.start_consuming()
这是对的吗?我错过了什么吗?请建议。
提前致谢。
答案 0 :(得分:1)
但是,在几个例子中,我看到在发送方也配置了队列交换绑定。所以我想澄清一下。
不,你绝对不需要在发送方这样做。只需知道exchange
和routing key
即可。队列及其绑定甚至不是接收器的问题,但我们通常在那里绑定。
当然,正常的方法是经纪人配置。