RabbitMQ入门(二)-helloworld
生活随笔
收集整理的這篇文章主要介紹了
RabbitMQ入门(二)-helloworld
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先引入pom依賴:
<dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>5.1.2</version></dependency>啟動項目之前把RabbitMQ啟動
首先是OneProducer生產者:
package com.baidu.RabbitMQ.mq01;import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory;public class OneProducer {private static final String Queue_Name="rabbit:mq01:queue";public static void main(String[] args) {try {ConnectionFactory factory = new ConnectionFactory();factory.setHost("127.0.0.1");//TODO:點 ConnectionFactory 進去看看 會發現其中的userName跟password默認就是使用我下面兩個設置,所以可以不需要設置//factory.setUsername("guest");//factory.setPassword("guest"); Connection connection = factory.newConnection();//TODO:channel貫穿通信的始終,連接了 "消息發送端-隊列-消息接收端"Channel channel = connection.createChannel();//TODO:聲明隊列并將消息發送到隊列中. 每個方法中的各個參數均可以 點進去 看看就一目了然. -> 此為簡單的消息模型channel.queueDeclare(Queue_Name, true, false, false, null);String message = "我的第一條消息-Hello World!";channel.basicPublish("", Queue_Name, null, message.getBytes("UTF-8"));System.out.println("生產者發送消息成功---> ");channel.close();connection.close();} catch (Exception e) {e.printStackTrace();}} }接下來是是OneConsumer消費者:
package com.baidu.RabbitMQ.mq01;import java.io.IOException;import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope;public class OneConsumer {private static final String Queue_Name="rabbit:mq01:queue";public static void main(String[] args) {try {ConnectionFactory factory = new ConnectionFactory();factory.setHost("127.0.0.1");Connection connection = factory.newConnection();Channel channel = connection.createChannel();channel.queueDeclare(Queue_Name, true, false, false, null);Consumer consumer = new DefaultConsumer(channel) {@Overridepublic void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)throws IOException {String message = new String(body, "UTF-8");System.out.println("消費端接受到消息---> "+message);}};//TODO:確認消費->這在SpringBoot整合將會進一步的細講channel.basicConsume(Queue_Name, true, consumer);} catch (Exception e) {e.printStackTrace();}} }?
總結
以上是生活随笔為你收集整理的RabbitMQ入门(二)-helloworld的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 贝瓦儿歌500首歌
- 下一篇: 骆驼祥子的读后感1000字左右