influxdb

zrx001發表於2024-05-28

InfluxDB

  1. influxdb 時序性資料庫
    時序資料是描述一個實體在不同時間所處的不同狀態。一般用於指標監控場景。

  2. influxdb連線

    @Component
    @ConfigurationProperties(prefix = "influxdb")
    public class InfluxDBInfoStatic {
    	private static String url;
    	private static String port;
    	private static String database;
    	private static String measurement;
    	private static String user;
    	private static String password;
    	private static String retentionPolicy="hour";
    	//okhttpclient連線池最大空閒數量
    	private static Integer idleConnectionCount=100;
    	//okhttpclient連線池最大空閒保持時間
    	private static Integer keepAliveDuration=10;
    }
    @Slf4j
    public class InfluxDBConnectionUtil {
    	private static final InfluxDB INFLUXDB;
    	private final static ConnectionPool connectionPool=new ConnectionPool(InfluxDBInfoStatic.getIdleConnectionCount(),InfluxDBInfoStatic.getKeepAliveDuration(), TimeUnit.SECONDS);
    	static{
    		OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient().newBuilder()
    				.connectTimeout(30, TimeUnit.SECONDS)
    				.writeTimeout(30, TimeUnit.SECONDS)
    				.retryOnConnectionFailure(true)
    				.readTimeout(30, TimeUnit.SECONDS);
    		okHttpClientBuilder.connectionPool(connectionPool);
    		INFLUXDB = InfluxDBFactory.connect(
    				"http://" + InfluxDBInfoStatic.getUrl() + ":" + InfluxDBInfoStatic.getPort()
    				, InfluxDBInfoStatic.getUser(), InfluxDBInfoStatic.getPassword(),okHttpClientBuilder);
    	} 
        /**
         * 獲取物件控制代碼
         */
        public static InfluxDBConnectionUtil getInstance() {
            return SingletonInstance.INSTANCE;
        }
      
    	/**
    	 * 建立自定義保留策略 policyName-策略名;days-儲存天數;replication-儲存副本數量;isDefault-是否設為預設保留策略          
    	 */
    	public void createRetentionPolicy(String dataBaseName, String policyName, int days, int replication, Boolean isDefault) {
    		String sql = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %sd REPLICATION %s ", policyName, dataBaseName, days, replication);
    		if (isDefault) {
    			sql = sql + " DEFAULT";
    		}
    		query(sql);
    	}
    
    	/**
    	 * 建立預設的保留策略 策略名:hour,儲存天數:30天,儲存副本數量:1,設為預設保留策略
    	 * 
    	 */
    	public void createDefaultRetentionPolicy() {
    		String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s DEFAULT", "hour", InfluxDBInfoStatic.getDatabase(), "30d", 1);
    		this.query(command);
    	}
    
    	/**
    	 * 查詢 
    	 */
    	public QueryResult query(String command) {
    		return INFLUXDB.query(new Query(command, InfluxDBInfoStatic.getDatabase()));
    	}
    
    	/**
    	 * 插入 measurement-表;tags-標籤;fields-欄位
    	 */
    	public void insert(String measurement, Map<String, String> tags, Map<String, Object> fields, long time, TimeUnit timeUnit) {
    		Builder builder = Point.measurement(measurement);
    		builder.tag(tags);
    		builder.fields(fields);
    		if (0 != time) {
    			builder.time(time, timeUnit);
    		}
    		INFLUXDB.write(InfluxDBInfoStatic.getDatabase(), InfluxDBInfoStatic.getRetentionPolicy() == null || InfluxDBInfoStatic.getRetentionPolicy().equals("") ? "autogen" : InfluxDBInfoStatic.getRetentionPolicy(), builder.build());
    	} 
    	public static void main(String[] args) {
    		QueryResult results = InfluxDBConnectionUtil.getInstance()
    				.query("select time, application, avg, count, countError, max, min, \"pct90.0\", \"pct95.0\", \"pct99.0\", rb, sb, transaction from jmeter where application = '16'");
    		QueryResult.Result oneResult = results.getResults().get(0);
    		if (oneResult.getSeries() != null) {
    			List<List<Object>> valueList = oneResult.getSeries().stream().map(QueryResult.Series::getValues).collect(Collectors.toList()).get(0);
    			if (valueList != null && valueList.size() > 0) {
    				System.out.println("valueList ===> " + JSONUtil.toJsonStr(valueList));
    				for (List<Object> value : valueList) {
    					System.out.println("value ===> " + JSONUtil.toJsonStr(value)); 
    				}
    			}
    		}
    	}
    }
    

相關文章