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

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.getExchange()}")
    private String exchange;

    @Value("#{rabbitMqConfig.getQueue()}")
    private String queue;

    public void sendMessage(String msg){

        this.sendMessage(msg, null, null);

    }

    public void sendMessage(String msg, String queue){

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

        this.sendMessage(msg, null, queue);

    }

    public void sendMessage(String msg, String exchange, String queue){

        if (StringUtils.isEmpty(exchange)) {
            exchange = this.exchange;
        }

        if (StringUtils.isEmpty(queue)) {
            queue = this.queue;
        }

        this.sendDirectMessage(msg, exchange, queue);

    }

    private void sendDirectMessage(String msg, String exchange, String queue) {
        amqpTemplate.convertAndSend(exchange, queue, msg);
        log.info("send sendMessage msg || exchange: {} || queue: {} || msg:{} ", exchange, queue, msg);
    }
}