RabbitMQ(4)模板代码

本文详细介绍了RabbitMQ的高级配置方法,包括死信队列模式的配置,以及如何通过Spring Boot进行消息生产与消费的实现。通过具体代码示例,展示了不同类型的交换机与队列的使用,如Direct、Topic、Fanout等,并提供了消息生产者与消费者的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,application.properties对rabbitmq的配置

#对于rabbitMQ的支持
########################################################
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

2,配置RabbitConfig(增加死信队列模式)

package lc.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;


/**
 * @author liuchaoOvO on 2018/12/28
 * @description RabbitMQ 配置类
 */
@Configuration
public class RabbitConfig {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value ("${rabbitmq.host}")
    private String host;
    @Value ("${rabbitmq.port}")
    private int port;
    @Value ("${rabbitmq.username}")
    private String username;
    @Value ("${rabbitmq.password}")
    private String password;
    /**
     * 调用正常队列过期时间 单位为微秒.
     */
    @Value ("${tq.makecall.expire:60000}")
    private long makeCallExpire;

    //交换机
    public static final String DirectExchange_A = "directExchange_A";
    public static final String TopicExchange_B = "topicExchange_B";
    public static final String FanoutExchange_C = "fanoutExchange_C";
    public static final String TopicExchange_DeadLetter = "topicExchange_DeadLetter"; //死信交换机名称

    //路由键  用于把生产者的数据绑定到交换机上的
    public static final String DirectExchange_ROUTINGKEY = "DirectExchange_ROUTINGKEY";
    public static final String DirectExchange_SecKillROUTINGKEY = "DirectExchange_SecKillROUTINGKEY";
    public static final String TopicExchange_ROUTINGKEYSecond = "topic.second";
    public static final String TopicExchange_ROUTINGKEYThird = "topic.second.third";
    public static final String TopicExchange_DLROUTINGKEY = "lind.queue";
    //绑定键  用于把交换机的消息绑定到队列
    public final static String TopicROUTINGKEYOne = "topic.*";  //表达式适合topic.开头的下一级
    public final static String TopicROUTINGKEYAll = "topic.#";  //表达式适合topic.开头的所有

    //队列
    public static final String QUEUE_A = "QUEUE_A";
    public static final String QUEUE_B = "QUEUE_B";
    public static final String QUEUE_ProviderService_A = "QUEUE_Provider_A";
    public static final String QUEUE_C = "topic.QUEUE_C";
    public static final String QUEUE_D = "topic.QUEUE_D";
    public static final String QUEUE_Fanout_A = "fanout.A";
    public static final String QUEUE_Fanout_B = "fanout.B";
    public static final String QUEUE_SecKillQueue = "QUEUE_SecKillQueue";

    public static final String LIND_DEAD_QUEUE = "lind.queue.dead";

    @Bean
    public ConnectionFactory connectionFactory() {
        logger.info("rabbitmq的配置信息为host:[" + host + "]port:[" + port + "]username:[" + username + "]password:[" + password + "]");
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);  //自动确认机制 false为手动确认
        return connectionFactory;
    }

    @Bean
    @Scope (ConfigurableBeanFactory.SCOPE_PROTOTYPE)     //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

    /**
     * 针对消费者配置
     * 1. 设置交换机类型
     * 2. 将队列绑定到交换机
     * FanoutExchange: 将消息分发到所有的绑定队列,无routingkey的概念
     * HeadersExchange :通过添加属性key-value匹配
     * DirectExchange:按照routingkey分发到指定队列
     * TopicExchange:多关键字匹配
     */
    @Bean
    public DirectExchange defaultExchange() {
        return new DirectExchange(DirectExchange_A);
    }

    @Bean
    TopicExchange topicExchange() {
        return new TopicExchange(TopicExchange_B);
    }

    /**
     * 广播交换机.
     */
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange(FanoutExchange_C);
    }

    /**
     * 获取队列A
     */
    @Bean
    public Queue queueA() {
        return new Queue(QUEUE_A, true); //队列持久
    }

    /**
     * 获取队列B
     */
    @Bean
    public Queue queueB() {
        return new Queue(QUEUE_B, true); //队列持久
    }

    /**
     * 获取Topic队列C
     */
    @Bean
    public Queue queueC() {
        return new Queue(QUEUE_C, true); //队列持久
    }

    /**
     * 获取Topic队列D
     */
    @Bean
    public Queue queueD() {
        return new Queue(QUEUE_D, true); //队列持久
    }

    @Bean
    public Queue queueFanoutA() {
        return new Queue(QUEUE_Fanout_A);
    }

    @Bean
    public Queue queueFanoutB() {
        return new Queue(QUEUE_Fanout_B);
    }

    @Bean
    public Queue queue_SecKillQueue() {
        return new Queue(QUEUE_SecKillQueue, true);
    }


    /**
     * 创建死信交换机.
     */
    @Bean
    public TopicExchange lindExchangeDl() {
        return (TopicExchange) ExchangeBuilder.topicExchange(TopicExchange_DeadLetter).durable(true)
                .build();
    }

    /**
     * 创建普通队列.
     */
    @Bean
    public Queue lindQueue() {
        return QueueBuilder.durable(QUEUE_ProviderService_A)
                .withArgument("x-dead-letter-exchange", TopicExchange_DeadLetter)//设置死信交换机
                .withArgument("x-message-ttl", makeCallExpire)
                .withArgument("x-dead-letter-routing-key", LIND_DEAD_QUEUE)//设置死信routingKey
                .build();
    }

    /**
     * 创建死信队列.
     */
    @Bean
    public Queue lindDelayQueue() {
        return QueueBuilder.durable(LIND_DEAD_QUEUE).build();
    }

    /**
     * 绑定死信队列.
     */
    @Bean
    public Binding bindDeadBuilders() {
        return BindingBuilder.bind(lindDelayQueue()).to(lindExchangeDl()).with(LIND_DEAD_QUEUE);
    }

    /**
     * 绑定普通队列.
     *
     * @return
     */
    @Bean
    public Binding bindBuilders() {
        return BindingBuilder.bind(lindQueue()).to(topicExchange()).with(TopicExchange_DLROUTINGKEY);
    }


    @Bean
    public Binding binding_QueueA_DirectExchange_ROUTINGKEY() {
        return BindingBuilder.bind(queueA()).to(defaultExchange()).with(RabbitConfig.DirectExchange_ROUTINGKEY);
    }

    @Bean
    public Binding binding_QUEUE_SecKillQueue_DirectExchange_SecKillROUTINGKEY() {
        return BindingBuilder.bind(queue_SecKillQueue()).to(defaultExchange()).with(RabbitConfig.DirectExchange_SecKillROUTINGKEY);
    }

    @Bean
    Binding binding_queueFanoutA_FanoutExchange() {
        return BindingBuilder.bind(queueFanoutA()).to(fanoutExchange());
    }

    @Bean
    Binding binding_queueFanoutB_FanoutExchange() {
        return BindingBuilder.bind(queueFanoutB()).to(fanoutExchange());
    }

    @Bean
    Binding binding_queueC_TopicExchange() {
        return BindingBuilder.bind(queueC()).to(topicExchange()).with(TopicROUTINGKEYOne);
    }

    @Bean
    Binding binding_queueD_TopicExchange() {
        return BindingBuilder.bind(queueD()).to(topicExchange()).with(TopicROUTINGKEYAll);
    }

    //json消息转换器   保证接收和发送的格式一致
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        return factory;
    }
}

3,MsgProducer  消息生产者

package lc.mqproducer;

import lc.config.RabbitConfig;
import lc.entity.SeckillMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
public class MsgProducer implements RabbitTemplate.ConfirmCallback {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE,所以不能自动注入,需要构造方法注入的方式
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MsgProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话,那回调就是最后设置的内容
    }

    public String sendTopicMsg(String content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        //把消息放入TopicROUTINGKEY_B对应的队列当中去
        rabbitTemplate.convertAndSend(RabbitConfig.TopicExchange_B, RabbitConfig.TopicExchange_ROUTINGKEYThird, content, correlationId);
        return correlationId.toString();
    }

    public String mqSendUserObj(Object object) {
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            //把消息放入ROUTINGKEY_A对应的队列当中去,对应的是队列A
            rabbitTemplate.convertAndSend(RabbitConfig.DirectExchange_A, RabbitConfig.DirectExchange_ROUTINGKEY, object, correlationId);
            return correlationId.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String mqSendFanoutObj(Object object) {
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            //把消息放入ROUTINGKEY_A对应的队列当中去,对应的是队列A
            rabbitTemplate.convertAndSend(RabbitConfig.FanoutExchange_C, null, object, correlationId);
            return correlationId.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String mqSendTopicObj(Object object) {
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            //把消息放入ROUTINGKEY_A对应的队列当中去,对应的是队列A
            rabbitTemplate.convertAndSend(RabbitConfig.TopicExchange_B, RabbitConfig.TopicExchange_ROUTINGKEYThird, object, correlationId);
            return correlationId.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        logger.info(" 回调id:" + correlationData);
        if (ack) {
            logger.info("消息成功消费");
        } else {
            logger.info("消息消费失败:" + cause);
        }
    }

    public String sendSecKillMsg(SeckillMessage message) {
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(RabbitConfig.DirectExchange_A, RabbitConfig.DirectExchange_SecKillROUTINGKEY, message, correlationId);
            return "sendSecKill发送成功," + correlationId.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

4,MsgReceiver  消息消费者

package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.FanoutObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_Fanout_A,containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueue_Fanout_A
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RabbitHandler
    public void processHandler(@Payload FanoutObj obj)
    {
        logger.info("QUEUE_Fanout_A--用户信息:"+obj.toString());
    }
}

package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.FanoutObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
@RabbitListener (queues = RabbitConfig.QUEUE_Fanout_B, containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueue_Fanout_B {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processHandler(@Payload FanoutObj obj) {
        logger.info("QUEUE_Fanout_B--用户信息:" + obj.toString());
    }
}


package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */

@Component
@RabbitListener(queues = RabbitConfig.QUEUE_A,containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueueA
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processHandler(@Payload SysUser obj)
    {
        logger.info("用户信息:"+obj.toString());
    }
}


package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.SysUser;
import lc.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;


/**
 * @author liuchaoOvO on 2018/12/28
 */

@Component
@RabbitListener (queues = RabbitConfig.QUEUE_B, containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueueB {
    //处理User的Service
    @Autowired
    private UserService service;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processRegist(@Payload SysUser obj) {
        try {
            logger.info("processObj()接收处理队列A当中的消息:" + obj.toString());
            boolean flag = service.addUser(obj);
            if (flag == true) {
                logger.info("处理队列A的数据:" + obj.toString() + ",成功。");
            } else {
                logger.info("处理队列A的数据:" + obj.toString() + ",失败。");
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
    }
}


package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.TopicObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_C,containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueueC
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processHandler(@Payload TopicObj obj)
    {
        logger.info("QUEUE_C--客户端收到的信息:"+obj.toString());
    }
}

 

package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.entity.TopicObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_D,containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverQueueD
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processHandler(@Payload TopicObj obj)
    {
        logger.info("QUEUE_D--客户端收到的信息:"+obj.toString());
    }

}

 

package lc.mqreceiver;

import lc.config.RabbitConfig;
import lc.dto.OrderInfo;
import lc.entity.GoodsVo;
import lc.entity.SeckillMessage;
import lc.service.secKill.SecKillService;
import lc.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author liuchaoOvO on 2018/12/28
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_SecKillQueue,containerFactory = "rabbitListenerContainerFactory")
public class MsgReceiverSecKillQueue
{
    @Autowired
    private SecKillService secKillService;
    @Autowired
    private RedisUtil redisUtil;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RabbitHandler
    public void processSecKill(@Payload SeckillMessage obj)
    {
        try
        {
            logger.info("receive message:" + obj.toString());
            lc.entity.SysUser user = obj.getUser();
            long goodsId = obj.getGoodsId();
            GoodsVo goodsVo = secKillService.getGoodsVoByGoodsId(goodsId);
            int stock = goodsVo.getStock_count();
            if (stock <= 0)
            {
                return;
            }
            //判断重复秒杀
            Object order = redisUtil.get("" + user.getId() + "_" + goodsId);
            if (order != null)
            {
                return;
            }
            try {
                //减库存 下订单 写入秒杀订单
                OrderInfo orderInfo = secKillService.seckill(user, goodsVo);
                logger.info("orderInfo:" + orderInfo.toString());
            }catch (Exception e){
                logger.info(e.getMessage());
            }
        }catch (Exception e){
            logger.debug(e.getMessage());
        }
    }

}

 5、消息体 各种自定义的实体dto类(需要实现序列化)

package lc.entity;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * @author liuchaoOvO on 2019/9/19
 */
@Setter
@Getter
@ToString
@EqualsAndHashCode
public class TopicObj implements Serializable {
    private static final long serialVersionUID = 1L;

    private String topicObj_id;
    private String topicObj_name;
    private String topicObj_code;
}
package lc.entity;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * @author liuchaoOvO on 2019/9/19
 */
@Setter
@Getter
@ToString
@EqualsAndHashCode
public class FanoutObj implements Serializable {
    private static final long serialVersionUID = 1L;

    private String fanoutObj_id;
    private String fanoutObj_name;
    private String fanoutObj_code;
}

 

package lc.entity;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;


/**
 * @author liuchaoOvO on 2019/4/16
 */


@Setter
@Getter
@ToString
@EqualsAndHashCode
public class SysUser implements Serializable
{
    private static final long serialVersionUID = 1L;

    private String id;
    private String username;
    private String password;
    private int status;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date last_ver;

    public SysUser(){

    }
    public SysUser(String id, String username, String password)
    {
        this.id=id;
        this.username=username;
        this.password=password;
    }
    public SysUser(String id, String username, String password, int status, Date last_ver)
    {
        this.id=id;
        this.username=username;
        this.password=password;
        this.status=status;
        this.last_ver=last_ver;
    }
}

6、mq 发送的controller

package lc.controller.mq;

import lc.entity.FanoutObj;
import lc.entity.SysUser;
import lc.entity.TopicObj;
import lc.mqproducer.MsgProducer;
import lc.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author liuchaoOvO on 2019/4/11
 */
@Controller
@RequestMapping(value = "/mq")
public class MQController
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MsgProducer msgProducer;
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    //验证直接模式
    @RequestMapping(value="/mqSendUserObj", method= RequestMethod.POST)
    @ResponseBody
    public void mqSendUserObj(SysUser sysUser) throws Exception{
        //uuid 设置主键
        sysUser.setId(UUIDUtil.uuid());
        sysUser.setStatus(1);
        sysUser.setLast_ver(new Date());
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        String correlationId=msgProducer.mqSendUserObj(sysUser);
        if(correlationId!=""){
            logger.info("发送到mq的请求成功:"+correlationId+"/mqSendMsg");
        }
       else{
            logger.info("发送到mq的请求失败");
        }
    }

    //验证广播模式
    @RequestMapping(value="/mqSendFanoutObj", method= RequestMethod.POST)
    @ResponseBody
    public void mqSendFanoutObj(FanoutObj object) throws Exception{
        String correlationId=msgProducer.mqSendFanoutObj(object);
        if(correlationId!=""){
            logger.info("发送到mq的请求成功:"+correlationId+"/mqSendFanoutObj");
        }
        else{
            logger.info("发送到mq的请求失败");
        }
    }
    //验证话题模式
    @RequestMapping(value="/mqSendTopicObj", method= RequestMethod.POST)
    @ResponseBody
    public void mqSendTopicObj(TopicObj object) throws Exception{
        String correlationId=msgProducer.mqSendTopicObj(object);
        if(correlationId!=""){
            logger.info("发送到mq的请求成功:"+correlationId+"/mqSendTopicObj");
        }
        else{
            logger.info("发送到mq的请求失败");
        }
    }

    @RequestMapping(value="/mqSendTopMsg", method= RequestMethod.POST)
    public void mqSendTopMsg(String msg) throws Exception{
        String correlationId=msgProducer.sendTopicMsg(msg);
        if(correlationId!=""){
            System.out.println("发送到mq的请求成功:"+correlationId+"/mqSendTopMsg");
        }
        else{
            System.out.println("发送到mq的请求失败");
        }
    }
    @RequestMapping(value="/mqUI", method= RequestMethod.GET)
    public String mqUI() throws Exception{
        return "/mq/mqUI";
    }
}

 在某个类文件对象中,注入生产者消息对象:

@Autowired
    private MsgProducer msgProducer;

执行相应的生产者函数逻辑代码:
例如:

String correlationId=msgProducer.mqSendUserObj(object);

则在相应的,通过Queue类型

@RabbitListener(queues = RabbitConfig.QUEUE_A,containerFactory = "rabbitListenerContainerFactory")

例如对队列A的匹配下的消费者的

 @RabbitHandler
    public void processHandler(@Payload SysUser obj)
    {
        logger.info("用户信息:"+obj.toString());
    }

执行方法中处理相应的业务逻辑。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值