qq_36319828 2022-06-21 09:40 采纳率: 16.7%
浏览 144
已结题

如何使用commons-pool2建立influxdb1.8的数据库连接池

我现在想在springboot中集成influxdb1.8,已经能够实现数据的查找以及传递,但是只有一个最基础的influxdb配置类,目前想通过使用commons-pool2来建立一个数据库连接池,但是目前网上的都是influxdb2.0的写法,想请教一下该怎么写

  • 写回答

3条回答 默认 最新

  • blackoon88 2022-06-21 17:43
    关注

    1.添加maven依赖

            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
                <version>2.11.1</version>
            </dependency>
    
            <!--influxdb-->
            <dependency>
                <groupId>com.influxdb</groupId>
                <artifactId>influxdb-client-java</artifactId>
                <version>2.3.0</version>
            </dependency>
    
    

    2.代码如下

    
    package com.valley.util.influxdbpool;
    
    import com.influxdb.client.InfluxDBClient;
    import com.influxdb.client.InfluxDBClientFactory;
    import com.influxdb.client.domain.HealthCheck;
    import org.apache.commons.pool2.PooledObject;
    import org.apache.commons.pool2.PooledObjectFactory;
    import org.apache.commons.pool2.impl.DefaultPooledObject;
    
    /**
     * @author valley
     * @date 2022/6/21
     * @Description 创建一个对象工厂
     */
    public class InfluxdbPooledObjectFactory implements PooledObjectFactory<InfluxDBClient> {
    
        @Override
        public void activateObject(PooledObject<InfluxDBClient> p) throws Exception {
            System.out.println("重新初始化要由池返回的实例-即从池中借用一个对象时调用");
        }
    
        @Override
        public void destroyObject(PooledObject<InfluxDBClient> pooledObject) throws Exception {
            InfluxDBClient influxDBClient = pooledObject.getObject();
            influxDBClient.close();
        }
    
        @Override
        public PooledObject<InfluxDBClient> makeObject() throws Exception {
    //        InfluxDBClient client = InfluxDBClientFactory.create(this.url, this.token.toCharArray());
    //        InfluxDBClient client = InfluxDBClientFactory.create("http://127.0.0.1:8086","root","gugu".toCharArray());
            InfluxDBClient client = InfluxDBClientFactory.createV1("http://127.0.0.1:8086","root","gugu".toCharArray(),"telegraf","autogen");
            System.out.println("创建可由池提供服务的实例,并将其包装在由池管理的PooledObject中, hashcode :"+client.hashCode());
            return new DefaultPooledObject<>(client);
        }
    
        @Override
        public void passivateObject(PooledObject<InfluxDBClient> p) throws Exception {
            System.out.println("取消初始化要返回到空闲对象池的实例-即从池中归还一个对象时调用");
        }
    
        @Override
        public boolean validateObject(PooledObject<InfluxDBClient> pooledObject) {
            InfluxDBClient influxDBClient = pooledObject.getObject();
            HealthCheck health = influxDBClient.health();
            return HealthCheck.StatusEnum.PASS.equals(health.getStatus());
        }
    }
    
    
    
    
    package com.valley.util.influxdbpool;
    
    import com.influxdb.client.InfluxDBClient;
    import org.apache.commons.pool2.PooledObjectFactory;
    import org.apache.commons.pool2.impl.AbandonedConfig;
    import org.apache.commons.pool2.impl.GenericObjectPool;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    
    /**
     * @author valley
     * @date 2022/6/21
     * @Description 创建对象池,继承GenericObjectPool
     */
    public class InluxdbClientPool extends GenericObjectPool<InfluxDBClient> {
        public InluxdbClientPool(PooledObjectFactory<InfluxDBClient> factory) {
            super(factory);
        }
        public InluxdbClientPool(PooledObjectFactory<InfluxDBClient> factory, GenericObjectPoolConfig<InfluxDBClient> config) {
            super(factory, config);
        }
    
        public InluxdbClientPool(PooledObjectFactory<InfluxDBClient> factory, GenericObjectPoolConfig<InfluxDBClient> config, AbandonedConfig abandonedConfig) {
            super(factory, config, abandonedConfig);
        }
    }
    
    
    
    package com.valley.util.influxdbpool;
    
    import com.influxdb.client.InfluxDBClient;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.annotation.PreDestroy;
    
    /**
     * @author valley
     * @date 2022/6/21
     * @Description 创建对象池自动装配配置类,将对象池做成一个Bean
     */
    @Configuration
    public class InfluxdbPoolAutoConfig {
        private InluxdbClientPool pool;
    
        @ConditionalOnClass({InfluxdbPooledObjectFactory.class})
        @Bean("inluxdbClientPool")
        protected InluxdbClientPool createInluxdbClientPool(){
            InfluxdbPooledObjectFactory factory = new InfluxdbPooledObjectFactory();
            // 设置对象池相关参数
            GenericObjectPoolConfig<InfluxDBClient> poolConfig = new GenericObjectPoolConfig<>();
            /**
             * 最大空闲
             */
            poolConfig.setMaxIdle(5);
            /**
             * 最大总数
             */
            poolConfig.setMaxTotal(10);
            /**
             * 最小空闲
             */
            poolConfig.setMinIdle(2);
            poolConfig.setBlockWhenExhausted(true);
            poolConfig.setTestOnBorrow(true);
            poolConfig.setTestOnReturn(true);
            poolConfig.setTestWhileIdle(true);
            poolConfig.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30);
            //一定要关闭jmx,不然springboot启动会报已经注册了某个jmx的错误
            poolConfig.setJmxEnabled(false);
    
            // 新建一个对象池,传入对象工厂和配置
            pool = new InluxdbClientPool(factory, poolConfig);
    
            initPool(3, 5);
    
            return pool;
        }
    
        /**
         * 预先加载testObject对象到对象池中
         *
         * @param initialSize 初始化连接数
         * @param maxIdle     最大空闲连接数
         */
        private void initPool(int initialSize, int maxIdle) {
            if (initialSize <= 0) {
                return;
            }
    
            int size = Math.min(initialSize, maxIdle);
            for (int i = 0; i < size; i++) {
                try {
                    pool.addObject();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        @PreDestroy
        public void destroy() {
            if (pool != null) {
                pool.close();
            }
        }
    }
    
    
    
    package com.valley.util.influxdbpool;
    
    import com.influxdb.client.InfluxDBClient;
    import com.influxdb.query.FluxRecord;
    import com.influxdb.query.FluxTable;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    import javax.annotation.Resource;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author valley
     * @date 2022/6/21
     * @Description 使用池
     */
    @Component
    public class Client {
    
        @Resource
        private InluxdbClientPool inluxdbClientPool;
    
        @PostConstruct
        public  void test() {
            List<FluxTable> tables = new ArrayList<>();
            String database = "telegraf";
            String retentionPolicy = "autogen";
            String query = String.format("from(bucket: \"%s\") " +
                    " |> range(start: -1h)", database);
            InfluxDBClient poolClient = null;
            try {
                poolClient = inluxdbClientPool.borrowObject();
                tables = poolClient.getQueryApi().query(query);
                tables.get(0).getRecords()
                        .forEach(record -> System.out.println(String.format("%s %s: %s %s",
                                record.getTime(), record.getMeasurement(), record.getField(), record.getValue())));
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (poolClient != null) {
                    //最终归还对象到对象池
                    inluxdbClientPool.returnObject(poolClient);
                }
            }
        }
    }
    
    

    img

    若有帮助,谢谢采纳~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 7月2日
  • 已采纳回答 6月24日
  • 赞助了问题酬金40元 6月21日
  • 创建了问题 6月21日

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!