<!--引入maven--> <dependency> <groupId>org.influxdb</groupId> <artifactId>influxdb-java</artifactId> <version>2.15</version> </dependency>
/** * influxdb 鏈接配置類 */ @Configuration public class InfluxDbConfig { @Value("${spring.influx.url:''}") private String influxDBUrl; @Value("${spring.influx.user:''}") private String userName; @Value("${spring.influx.password:''}") private String password; @Value("${spring.influx.database:''}") private String database; @Value("${spring.influx.retentionPolicy:''}") private String retentionPolicy; public static String tabName; @Bean public InfluxDbUtils influxDbUtils() { return new InfluxDbUtils(userName, password, influxDBUrl, database, retentionPolicy); } @Value("${spring.influx.tabName:''}") public void setTabName(String tabName) { InfluxDbConfig.tabName = tabName; } }
/** * 操做工具類 */ @Data @Slf4j public class InfluxDbUtils { private String userName; private String password; private String url; public String database; public String tabName; // 保留策略 private String retentionPolicy; // InfluxDB實例 private InfluxDB influxDB; /** * @param userName 數據庫用戶名 * @param password 數據庫密碼 * @param url 數據庫鏈接 * @param database 數據庫名稱 * @param retentionPolicy 保留策略,默認autogen策略(數據保留7天,SHOW RETENTION POLICIES ON database) */ public InfluxDbUtils(String userName, String password, String url, String database, String retentionPolicy) { this.userName = userName; this.password = password; this.url = url; this.database = database; this.retentionPolicy = StringUtils.isBlank(retentionPolicy) ? "autogen" : retentionPolicy; this.influxDB = influxDbBuild(); } /** * 鏈接數據庫 ,若不存在則建立 * * @return influxDb實例 */ private InfluxDB influxDbBuild() { if (influxDB == null) { influxDB = InfluxDBFactory.connect(url, userName, password); } try { createDB(database); influxDB.setDatabase(database); } catch (Exception e) { log.error("create influx db failed, error: {}", e.getMessage()); } finally { influxDB.setRetentionPolicy(retentionPolicy); } influxDB.setLogLevel(InfluxDB.LogLevel.BASIC); return influxDB; } /**** * 建立數據庫 * @param database */ private void createDB(String database) { influxDB.query(new Query("CREATE DATABASE " + database)); }
//具體使用方法 InfluxDbUtils influxDbUtils = SpringUtil.getBean(InfluxDbUtils.class); influxDB = influxDbUtils.getInfluxDB(); Point.Builder point = Point.measurement(InfluxDbConfig.tabName); point.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS); point.tag("code",""); point.addField("name",""); influxDB.write(point.build());