我有一个 java 应用程序,它将测量结果发送到 influxDB 数据库。
我正在我的 influxdb 数据库中添加点。 我每次程序运行时添加的点都有当前时间戳。
这就是我添加积分的方式(测量构建):
BatchPoints batchPoints;
Date date = new Date();
String beginofday = Constant.simpledateFormat.format(date);
date = Constant.simpledateFormat.parse(beginofday);
long timestamp = date.getTime();
//adding points
for buildings ... do
Point point = Point.measurement("building").tag(tagsToAdd).fields(fieldsToAdd)
.time(timestamp, TimeUnit.NANOSECONDS).build();
batchPoints.point(point);
我的问题是,当我用这样的请求请求我的数据库时:
select count(tag) from building where time > (my timestamp)
我注意到以前的时间戳结果也被计算在内,即使我正在做 time>timestamp。 当我执行 > 而不是 >= 时,它只计算最后一个。 我还注意到,对于前一个时间戳,例如,如果我有像这样的时间戳 1540300800000 ns,influxdb 在开头添加 6,它就会变成 61540300800000 ms。
我真的不明白发生了什么。
有什么想法吗?
最佳答案
java.time
ZoneId zone = ZoneId.systemDefault();
Instant beginofday = LocalDate.now(zone).atStartOfDay(zone).toInstant();
long timestamp = beginofday.toEpochMilli();
//adding points
for buildings ... do
Point point = Point.measurement("building").tag(tagsToAdd).fields(fieldsToAdd)
.time(timestamp, TimeUnit.MILLISECONDS).build();
我正在使用 java.time,现代 Java 日期和时间 API。
你的代码出了什么问题
虽然我没有重现和测试,但我相信您混淆了毫秒、10^-3秒和纳秒、10^-9秒。 date.getTime()
为您提供自纪元以来的毫秒数,但您在 time(timestamp, TimeUnit.NANOSECONDS)
中传递该数字。如果我以我所在时区 (CET) 的今天(2 月 21 日)开始,并使用自纪元以来的毫秒数作为纳秒,我会得到 1970-01-01T00:25:50.703600Z
。所以我假设你在那个时间点之后得到了一切。
其他要点:
- 您使用的
Date
和SimpleDateFormat
类设计不佳且早已过时,因此我建议您避免使用它们。现代 java.time 更适合使用。 - 将日期时间格式化为日期字符串并将其解析回来是查找一天的开始的绕道。
链接
Oracle tutorial: Date Time解释如何使用 java.time。
关于java - InfluxDB'请求选择其中时间>时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791266/