com.aliyun.datahub.client.example.examples.CursorExample Maven / Gradle / Ivy
The newest version!
package com.aliyun.datahub.client.example.examples;
import com.aliyun.datahub.client.DatahubClient;
import com.aliyun.datahub.client.DatahubClientBuilder;
import com.aliyun.datahub.client.auth.AliyunAccount;
import com.aliyun.datahub.client.common.DatahubConfig;
import com.aliyun.datahub.client.exception.*;
import com.aliyun.datahub.client.model.CursorType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CursorExample {
private static DatahubClient datahubClient;
public static void init() {
// 创建DataHubClient实例
datahubClient = DatahubClientBuilder.newBuilder()
.setDatahubConfig(
new DatahubConfig(Constant.endpoint,
new AliyunAccount(Constant.accessId, Constant.accessKey)))
.build();
}
public static void getCursor() {
String shardId = "0";
try {
/* OLDEST用法示例 */
String oldestCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.OLDEST).getCursor();
/* LATEST用法示例 */
String latestCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.LATEST).getCursor();
/* SEQUENCE用法示例 */
//获取最新数据的sequence
long seq = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.LATEST).getSequence();
//获取最新的十条数据的读取位置
String seqCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.SEQUENCE, seq - 9).getCursor();
/* SYSTEM_TIME用法示例 */
//将时间转为时间戳形式
String time = "2019-07-01 09:00:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(time);
long timestamp = date.getTime();
//获取时间time之后的数据读取位置
String timeCursor = datahubClient.getCursor(Constant.projectName, Constant.topicName, shardId, CursorType.SYSTEM_TIME, timestamp).getCursor();
System.out.println("get cursor successful");
} catch (InvalidParameterException e) {
// invalid parameter, please check your parameter
e.printStackTrace();
throw e;
} catch (AuthorizationFailureException e) {
// AK error, please check your accessId and accessKey
e.printStackTrace();
throw e;
} catch (ResourceNotFoundException e) {
// project or topic not found
e.printStackTrace();
throw e;
} catch (SeekOutOfRangeException e){
// offset invalid ,may be offset has expired
e.printStackTrace();
throw e;
} catch (DatahubClientException e) {
// other error
e.printStackTrace();
throw e;
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[]args){
}
}