• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
进阶的大白
博客园    首页    新随笔    联系   管理    订阅  订阅
SpringBoot整合RabbitMQ

1.导入相应依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.在测试类里进行测试

package com.ws;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class Springboot02AmqpApplicationTests {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Test
    void contextLoads() {
        /*message需要自己构造一个;定义消息体内容和消息头
        *rabbitTemplate.send(exchange,routeKey,message)
        *
        * object默认当成消息体,只需要传入发送的对象,自动序列化发给rabbitmq
        * rabbitTemplate.convertAnd Send(exchange,routeKey,object)
        * */
        Map<String, Object> map = new HashMap<>();
        map.put("msg","one");
        map.put("data", Arrays.asList("HelloWorld",111));
        rabbitTemplate.convertAndSend("exchange.direct","ws.news",map);
    }
    @Test
    void test2(){
        Object o = rabbitTemplate.receiveAndConvert("ws.news");
        System.out.println(o.getClass());
        System.out.println(o);

    }
}

3.编写自己的序列化Bean

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.support.converter.MessageConverter;

@Configuration
public class MyAMQPConfig {
    @Bean
    public MessageConverter messageConverter(){
      return new Jackson2JsonMessageConverter();
    }
}

 4.使用监听时需要在主启动类上加上@EnableRabbit注解

   在方法上加@RabbitListener(queues="")注解,当消息队列里有值的时候就会被取出

 @RabbitListener(queues = "ws.news")
    public void get(User user){
        System.out.println("get"+user);
    }
    @RabbitListener(queues = "ws.news")
    public void get2(Message message){
        System.out.println(message.getBody());
        System.out.println(message.getMessageProperties());
    }

 

posted on 2020-08-03 15:30  进阶的大白  阅读(268)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3