- 结构
- 1. 创建maven工程,并导入依赖
- 2. 创建生产者对象
- 3. 将Rabbitmq部署到ubuntu虚拟机上,并开启服务
- 4. 运行producer程序,发送数据到mq上
- 5. 创建消费者程序
- 6. 运行消费者程序,消费消息
rabbitmq作为一个消息中间件,可以从生产者手中获得和存储消息,并被消费者带走。
1. 创建maven工程,并导入依赖2. 创建生产者对象com.rabbitmq amqp-client 5.8.0 commons-io commons-io 2.6 ch.qos.logback logback-classic 1.3.0-alpha5 org.slf4j slf4j-api 2.0.0-alpha1
public class producer {
public final static String QUEUE_NAME="hello";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory=new ConnectionFactory();
factory.setHost("****.****.****.****");
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection=factory.newConnection();
Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message="hello world";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("发送成功");
}
}
3. 将Rabbitmq部署到ubuntu虚拟机上,并开启服务
可以在web界面进行管理
public class consumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory=new ConnectionFactory();
factory.setHost("192.168.***.***");
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection=factory.newConnection();
Channel channel=connection.createChannel();
//成功以后的回调函数
DeliverCallback deliverCallback=(consumerTag,message)->{
System.out.println(new String(message.getBody()));
};
//失败或中断以后的回调函数
CancelCallback cancelCallback=(message)->{
System.out.println(message);
};
//1.获取消息的队列名称
//2.是否自动应答
//3.成功的回调函数
//4.失败的回调函数
channel.basicConsume(producer.QUEUE_NAME,true,deliverCallback,cancelCallback )
}
}
)
}
6. 运行消费者程序,消费消息



