SpringBoot整合RabbitMQ之基礎實例

在pom文件中導入依賴

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

在application.properties中添加如下配置信息

spring.rabbitmq.host=192.168.43.127(這裏配置自己的虛機地址)
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin

創建隊列

package com.etoak.crazy.config.rabbitmq;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitMQConfig {

		@Bean
		public Queue queue() {
			//創建隊列名爲TEST的隊列
			return new Queue("TEST");
		}
}

創建生產者

package com.etoak.crazy.study.rabbitmq.producer;

import java.util.Date;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProducerDemo {
	@Autowired
	private AmqpTemplate rabbitTemplate;
	
	public void send() {
		String message = "hello!Now the time is " + new Date();
		System.out.println("發送的信息爲 : " + message);
		//發送message給名爲TEST的隊列
		this.rabbitTemplate.convertAndSend("TEST", message);
	}
}


創建消費者

package com.etoak.crazy.study.rabbitmq.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
//監聽名爲TEST的隊列
@RabbitListener(queues = "TEST")
public class ConsumerDemo {
    //@RabbitListener 標註在類上面表示當有收到消息的時候,就交給 @RabbitHandler 的方法處理,具體使用哪個方法處理
    @RabbitHandler
    public void process(String message) {
        System.out.println("接收消息爲  : " + message);
    }
}

測試類測試

package com.etoak.crazy.test.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.etoak.crazy.study.rabbitmq.producer.ProducerDemo;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqDemoTest {
	
	@Autowired
	private ProducerDemo producerdemo;

	@Test
	public void hello() throws Exception {
		producerdemo.send();
	}

}

在虛擬機中service rabbitmq-server start輸入開啓RabbitMQ服務
啓動後輸入service rabbitmq-server status查看RabbitMQ服務狀態
在這裏插入圖片描述

測試結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章