使用工具idea,springboot版本2.0+,RabbitMQ我已经在自己的云服务器Linux上面安装了,你们要测试的话,自己可以在本地安装RabbitMQ
github地址是https://github.com/samdidemo/springboot-rabbitMQ.git
第一步,创建新工程
第二步,引进相应的依赖
然后,在application.properties中添加配置,服务器地址,就是你安装RabbitMQ的ip地址,如果你是安装在本地,那么你直接写localhost就行,用户名和密码默认是guest
在主类中添加@EnableRabbit注解,开启RabbitMQ
新建一个类,其中新建一个方法,比如在这个方法开头添加注解@RabbitListener(queues = "lin"),它便会监听消息队列lin,一旦里面有消息,便会进行接收
public class rabbitService {
@RabbitListener(queues = "lin")
public void recieve(Map<String, Object> map){
System.out.println(map.toString());
}
}
我们可以在测试类中自动注入RabbitTemplate template; 然后使用template.convertAndSend("linyongbin","lin",map)发送消息到队列中,测试是否接收到了消息
其中“linyongbin”是交换机的名字,“lin”是路由键,map是要传送的东西
@Autowired
RabbitTemplate template;
@Test
public void contextLoads() {
Map<String,Object> map=new HashMap<>();
map.put("msg","林阳光发送消息");
map.put("name","linyongbin");
template.convertAndSend("linyongbin","lin",map);
}