InfluxDB的批量插入个人理解有两种含义:1、一次性设定多条数据插入数据库;2、每次设置一条,满足一定条件之后(定时或者定量)插入数据库。
第二种属于异步,感觉很多朋友更需要那种实现,具体可以参考我的上篇文章InfluxDB Batch功能 定时定量发送请求。
这里要介绍的是第一种一次性插入多条数据,并且直接请求数据库写操作。
看代码:
定义BatchPoints的bean:
/**
* @author Created by pangkunkun on 2018/3/29.
*/
@SpringBootApplication
@EnableScheduling
public class InfluxApplication {
public static void main(String[] args) {
SpringApplication.run(InfluxApplication.class,args);
}
@Bean(value = "sdads")
public InfluxDB influxDB(){
InfluxDB influxDB = InfluxDBFactory.connect("http://10.10.20.154:8086");
influxDB.setDatabase("billingrecord")
.setRetentionPolicy("rp_90d")
.enableBatch(20,200, TimeUnit.MILLISECONDS);
return influxDB;
}
@Bean
public BatchPoints batchPoints(){
return BatchPoints.database("billingrecord")
.retentionPolicy("rp_90d")
.build();
}
}
使用
@Component
public class InfluxBatch implements CommandLineRunner{
@Autowired
BatchPoints batchPoints;
@Autowired
private InfluxDB influxDB;
@Override
public void run(String... args) throws Exception{
for (int i = 0; i< 10000; i++){
Thread.sleep(10);
Point point = Point.measurement("cpu22")
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.addField("num",1)
.tag("pkg",i+"")
.tag("statusCode","statusCode")
.build();
batchPoints.point(point);
}
influxDB.write(batchPoints);
}
}
这样influxDB.write的时候会把上面batchPoints里所有的数据都写入数据库。
如果想要异步的就去掉batchPoints,直接用influxDB.write(point),这样时间到了或者设定的数据量达到了就会执行一次写操作。