package cn.reghao.tnb.message.app.rabbit.c;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;

/**
 * @author reghao
 * @date 2021-04-01 21:55:32
 */
public class RabbitProducers {
    private final ConnectionFactory connFactory;
    private final String exchange = "amq.direct";

    public RabbitProducers(RabbitConfig config) {
        this.connFactory = new ConnectionFactory();
        this.connFactory.setHost(config.getHost());
        this.connFactory.setPort(5672);
        this.connFactory.setUsername(config.getUsername());
        this.connFactory.setPassword(config.getPassword());
        this.connFactory.setVirtualHost(config.getVhost());
    }

    public void sendObject(String exchange, String routeKey, Object payload) {
        try (Connection connection = connFactory.newConnection(); Channel channel = connection.createChannel()) {
            String msg = JsonConverter.objectToJson(payload);
            send(channel, exchange, routeKey, msg);
        } catch (Exception e) {
            System.out.printf("发送消息到 %s 队列失败...\n", routeKey);
            e.printStackTrace();
        }
    }

    public void sendMessage(String routeKey, Object bizMessage) {
        try (Connection connection = connFactory.newConnection(); Channel channel = connection.createChannel()) {
            String msg = JsonConverter.objectToJson(bizMessage);
            send(channel, exchange, routeKey, msg);
        } catch (Exception e) {
            System.out.printf("发送消息到 %s 队列失败...\n", routeKey);
            e.printStackTrace();
        }
    }

    private void send(Channel channel, String exchange, String routeKey, String msg) throws IOException {
        String msgBus = "MsgQueue.messageBus()";
        // 发送消息前先声明队列
        channel.queueDeclare(msgBus, true, false, false, null);
        channel.queueBind(msgBus, exchange, routeKey);
        channel.basicPublish(exchange, routeKey, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
    }
}
