Redis Time Series 数据结构详解与Java实现
import redis.clients.jedis.Jedis;
import redis.clients.jedis.timeseries.TSCreateParams;
import redis.clients.jedis.timeseries.TSInfo;
import redis.clients.jedis.timeseries.TSKeyedElements;
import redis.clients.jedis.timeseries.TSRangeElements;
import redis.clients.jedis.timeseries.TSRangeParams;
import java.util.List;
public class TimeSeriesExample {
private static final String TS_KEY = "sensor:temperature";
public static void main(String[] args) {
// 连接到本地的Redis服务器
Jedis jedis = new Jedis("localhost");
// 创建时间序列
jedis.tsCreate(TS_KEY, TSCreateParams.createParams());
// 插入时间序列数据
jedis.tsAdd(TS_KEY, System.currentTimeMillis(), 22.5);
jedis.tsAdd(TS_KEY, System.currentTimeMillis() + 1000, 23.0);
jedis.tsAdd(TS_KEY, System.currentTimeMillis() + 2000, 22.8);
// 查询时间序列数据
long startTime = System.currentTimeMillis() - 5000;
long endTime = System.currentTimeMillis() + 5000;
List<TSRangeElements> range = jedis.tsRange(TS_KEY, startTime, endTime, TSRangeParams.rangeParams());
System.out.println("Time Series Data:");
for (TSRangeElements element : range) {
System.out.println("Timestamp: " + element.getTimestamp() + ", Value: " + element.getValue());
}
// 获取时间序列信息
TSInfo info = jedis.tsInfo(TS_KEY);
System.out.println("Time Series Info: " + info);
// 关闭连接
jedis.close();
}
}