问题
同步influxdb有些数据没有,不知道啥原因,后来百度发现时间需要唯一,毫秒还会重复,只能采用纳秒处理了
java实现
TimeStampUtils.java
package com.wujialiang;
/**
* 获取纳秒值的工具类
*/
public class TimeStampUtils {
/**
* 递增数初始值
*/
private static long randomNum = 1L;
/**
* 递增数最大值,可根据并发情况适当调整
*/
private static final long RANDOM_NUM_MAX = 999L;
public static long getTimeStamp() {
long curRandomNum;
synchronized (TimeStampUtils.class) {
if (randomNum > RANDOM_NUM_MAX) {
randomNum = 1;
}
curRandomNum = randomNum++;
}
return System.currentTimeMillis() * 1000000L + System.nanoTime() % 1000000L + curRandomNum;
}
}
测试
public static void main( String[] args )
{
for (int i = 0; i < 100; i++) {
System.out.println(TimeStampUtils.getTimeStamp());
}
}
C#实现
NanoHelper.cs
using System.Diagnostics;
namespace InfluxdbStu01;
public class NanoHelper
{
private static readonly object lockObj = new object();
/// <summary>
/// 递增数初始值
/// </summary>
private static long randomNum = 1L;
/// <summary>
/// 递增数最大值,可根据并发情况适当调整
/// </summary>
private const long RANDOM_NUM_MAX = 999L;
/// <summary>
/// 返回纳秒
/// </summary>
/// <returns>返回的结果是纳秒</returns>
public static long getTimeStamp()
{
long curRandomNum;
lock (lockObj)
{
if (randomNum > RANDOM_NUM_MAX)
{
randomNum = 1;
}
curRandomNum = randomNum++;
}
long nanoPart = Stopwatch.GetTimestamp(); // 计时器刻度(不是纳秒)
long nowTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
/*
皮秒 纳秒 微秒 毫秒 秒 ps、ns、us、ms、s 时间单位之间的换算
1,000,000,000,000皮秒=1秒 (12个0)ps -> s
1,000,000,000纳秒=1秒 (9个0) ns -> s
1,000,000微秒=1秒 (6个0)us -> s
1,000毫秒=1秒 (3个0) ms -> s
*/
return nowTimestamp* 1000000L
+ nanoPart % 1000000L + curRandomNum;
}
}
测试
NanoHelper.getTimeStamp()
参考
https://blog.csdn.net/hahawangzi520/article/details/134846374