引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
RabbitMQ的自动配置类
RabbitAutoConfiguration
测试运行
@SpringBootTest
class RabbitmqdemoApplicationTests {
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
//点对点 发送
@Test
void contextLoads() {
Map<Object,Object> map=new HashMap<>();
map.put("msg","wanghao");
map.put("data",Arrays.asList("helloword",123,true));
rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map);
}
@Test
void g() {
Object o = rabbitTemplate.receiveAndConvert("atguigu.news");
System.out.println(o.getClass());
System.out.println(o.toString());
}
}
运行发送方法:收到数据的形式
运行接收方法:控制台显示,同时队列中的消息自动删除
如何让消息以json的形式发送出去?
(RabbitTemplate 中
private MessageConverter messageConverter = new SimpleMessageConverter()这个类里面用的是jdk的东西)
方法:
@Configuration
public class RabbitConfig {
//import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
//import org.springframework.amqp.support.converter.MessageConverter;
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
在此运行发送方法:结果
反序列化获取出来:
RabbitListener&EnableRabbit
@SpringBootApplication
@EnableRabbit
public class RabbitmqdemoApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqdemoApplication.class, args);
}
}
@Configuration
public class RabbitConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
@Service
public class BookService {
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
@RabbitListener(queues = {"atguigu"})
public void receve(Book book){
System.out.println("receve======");
System.out.println("队列收到Book---"+book);
}
@RabbitListener(queues = {"atguigu.news"})
public void receve02(Message message){
System.out.println("receve02======");
message.getBody();
System.out.println(new String(message.getBody()));
System.out.println(message.getMessageProperties());
}
}
@Test
void yy() {
Book book=new Book(11,"三国杀");
rabbitTemplate.convertAndSend("exchange.fanout","",book);
}
结果:
工程: