MessageProducer.java 1.36 KB
package com.topdraw.mq.producer;

import com.topdraw.config.LocalConstants;
import com.topdraw.mq.config.RabbitMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
@Slf4j
public class MessageProducer {


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Value("#{rabbitMqConfig.getRoutingKey()}")
    private String routingKey;


    public void sendMessage(String msg,String exchangeName){

        // 管理侧
        if (StringUtils.isEmpty(exchangeName)) {
            exchangeName = this.routingKey;
        }

        this.sendDirectMessage(msg,exchangeName);

    }

    /**
     * 直连
     * @param msg
     * @param queueName
     * @author XiangHan
     * @date 2021/9/7 11:10 上午
     */
    private void sendDirectMessage(String msg,String queueName) {

        amqpTemplate.convertAndSend(queueName, msg);
        log.info("send sendMessage msg || routingkey: {} || msg:{} ", queueName, msg);
    }

    /**
     * 发送
     * @param msg
     * @author XiangHan
     * @date 2021/9/7 11:10 上午
     */
    public void sendMessage(String msg) {
        this.sendMessage(msg,null);
    }
}