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 javax.jms.*;
import java.util.HashMap;
import java.util.Map;

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

    public static final String QUEUE_NAME = "collection.queue.20220114";

    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)) {
            throw new Exception("读取不到activeMq的brokerUrl!");
        }

        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;
    }

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

        Session session = getSession();
        //创建queue
        Queue queue = session.createQueue(QUEUE_NAME);//Destination
        //消息生产者
        producer = session.createProducer(queue);
        return producer;
    }

    public static void sendMessage(String message) throws Exception {
        MessageProducer messageProducer = getMessageProducer();
        TextMessage textMessage = getSession().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);
        }

    }
}
