RabbitMQ点对点
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.6.5</version> </dependency>
public class RabbitMQUtils { public static Connection newConnection() throws Exception{ //定义连接工厂 ConnectionFactory factory = new ConnectionFactory(); //设置RabbitMQ服务 factory.setHost("127.0.0.1"); // 3. 设置协议端口号 factory.setPort(5672); // 4. 设置用户名 factory.setUsername("guest"); // 5. 设置密码 factory.setPassword("guest"); // 6. 设置vhost虚拟主机,类似于sql的库 factory.setVirtualHost("/test"); Connection connection = factory.newConnection(); return connection; } }
public class Producer { private static final String QUEUE_NAME="test_queue"; public static void main(String[] args) throws Exception { // 1. 获得连接 Connection connection = RabbitMQUtils.newConnection(); // 2. 创建通道 Channel channel = connection.createChannel(); // 3. 创建队列声明 channel.queueDeclare(QUEUE_NAME,false,false,false,null); // 4. 发送消息 String msg="生产者发送的信息"; channel.basicPublish("",QUEUE_NAME,null,msg.getBytes()); // 5. 关闭连接 connection.close(); } }
public class Customer {
//队列名字
private static final String QUEUE_NAME = "test_queue";
public static void main(String[] args) throws Exception {
// 1. 获取连接
Connection connection = RabbitMQUtils.newConnection();
// 2. 获取通道
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//3.获取消息
DefaultConsumer defaultConsumer=new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg=new String(body,"utf-8");
System.out.println("接收到的消息:"+msg);
}
};
//4.监听队列
channel.basicConsume(QUEUE_NAME,true,defaultConsumer);
}
}