package org.springblade.common.notify.message;

import com.aliyun.openservices.ons.api.Producer;
import java.io.Serializable;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

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

    public ProducerPool(Properties properties, GenericObjectPoolConfig config) {
        ProducerPooledObjectFactory producerPooledObjectFactory = new ProducerPooledObjectFactory(properties);
        objectPool = new GenericObjectPool<>(producerPooledObjectFactory, config);
    }

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

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

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