【发布时间】:2018-04-18 16:53:31
【问题描述】:
我正在尝试创建一个使用 RabbitMQ 的小型应用程序,其中我的发送方是用 Spring AMQP xml 配置编写的,而接收方是使用 PIKA 用 python 编写的。 请让我知道我的方法是否正确。
这是我的发件人文件-
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()
这是正确的吗?我错过了什么吗?请提出建议。
提前致谢。
【问题讨论】:
-
正确。就这样?你面临一些问题吗?发送消息时是否有一些错误?总的来说:是什么让你来找我们帮忙?
-
我只是想知道在xml文件中是否需要配置队列交换绑定?我有一个疑问,所以想澄清一下。正如我所研究的那样,发送方的 xml 中的上述配置就足够了。但是由于在几个示例中我也看到了在发送方配置的队列交换绑定......所以我想澄清一下。
标签: xml rabbitmq spring-amqp pika