package org.springblade.common.notify.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.io.Serializable;
import java.util.Properties;

/**
 * 对象池
 *
 * @author caiyihua
 */
@Slf4j
public class ProducerProxyPool implements Serializable {
    private GenericObjectPool<ProducerProxy> objectPool;

    public ProducerProxyPool(Properties properties, GenericObjectPoolConfig config) {
        ProducerProxyPooledObjectFactory producerProxyPooledObjectFactory = new ProducerProxyPooledObjectFactory(properties);
        objectPool = new GenericObjectPool<>(producerProxyPooledObjectFactory, config);
    }

    public ProducerProxy getProducerProxy() {
        try {
            ProducerProxy producerProxy = objectPool.borrowObject();
            log.info("Get producer proxy successfully! Producer Proxy: {}, Pool active num: {}, idle num: {}, wait num: {}",
                    producerProxy.toString(), objectPool.getNumActive(), objectPool.getNumIdle(),
                    objectPool.getNumWaiters());
            return producerProxy;
        } catch (Exception e) {
            log.error("获取Producer Proxy连接异常: ", e);
            throw new RuntimeException("获取Producer Proxy连接异常: ", e);
        }
    }

    public void returnProducerProxy(ProducerProxy producerProxy) {
        try {
            // 将对象放回对象池
            objectPool.returnObject(producerProxy);
            log.info("Return producer proxy successfully! Producer Proxy: {}, Pool active num: {}, idle num: {}, wait num: {}",
                    producerProxy.toString(), objectPool.getNumActive(), objectPool.getNumIdle(),
                    objectPool.getNumWaiters());
        } catch (Exception e) {
            log.error("释放Producer Proxy连接异常: ", e);
        }
    }

    public void close() {
        objectPool.close();
    }
}
