rabbitmq的简单使用


package com.example.rabbitmqjava.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
* 生产者
*/
public class Producer {
public static void main(String[] args) {
//所有的中间件技术都是基于tcp、ip协议的基础之上后见新型规范,rabbitmq基于amqp
//1.创建连接工程
ConnectionFactory connect = new ConnectionFactory();
connect.setHost("192.168.2.102");
connect.setPort(5672);
connect.setUsername("admin");
connect.setPassword("admin");
connect.setVirtualHost("/");
//2.创建连接connection
Channel channel=null;
Connection con=null;
try {
con = connect.newConnection("消费者");
//3.通过连接获取连接通道
channel = con.createChannel();
//4.通过创建交换机,声明队列,绑定关系,路由key,发送消息,和接收消息
String queueName="queue1";

//6.接收队列中的消息
channel.basicConsume(queueName, true, new DeliverCallback() {
@Override
public void handle(String s, Delivery message) throws IOException {
System.out.println("收到的消息是" + new String(message.getBody(), "UTF-8"));
}
}, new CancelCallback() {
@Override
public void handle(String s) throws IOException {
System.out.println("接收失败了");
}
});
System.in.read();

} catch (Exception e) {

e.printStackTrace();
}finally {
//7. 关闭通道
if(channel!=null&&channel.isOpen()){
try{
channel.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
//8.关闭连接
if(con!=null&&con.isOpen()){
try{
con.close();
}catch (Exception ex){
ex.printStackTrace();
}
}


}

MQ