功能描述:
使用rabbit mq 實現發送消息和消費消息
(1)添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
(2)創建消息生產者測試類
@Test
public void testProducer() throws IOException, TimeoutException{
// 創建連接工廠
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xxx.xxx.xxx.xxx");
factory.setPort(AMQP.PROTOCOL.PORT); // 5672
factory.setUsername("xxx");
factory.setPassword("xxx");
// 新建一個長連接
Connection connection = factory.newConnection();
// 創建一個通道(一個輕量級的連接)
Channel channel = connection.createChannel();
// 聲明一個隊列
String QUEUE_NAME = "hello";
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 發送消息到隊列中
String message = "Hello RabbitMQ!1";
// 注意:exchange如果不需要寫成空字符串,routingKey和隊列名稱保持一致
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer Send a message:" + message);
// 關閉資源
channel.close();
connection.close();
}
(3)新建消息消費者
@Test
public void testBasicConsumer() throws Exception{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xxx.199.31.248");
factory.setPort(AMQP.PROTOCOL.PORT); // 5672
factory.setUsername("xxx");
factory.setPassword("xxx");
// 新建一個長連接
Connection connection = factory.newConnection();
// 創建一個通道(一個輕量級的連接)
Channel channel = connection.createChannel();
// 聲明一個隊列
String QUEUE_NAME = "hello";
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("消費者消費消息-------------");
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [lizk] 接受消息: '" + message + "'");
}
};
// 訂閱消息
channel.basicConsume(QUEUE_NAME, true, consumer);
}
(4) 測試
運行生產者 從管理端可以發現有一條消息
運行消費者發現消息已經被消費