先上代码:
1.实现连接池工厂接口,定义获取连接方式以及检测连接断开连接逻辑
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("spring.influx")
@Data
@Log4j2
public class InfluxDBPoolFactory implements PooledObjectFactory<InfluxDB> {
@Value("${spring.influx.user}")
private String userName;
@Value("${spring.influx.password}")
private String password;
@Value("${spring.influx.url}")
private String url;
@Value("${spring.influx.database}")
private String database;
@Value("${spring.influx.retentionPolicy}")
private String retentionPolicy;
//初始化连接池的时候执行
@Override
public PooledObject<InfluxDB> makeObject() throws Exception {
InfluxDB influxDB = InfluxDBFactory.connect(url,userName,password);
influxDB.setDatabase(database);
log.info("初始化连接池,获取Infludb连接");
return new DefaultPooledObject<>(influxDB);
}
//剔除连接的时候执行
@Override
public void destroyObject(PooledObject<InfluxDB> pooledObject) throws Exception {
pooledObject.getObject().close();
}
//如何开启了定时检测,在检测的时候执行
@Override
public boolean validateObject(PooledObject<InfluxDB> pooledObject) {
// boolean good = pooledObject.getObject().ping().isGood();
//