Rabbitmq发消息工具类

复制代码
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class RabbitCallbackMqUtils implements AutoCloseable {

    @Value("${rabbitmq.callback.host}")
    private String callbackHost;

    @Value("${rabbitmq.callback.port}")
    private Integer callbackPort;

    @Value("${rabbitmq.callback.username}")
    private String callbackUsername;

    @Value("${rabbitmq.callback.password}")
    private String callbackPassword;

    @Value("${rabbitmq.callback.virtual-host}")
    private String callbackVirtualHost;

    @Value("${rabbitmq.callback.exchange}")
    private String callbackExchange;

    @Value("${rabbitmq.callback.queue}")
    private String callbackQueue;

    @Value("${rabbitmq.callback.routing.key}")
    private String callbackRoutingKey;

    private Connection connection;

    private Channel channel;

    /**
     * 发送对象消息
     *
     * @param obj
     */
    public void sendObjectMessage(Object obj) {
        try {
            if (!isHostReachable(callbackHost, callbackPort, 2000)) {
                log.error("MQ服务器无法访问:{}:{}", callbackHost, callbackPort);
                return;
            }
            if (connection == null || !connection.isOpen()) {
                initConnection();
            }
            // 对象转 JSON
            String json = JacksonUtil.toJson(obj);
            if (StringUtils.isNotBlank(json)) {
                channel.basicPublish(callbackExchange, callbackRoutingKey, null, json.getBytes(StandardCharsets.UTF_8));
            }
            log.info("回调消息发送成功:{}", json);
        } catch (Exception e) {
            log.error("回调消息发送失败", e);
        }
    }

    /**
     * 初始化连接
     *
     * @throws Exception
     */
    private void initConnection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(callbackHost);
        factory.setPort(callbackPort);
        factory.setUsername(callbackUsername);
        factory.setPassword(callbackPassword);
        factory.setVirtualHost(callbackVirtualHost);
        factory.setConnectionTimeout(3000);
        factory.setHandshakeTimeout(3000);
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        channel.exchangeDeclare(callbackExchange, "direct", true);
        channel.queueDeclare(callbackQueue, true, false, false, null);
        channel.queueBind(callbackQueue, callbackExchange, callbackRoutingKey);
        log.info("RabbitMQ 回调连接初始化成功");
    }


    /**
     * 判断 IP:端口 是否能通
     *
     * @param host
     * @param port
     * @param timeoutMillis
     * @return
     */
    private boolean isHostReachable(String host, int port, int timeoutMillis) {
        try (Socket socket = new Socket()) {
            socket.connect(new java.net.InetSocketAddress(host, port), timeoutMillis);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void close() {
        try {
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
            if (connection != null && connection.isOpen()) {
                connection.close();
            }
        } catch (Exception e) {
            log.error("关闭连接异常", e);
        }
    }
}
相关推荐
952369 小时前
RabbitMQ - 高级特性
java·spring boot·分布式·后端·rabbitmq
qiu_lovejun9981 天前
linux安装docker和redis和rabbitmq和nginx和rocketmq和kafka
linux·redis·docker·kafka·rabbitmq·rocketmq
她说可以呀1 天前
RabbitMQ Confirm与Returns模式
分布式·rabbitmq
她说可以呀1 天前
RabbitMQ重试机制
分布式·rabbitmq
wuqingshun3141591 天前
RabbitMQ 中消息什么时候会进入死信交换机?
分布式·rabbitmq
hdsoft_huge1 天前
SpringBoot系列12:整合RabbitMQ消息队列,异步解耦、死信队列完整业务案例
spring boot·rabbitmq·java-rabbitmq
长不胖的路人甲2 天前
RabbitMQ 死信队列 DLQ
分布式·rabbitmq
她说可以呀3 天前
RabbitMQ Publisher_Confirms(发布确认)
分布式·rabbitmq·ruby
952364 天前
RabbitMQ-基础操作
java·spring boot·分布式·后端·spring·rabbitmq
Rain的Java大神实战圈5 天前
订单超时如何自动取消
消息队列·rabbitmq·高并发·架构设计