java 往rabbitmq交换机testchange routingKeytest 队列testqueue 中推送数据
以下是使用Java往RabbitMQ的交换机"testchange",使用routingKey".test.",向队列"testqueue"中推送数据的示例代码:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMQProducer {
private static final String EXCHANGE_NAME = "testchange";
private static final String ROUTING_KEY = "*.test.*";
private static final String QUEUE_NAME = "testqueue";
public static void main(String[] args) {
try {
// 创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
// 创建连接
Connection connection = factory.newConnection();
// 创建信道
Channel channel = connection.createChannel();
// 声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, "direct");
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 绑定队列到交换机
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
// 发送消息
String message = "Hello RabbitMQ!";
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes("UTF-8"));
System.out.println("Sent message: " + message);
// 关闭信道和连接
channel.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请确保已经安装了RabbitMQ,并且已经在本地运行
原文地址: https://www.cveoy.top/t/topic/hZU3 著作权归作者所有。请勿转载和采集!