目录
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
首先配置RabbitMq
port:默认 5672
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
创建消息队列
注意:Queue 是这个 org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName QueueConfig
* @Description TODO
* @Author liguanhua
* @Date 2019-3-20 14:04
* @Version 1.0
* 创建消息队列
**/
@Configuration
public class QueueConfig {
/**
* 功能描述:
* @param: 创建消息队列hello
* @return:
* @auther: liguanhua
* @date: 2019-3-20 14:06
*/
@Bean
public Queue createQueue(){
return new Queue("hello");
}
}
创建消息发送者
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @ClassName Sender
* @Description TODO
* @Author liguanhua
* @Date 2019-3-20 14:07
* @Version 1.0
* 创建消息发送者
**/
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String msg){
//消息发送到hello这个消息队列。发送的信息为 msg
this.amqpTemplate.convertAndSend("hello",msg);
}
}
创建消息接收者
通过监听器来监听消息队列是否有消息进来。
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @ClassName Receiver
* @Description TODO
* @Author liguanhua
* @Date 2019-3-20 14:12
* @Version 1.0
* 消息接收者
**/
@Component
public class Receiver {
// 创建消息监听器
@RabbitListener(queues="hello")
public void process(String msg){
System.out.println(msg);
}
}
也可以将监听器放到类上
方法上带有@RabbitHandler的则处理消息
测试
import com.lgh.rabbit_mq.config.Sender;
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 RabbitMqApplicationTests {
@Autowired
private Sender sender;
@Test
public void contextLoads() {
}
@Test
public void queueTest() throws InterruptedException {
while (true){
Thread.sleep(1000);
sender.send("你好");
}
}
}
启动项目
上面测试写死循环为了看RabbitMq管理界面
可以来到RabbitMq管理界面,看到我们刚才创建的队列。
这样就可以简单的使用RebbitMq了
进一步测试
从上面可以看出来,当消息发送者发送给消息中间件之后,这里就可以不用管 消息中间件如何去发送消息给消息接收者了。