使用 reader 接口, Pulsar客户可以在主题中“手动定位”自己,从指定的消息开始向前读取所有消息
下面是一个示例:
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Reader;
import org.apache.pulsar.client.impl.schema.JSONSchema;
public class ReaderTest{
public static void main(String[] args) {
String url = "http://192.168.1.48:8080";
try{
PulsarClient client =PulsarClient.builder()
.serviceUrl(url)
.build();
Reader<UserModel> reader=client.newReader(JSONSchema.of(UserModel.class))
.topic("my-tenant/my-namespace/testschema-topic")
.startMessageId(MessageId.earliest) //MessageId.earliest最早 MessageId.latest 最新 MessageId断点
.create();
while (true) {
Message<UserModel> userModelmsg = reader.readNext();
UserModel userModel=userModelmsg.getValue();//业务数据
MessageId messageId=userModelmsg.getMessageId();//断点
System.out.println("receive message: " +userModel.getName()+"="+userModel.getAge()+"="+messageId.toString());
}
}catch(Exception e){
e.printStackTrace();
}
}
}
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/183934.html