package com.wx.application.nebula.graph.factory;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.vesoft.nebula.client.graph.net.Session;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NebulaGraphClient {

	private GenericObjectPool<Session> clientPool;
	
	public NebulaGraphClient(SessionFactory sessionFactory) {
		
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        
        //最大连接
        poolConfig.setMaxTotal(100);
        //最大空闲连接
        poolConfig.setMaxIdle(5);
        //最小空闲连接 
        poolConfig.setMinIdle(5);
        
        poolConfig.setTestWhileIdle(true);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        
        //连接满时最多等待时间
        /*poolConfig.setMaxWaitMillis(5000L);
         //使用时检查对象（默认不检查）
        poolConfig.setTestWhileIdle(true);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        //jmx启用 之后可以实时的查看线程池对象的状态
        poolConfig.setJmxEnabled(false);
        poolConfig.setJmxNameBase("namebase");
        poolConfig.setJmxNamePrefix("nameprefix");
         //驱逐线程每次检查对象个数
        poolConfig.setNumTestsPerEvictionRun(2);
        //空闲连接被驱逐前能够保留的时间
        poolConfig.setMinEvictableIdleTimeMillis(10000L);
        //当空闲线程大于minIdle 空闲连接能够保留时间，同时指定会被上面的覆盖
        poolConfig.setSoftMinEvictableIdleTimeMillis(10000L);
        //驱逐线程执行间隔时间
        poolConfig.setTimeBetweenEvictionRunsMillis(200000L);
        //放弃长时间占用连接的对象
       	AbandonedConfig abandonedConfig=new AbandonedConfig();
       	abandonedConfig.setLogAbandoned(true);
       	abandonedConfig.setUseUsageTracking(false);
       	abandonedConfig.setRemoveAbandonedOnBorrow(true);
       	abandonedConfig.setRemoveAbandonedOnMaintenance(true);
       	abandonedConfig.setRemoveAbandonedTimeout(20);//second*/
        
        this.clientPool = new GenericObjectPool<>(sessionFactory, poolConfig);
	}
	
	public Session getSession() throws Exception {
		return clientPool.borrowObject();
	}
	public void returnSession(Session session) {
		if(session == null) {
			return;
		}
		clientPool.returnObject(session);
	}
}
