package com.sqx.nsqChannel.config;

import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeoutException;

@Slf4j
//@Component
public class NsqProduce {
    @Value("${nsq.port.produce}")
    private int port;

    @Value("${nsq.address}")
    private String address;


    private NSQProducer producer;
    private static boolean is_start = false;
    private static final byte[] LOCK = new byte[0];

    public NsqProduce() {
        producer = new NSQProducer();
        producer.addAddress(address, port).start();
        is_start = true;
    }

    public NSQProducer getProducer() {
        if (!is_start) {
            log.info("========================NSQProduce no start====================");
        }
        if (producer == null) {
            synchronized (LOCK) {
                if (producer == null) {
                    producer = new NSQProducer();
                    producer.addAddress(address, port).start();
                }
            }
        }
        return producer;
    }

    public void sendMsgToTestTopic(String topic,String msg) {
        try {
            this.getProducer().produce(topic, msg.getBytes());
        } catch (NSQException | TimeoutException e) {
            log.error(e.getMessage());
        }
    }
}