封装的influxDB工具类(不依赖json反序列化)

1 背景

之前写过一篇influxDB工具类的文章,见《封装的influxDB工具类》,里面使用了fastJson来把从influxDB查询出来的数据转为javaBean。
但是里面存在一个问题,就是当influxDB中的time格式为“2020-08-12T09:27:01.000000001+08:00”时,会发生转换失败。

故今天使用spring自带的BeanWrapperImpl来重写该工具类。

2 本工具类依赖:

		<dependency>
            <groupId>org.influxdbgroupId>
            <artifactId>influxdb-javaartifactId>
            <version>2.15version>
        dependency>

3 工具类

package cc.xxxx.utils;

import cc.wellcloud.cdr.configs.EnvConfig;
import cc.wellcloud.cdr.exception.CustomException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.*;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * influxdb工具类
 *
 * @author wangll
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InfluxDbUtil{

    @NonNull
    private InfluxDB influxDB;
    @NonNull
    private EnvConfig envConfig;

    /**
     * 查询
     *
     * @param command 查询语句
     * @param clazz javaBean
     * @return
     */
    public <T> List<T> query(String command,Class<T> clazz) throws CustomException {
        log.info("InfluxDbUtil query 开始 ---> command:{}",command);
        final List<T> list = new ArrayList<>();
        try {
            if (influxDB.ping() == null) {
                log.error("无法连接到influxDB");
                return list;
            }
            QueryResult query = influxDB.query(new Query(command,envConfig.getInfluxdbName()));
            for (QueryResult.Result result : query.getResults()) {
                List<QueryResult.Series> series = result.getSeries();
                if (series == null) {
                    continue;
                }
                for (QueryResult.Series serie : series) {
                    List<List<Object>> values = serie.getValues();
                    List<String> columns = serie.getColumns();
                    Map<String, String> tags = serie.getTags();
                    for (int i = 0; i < values.size(); ++i) {
                        T object = clazz.newInstance();
                        BeanWrapperImpl bean = new BeanWrapperImpl(object);
                        if (tags != null && tags.keySet().size() > 0) {
                            tags.forEach((k, v) -> bean.setPropertyValue(k,v));
                        }
                        for (int j = 0; j < columns.size(); ++j) {
                            String k = columns.get(j);
                            Object v = values.get(i).get(j);
                            if ("time".equals(k)){
                                //需要处理三种时间格式:2020-08-01T00:00:00+08:00      2020-08-06T00:00:00.800319164Z    2020-08-06T08:00:26.0906948+08:00
                                bean.setPropertyValue(k, StringUtils.substringBefore(StringUtils.substringBefore((String)v,"."),"+").replace("T", " "));
                            }else {
                                bean.setPropertyValue(k,v);
                            }
                        }
                        list.add(object);
                    }
                }
            }
        }catch (Exception e){
            log.error("InfluxDbUtil 查询influxDB时发生错误 {}",e);
            throw new CustomException("InfluxDbUtil 查询influxDB时发生错误", CustomException.ExceptionName.ILLEGAL_PARAM);
        }
        log.info("InfluxDbUtil query 结束,返回数据条数:{}",list.size());
        return list;
    }
}

PS:EnvConfig.java中就一个influxDB数据库名的参数,这里就不写了。

4 工具类的使用

package cc.xxxx.utils;

import cc.wellcloud.cdr.configs.EnvConfig;
import cc.wellcloud.cdr.exception.CustomException;
import org.influxdb.InfluxDB;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.List;

@RunWith(MockitoJUnitRunner.class)
public class InfluxDbUtilTest {

    @Mock
    private InfluxDB influxDB;
    @Mock
    private EnvConfig envConfig;
    @InjectMocks
    private InfluxDbUtil influxDbUtil;

    @Before
    public void setUp(){
        influxDbUtil = new InfluxDbUtil(influxDB,envConfig);
    }

    class Result {
        String time;
        Integer callTotals;
    }

    @Test
    public void query() throws CustomException {
        String command = "SELECT call_totals FROM db1.\"table_a\" WHERE time>'2020-07-27 09:00:12'  limit 1";
        List<Result> items = influxDbUtil.query(command, Result.class);
        System.out.println(items.get(0).time +"-----"+items.get(0).callTotals);
    }
}

你可能感兴趣的:(Java)