rabbitmq消息中間件,按我的理解就是解決同時大量請求造成服務器壓力大掛掉,可以作為中間商存儲請求,再慢慢讓服務器返回。
首先是配置環境,默認已經安裝了本地rabbitmq,可以通過localhost:15672 進入管理頁面
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
導入依賴后,在RabbitMq Manager頁面按照下面步驟設置好登錄用戶,host和權限,



然后你就可以在ide中寫測試代碼了。
首先寫個連接工具類:
package com.yaimer.d.rabbit; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.AMQConnection; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @program: SpringSecurityTestProject * @description: * @author: yaimer * @create: 2020-09-07 23:56 **/ public class test { /** * 獲取MQ的連接 */ public static Connection getConnection() throws IOException, TimeoutException { //定義一個連接工廠 ConnectionFactory factory = new ConnectionFactory(); //設置服務地址 factory.setHost("127.0.0.1"); //設置端口 AMQ 5672 factory.setPort(5672); //vhost factory.setVirtualHost("/vhost"); //用戶名 factory.setUsername("zard"); //密碼 factory.setPassword("admin"); return factory.newConnection(); } }
簡單隊列就是一個生產者Producer和一個消費者Consumer
寫一個生產者:
package com.yaimer.d.rabbit; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @program: SpringSecurityTestProject * @description: * @author: yaimer * @create: 2020-09-08 00:19 **/ public class produce { private static final String QUEUE_NAME="testQueue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = test.getConnection(); //從連接中獲取一個通道 Channel channel = connection.createChannel(); //創建隊列聲明 channel.queueDeclare(QUEUE_NAME,false,false,false,null); String str ="hello_zard_test______"; channel.basicPublish("",QUEUE_NAME,null,str.getBytes()); System.out.println("她走過——————"+str); channel.close(); connection.close(); } }
,接着一個消費者:
package com.yaimer.d.rabbit; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @program: SpringSecurityTestProject * @description: * @author: yaimer * @create: 2020-09-08 00:29 **/ public class consumer { private static final String QUEUE_NAME="testQueue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = test.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, AMQP.BasicProperties properties, byte[] body) throws IOException { String str = new String(body,"utf-8"); System.out.println("consumer____"+str); } }; channel.basicConsume(QUEUE_NAME,true,consumer); } }
寫完就可以運行了,可以先運行消費者,再運行生產者,運行幾次,消費者接受幾次。
也可不運行消費者,運行幾次生產者,最后運行消費者,會一次性接收。
這是簡單隊列的實現。

