[英]How to create a spring boot rabbitmq consumer for a python sender?
[英]How do I write a spring boot rabbitmq sender for a python receiver?
我想編寫一個應用程序,其中我需要一個生產者使用spring boot rabbitmq發送消息,而接收者是用python編寫的。 接收器部分很容易-
receive.py
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
如何為此編寫一個Spring Boot Rabbitmq發送者代碼? 在那聲明什么必要的東西? 請幫忙。
首先,Spring Boot是Java應用程序。
因此,您需要使自己熟悉該語言。
選擇是正確的:您確實可以從Java發送到RabbitMQ並從任何其他客戶端的隊列中接收。
Spring Boot為您提供RabbitTemplate
bean。 因此,如果故事即將發送,您只需要注入這樣的bean並使用其API發送即可:
@Autowired
RabbitTemplate rabbitTemplate;
...
this.rabbitTemplate.convertAndSend("topic_logs", binding_key, data);
有關更多信息,請參見參考手冊 。
通過spring集成,首先需要創建一個配置類:
@Configuration
public class RabbitConfig {
@Autowired
private ConnectionFactory connectionFactory;
@Bean
DirectExchange dropfileExchange() {
return new DirectExchange("exchange_name", true, false);
}
@Bean
public Queue dropfileQueue() {
return new Queue("queue_name", true);
}
@Bean
Binding dropfileExchangeBinding(DirectExchange dropfileExchange, Queue dropfileQueue) {
return BindingBuilder.bind(dropfileQueue).to(dropfileExchange).with("key_name");
}
@Bean
public RabbitTemplate dropfileExchangeTemplate() {
RabbitTemplate rt = new RabbitTemplate(connectionFactory);
rt.setExchange("exchange_name");
rt.setRoutingKey("key_name");
rt.setConnectionFactory(connectionFactory);
return rt;
}
@Bean
public RabbitMessagingTemplate rabbitMessagingTemplate() {
return new RabbitMessagingTemplate(dropfileExchangeTemplate());
}
}
然后創建一個網關服務:
@MessagingGateway
public interface DropfileMessageGateway {
@Gateway(requestChannel = "channel_name")
void generate(String payload);
}
然后使用Java DSL指定生產者流程,如下所示:
@Bean
public IntegrationFlow toOutboundQueueFlow() {
return IntegrationFlows.from("channel_name")
.transform(Transformers.toJson())
.handle(Amqp.outboundAdapter(rabbitConfig.dropfileExchangeTemplate())).get();
}
這將從通道中讀取一條消息,將其轉換為JSON,然后使用出站適配器將其分發到Rabbit交換。
請注意,消息通過消息傳遞網關到達通道,因此兩者中的通道名稱應相同。
不要忘記包括適當的依賴項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.