SpringBoot2.X整合RabbitMQ

引入依赖

 <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);
    }

结果
在这里插入图片描述
工程:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值