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);
        }
    }
}
相关推荐
辰辉创聚12 小时前
禽流感病毒分子基础:表面抗原与内部转录复合体的功能解析
ide·leetcode·rabbitmq·重组血凝素蛋白·甲型流感病毒核蛋白·禽流感单抗
她说..13 小时前
RabbitMQ 使用场景详解
java·spring boot·后端·spring·rabbitmq·java-rabbitmq
weixin_4407305017 小时前
rabbitmq的使用记录-架构图、生产端、消费端、rabbitmqctl命令、重启MQ服务
rabbitmq
xbgRS17 小时前
RabbitMQ使用
rabbitmq
橙子圆1233 天前
RabbitMQ知识1
分布式·rabbitmq
無a伟5 天前
RabbitMq高级特性:TTL,死信队列,延迟队列
java·分布式·rabbitmq
小楼昨夜又东风1265 天前
kafka、rocketmq、rabbitmq,有什么区别
kafka·rabbitmq·rocketmq
無a伟5 天前
RabbitMq高级特性:消息确认,持久化,重试机制
java·分布式·rabbitmq
Dreams_l8 天前
如何保证RabbitMQ消息可靠传输
java·rabbitmq·java-rabbitmq
专注仿真10 天前
RabbitMQ消息队列实战项目
数据结构·rabbitmq