package com.saga.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.zillion.util.log.LogUtil;

import javax.jms.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: fenghanchao
 * @since: 2022/1/14 11:44
 **/
public class MessageUtil {

    private static MessageProducer producer;

    private static Session session;

    public synchronized static Session getSession() throws Exception {
        if (session != null) {
            return session;
        }

        if (StringUtils.isBlank(Constant.activeMqBrokerUrl)) {
            LogUtil.error("读取不到activeMq的brokerUrl!");
            return null;
        }

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD
                , "failover:(" + Constant.activeMqBrokerUrl + ")?initialReconnectDelay=1000&maxReconnectDelay=30000");
        //创建jms连接
        Connection connection = connectionFactory.createConnection();
        connection.start();
        //创建session,参数是否开启事务，签收模式(自动签收Session.AUTO_ACKNOWLEDGE）
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        return session;
    }

    private static final long FIVE_MINUTES = 5 * 60 * 1000;

    public synchronized static MessageProducer getMessageProducer(Session session) throws Exception {
        if (session == null) {
            return null;
        }

        if (producer != null) {
            return producer;
        }
        //创建queue
        Queue queue = session.createQueue(Constant.queueName);//Destination
        //消息生产者
        producer = session.createProducer(queue);
        producer.setTimeToLive(FIVE_MINUTES);
        return producer;
    }

    public static void sendMessage(String message) throws Exception {
        Session session = getSession();
        if (session == null) {
            LogUtil.error("未连接到ActiveMq服务!");
            return;
        }
        MessageProducer messageProducer = getMessageProducer(session);
        if (messageProducer == null) {
            LogUtil.error("未连接到ActiveMq服务!");
            return;
        }
        TextMessage textMessage = session.createTextMessage(message);
        messageProducer.send(textMessage);
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            Map<String, Object> request = new HashMap<>();
            request.put("key1", "value1");
            sendMessage(JSONObject.toJSONString(request));
            Thread.sleep(1000 * 5);
        }

    }
}
