Springboot整合RabbitMQ

pom
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
application.yml
server:
  port: 802

spring:
  rabbitmq:
    host: IP
    port: PORT
    username: 
    password: 
    # 开启发送确认
    # 开启发送失败退回
    publisher-returns: true
#    # 开启ACK,没用到所以没改格式
#    listener.direct.acknowledge-mode=manual
#    listener.simple.acknowledge-mode=manual
测试类
@SpringBootTest
class RabbitmqConsumerApplicationTests {

//    @Test
//    void contextLoads() {
//    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * direct 单播
     * 参数为exchange,routekey,msg消息体
     */
    @Test
    public void pubDirect(){

        HashMap<String,String>hashMap = new HashMap<>();
        hashMap.put("001","hello");
        hashMap.put("002","rabbitmq");
        rabbitTemplate.convertAndSend("awsa.direct","awsa.emps",hashMap);
    }

    /**
     * 广播
     */
    @Test
    public void pubFanout(){

        HashMap<String,String>hashMap = new HashMap<>();
        hashMap.put("001","hello");
        hashMap.put("002","rabbitmq");
        rabbitTemplate.convertAndSend("awsa.fanout","awsa.emps",hashMap);
    }
    /**
     * 接收方法receiveAndConvert
     */
    
    @Test
    public void receive(){
        Object o = rabbitTemplate.receiveAndConvert("awsa.emps");
        System.out.println(o.getClass());
        System.out.println(o.toString());
    }
}
生产环境大部分用RabbitListener进行监听
@Service
public class RabbitService {

    //可直接接受对象
    @RabbitListener(queues = "awsa.emps")
    public void receiveMsg(Object o){
        System.out.println("receive message"+o.toString());
    }

    //建议用Message接收
    @RabbitListener(queues = "awsa.emps")
    public void receiveMsg(Message msg){
        System.out.println("receive message body" + new String(msg.getBody()));
        System.out.println("message handle"+msg.getMessageProperties());
    }
}

@SpringBootApplication
@EnableRabbit //开启基于注解的rabbitMQ
public class RabbitmqConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(RabbitmqConsumerApplication.class, args);
    }
}
若需要改json传输
@Configuration
public class MyAmqpConfig {
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值