Mq队列及交换机代码示例

首先写一个RabbitMQ的配置类,可以点对点的形式注入Queue,也可以用交换机的形式

package com.moon.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class RabbitConfig {
    @Bean
    public Queue XukeQ(){
        return new Queue("XukeQ");
    }

    @Bean
    public Queue QuzheQ() {
        return new Queue("QuzheQ");
    }

    @Bean
    public FanoutExchange liShenExchange(){
        return  new FanoutExchange("liShenExchange");
    }
    @Bean
    public DirectExchange DingJianJunExchange() {
        return new DirectExchange("DingJianJunExchange");
    }

    //定义绑定关系
    @Bean
    public Binding bindQuzheQToliShenExchange(){
        return BindingBuilder.bind(XukeQ()).to(liShenExchange());
    }

    @Bean
    public Binding bindQuzheQToliShenExchange2(){
        return BindingBuilder.bind(QuzheQ()).to(liShenExchange());
    }
    @Bean
    public Binding bindQuzheQToliShenExchange3(){
        return BindingBuilder.bind(XukeQ()).to(DingJianJunExchange()).with("aaa");
    }
    @Bean
    public Binding bindQuzheQToliShenExchange4(){
        return BindingBuilder.bind(XukeQ()).to(DingJianJunExchange()).with("nnn");
    }





}

然后是在controller发送消息及接受消息的代码详解

package com.moon.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mq")
public class MqController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/addToQ")
    public String addToQ(String task){
        rabbitTemplate.convertAndSend("DingJianJunExchange","nnn", task);
        return "success";
    }
  @RequestMapping("/getFromQ")
    public String getFromQ(String task){
    String xukeQ = rabbitTemplate.receiveAndConvert("liShenExchange").toString();
        return xukeQ;
    }
}

配置一个监听器

package com.moon.listener;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class XuKeQlistener {
    @Value("${moon.proj.name}")
    private String name;

    @RabbitListener(queues="XukeQ")
    public  void onMsg(String task){
        System.out.println(name+":222"+task);
    }
    @RabbitListener(queues="QuzheQ")
    public  void onMsg1(String task){
        System.out.println(name+":"+task);
    }
}
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值