1、新建一个springboot项目,选择web、rabbitmq
2、rabbitmq相关信息
(1)RabbitAutoConfiguration
(2)自动配置了ConnectionFactory
(3)RabbitProperties封装了RabbitMQ配置
(4)RabbitTemplate:给RabbitMQ发送和接受消息
(5)AmqAdmin:RabbitMQ系统管理功能组件
3、在application.properties中配置rabbitmq相关
spring.rabbitmq.host=192.168.124.22 spring.rabbitmq.username=guest spring.rabbitmq.password=guest #spring.rabbitmq.virtual-host=
4、在springboot自带的测试文件中进行测试
package com.gong.springbootrabbitmq; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootRabbitmqApplicationTests { @Autowired RabbitTemplate rabbitTemplate; @Test public void contextLoads() { //点对点消息 //rabbitTemplate.send(exchange,routeKey,message);message需要自定义消息内容和消息头 //rabbitTemplate.convertAndSend(exchange,routeKey,object);主需要传入要发送的对象,会自动序列化发送给rabbitmq, // object默认当成消息体 Mapmap = new HashMap<>(); map.put("msg","这是第一个消息"); map.put("data", Arrays.asList("hello",123,true)); rabbitTemplate.convertAndSend("exchange.direct","gong.news",map); } }
首先是删除掉上一节进行测试的全部消息,点击Purge--Purge messages。然后运行测试,在rabbitmq界面上查看,成功发送了过来。
默认会被序列化之后发送。 然后我们再进行消息的获取:
@Test public void testRecieve(){ Object receiveAndConvert = rabbitTemplate.receiveAndConvert("gong.news"); System.out.println(receiveAndConvert.getClass()); System.out.println(receiveAndConvert); }
成功获得:
5、我们也可以设置发送消息为json格式
package com.gong.springbootrabbitmq.config; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyAmqpConfig { @Bean public MessageConverter messageConvter(){ return new Jackson2JsonMessageConverter(); } }
再测试发送数据:
6、测试发送一个对象
Book.java
package com.gong.springbootrabbitmq.bean; public class Book { private String bookName; private String author; @Override public String toString() { return "Book{" + "bookName='" + bookName + '\'' + ", author='" + author + '\'' + '}'; } public Book(){ } public Book(String bookName, String author) { this.bookName = bookName; this.author = author; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
我们这么发送:
rabbitTemplate.convertAndSend("exchange.direct","gong.news", new Book("英雄联盟","德玛西亚"));
也可以发送:
7、广播
@Test public void testMsg(){ rabbitTemplate.convertAndSend("exchange.fanout","", new Book("绝地求生","西西嘛呦")); }
都收到了消息: