二、创建项目:
1、File -> new -> spring starter project
2、将RabbitMQ加入项目依赖中:
3、配置rabbitmq相关的属性,在application.properties中,加入以下配置:
spring.application.name=spring-cloud-mq
spring.rabbitmq.host=192.168.1.3
spring.rabbitmq.port=5672
spring.rabbitmq.username=unam
spring.rabbitmq.password=pwd
二、编写生产者、消息者和测试类
1、创建配置QueueConfig类,创建消息队列Bean:
package com.fifi.mqdemo;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QueueConfig {
@Bean
public Queue createQueue() {
return new Queue("test-mq");
}
}
2、创建消息生产类(provider):
package com.fifi.mqdemo;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbiTemplate;
public void send(String msg) {
this.rabbiTemplate.convertAndSend("test-mq", msg);
}
}
3、创建消息消费类(cusumer)
package com.fifi.mqdemo;
import java.util.Date;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@RabbitListener(queues= {"test-mq"})
public void processMsg(String msg) {
System.out.println("receiver time : "+new Date()+" , msg : "+msg);
}
}
4、创建测试类:
package com.fifi.mqdemo;
import java.util.Date;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMqTestApplicationTests {
@Autowired
private Sender sender;
@Test
public void contextLoads() {
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.sender.send("hello time : "+new Date());
}
}
}
输出及结果:
receiver time : Sat May 04 15:46:39 CST 2019 , msg : hello time : Fri May 03 14:52:06 CST 2019
receiver time : Sat May 04 15:46:40 CST 2019 , msg : hello time : Sat May 04 15:46:40 CST 2019
receiver time : Sat May 04 15:46:41 CST 2019 , msg : hello time : Sat May 04 15:46:41 CST 2019
receiver time : Sat May 04 15:46:42 CST 2019 , msg : hello time : Sat May 04 15:46:42 CST 2019
receiver time : Sat May 04 15:46:43 CST 2019 , msg : hello time : Sat May 04 15:46:43 CST 2019
receiver time : Sat May 04 15:46:44 CST 2019 , msg : hello time : Sat May 04 15:46:44 CST 2019
receiver time : Sat May 04 15:46:45 CST 2019 , msg : hello time : Sat May 04 15:46:45 CST 2019
receiver time : Sat May 04 15:46:46 CST 2019 , msg : hello time : Sat May 04 15:46:46 CST 2019
receiver time : Sat May 04 15:46:47 CST 2019 , msg : hello time : Sat May 04 15:46:47 CST 2019
在浏览器中输入:http://localhost:15672查看消息队列的情况: