RabbitMQ學習第一記:用java串連RabbitMQ

來源:互聯網
上載者:User

標籤:catch   class   getc   生產者   nbsp   通道   err   als   輪詢   

1、什麼是RabbitMQ

  MQ(Message Queue):訊息佇列,是服務端設計的一個可以儲存大量訊息的隊列,並提供用戶端操作隊列的方法:生產隊列(向隊列中添加資料)、消費隊列(從隊列中取資料)。RabbitMQ就是基於訊息佇列的一個典型應用。RabbitMQ除了普通的生產消費功能,還有一些進階功能:公平分發 ,輪詢分發,路由模式,萬用字元模式,發布訂閱,隊列持久化。

2、java實現RabbitMQ的串連

2.1、RabbitMQ用戶端jar包

 

<dependency>    <groupId>com.rabbitmq</groupId>    <artifactId>amqp-client</artifactId>    <version>4.0.2</version></dependency>

 

2.2、java串連RabbitMQ工具類

public class ConnectionUtil{    private static Logger logger = Logger.getLogger(ConnectionUtil.class);        public static Connection getConnection()    {        try        {            Connection connection = null;            //定義一個串連工廠            ConnectionFactory factory = new ConnectionFactory();            //設定服務端地址(網域名稱地址/ip)            factory.setHost("127.0.0.1");            //設定伺服器連接埠號碼            factory.setPort(5672);            //設定虛擬機器主機(相當於資料庫中的庫)            factory.setVirtualHost("/");            //設定使用者名稱            factory.setUsername("admin");            //設定密碼            factory.setPassword("888888");            connection = factory.newConnection();            return connection;        }        catch (Exception e)        {            return null;        }    }}

2.3、簡單的生產者-消費者模式

  取自於官方網站(RabbitMQ)的生產消費模式的工作圖

P:訊息的生產者

C:訊息的消費者

紅色:隊列 

生產者將訊息發送到隊列,消費者從隊列中擷取訊息。

2.4、生產者(Send)

public class Send{    //隊列名稱    private static final String QUEUE_NAME = "test_simple_queue";        public static void main(String[] args)    {        try        {            //擷取串連            Connection connection = ConnectionUtil.getConnection();            //從串連中擷取一個通道            Channel channel = connection.createChannel();            //聲明隊列            channel.queueDeclare(QUEUE_NAME, false, false, false, null);            String message = "This is simple queue";            //發送訊息            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("utf-8"));            System.out.println("[send]:" + message);            channel.close();            connection.close();        }        catch (IOException | TimeoutException e)        {            e.printStackTrace();        }    }}

運行結果:
[send]:This is simple queue

2.5、消費者(Receive)

public class Receive{    //隊列名稱    private static final String QUEUE_NAME = "test_simple_queue";        public static void main(String[] args)    {        try        {            //擷取串連            Connection connection = ConnectionUtil.getConnection();            //從串連中擷取一個通道            Channel channel = connection.createChannel();            //聲明隊列            channel.queueDeclare(QUEUE_NAME, false, false, false, null);            //定義消費者            DefaultConsumer consumer = new DefaultConsumer(channel)            {                //當訊息到達時執行回調方法                @Override                public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,                        byte[] body) throws IOException                {                    String message = new String(body, "utf-8");                    System.out.println("[Receive]:" + message);                }            };            //監聽隊列            channel.basicConsume(QUEUE_NAME, true, consumer);        }        catch (IOException | ShutdownSignalException | ConsumerCancelledException e)        {            e.printStackTrace();        }    }}運行結果:[Receive]:This is simple queue

總結:簡單的生產者-消費者模式實現了生產者向隊列裡生產資料,消費者啟動後可以一直監聽隊列,不斷的從隊列裡取出資料。

注意:本文僅代表個人理解和看法喲!和本人所在公司和團體無任何關係!

RabbitMQ學習第一記:用java串連RabbitMQ

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.