pulsar启动后,默认的url为pulsar://localhost:6650
创建PulsarClient
String Pulsar_URL=“pulsar://localhost:6650”;
PulsarClient client = mkClient(Pulsar_URL);
其中mkClient函数如下:
private static PulsarClient mkClient(String URL) {
try {
PulsarClient client = PulsarClient.builder()
.serviceUrl(URL)
.build();
return client;
} catch (PulsarClientException e) {
e.printStackTrace();
}
return null;
}
private static void send(PulsarClient client) throws PulsarClientException {
Producer producer=client.newProducer(Schema.STRING)
.topic(“my-topic”)
.create();
Scanner input=new Scanner(System.in);
for (int i=0;i<100;i++) {
String str=input.next();
producer.send(str+i);
System.out.println(“消息已发送”);
}
}
private static void receive (PulsarClient client) throws PulsarClientException {
Consumer consumer = null;
consumer = client.newConsumer()
.topic(“my-topic”)
.subscriptionName(“my-subscription”)
.subscribe();
while (true){
Message msg= null;
try {
msg = consumer.receive();
System.out.println("Message received: " +new String(msg.getData()));
//确认消息,以便删除已经接受的消息
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
//消息处理失败,请稍后重新传递
consumer.negativeAcknowledge(msg);
}
}
}
结果如下:
//不阻塞主线程而是不断地监听新消息
private static void receive_1 (PulsarClient client) throws PulsarClientException {
MessageListener myMessageListener = (consumer, msg) -> {
try {
System.out.println("Message received: " + new String(msg.getData()));
consumer.acknowledge(msg);
} catch (Exception e) {
consumer.negativeAcknowledge(msg);
}
};
Consumer consumer = client.newConsumer()
.topic(“my-topic”)
.subscriptionName(“my-subscription”)
.messageListener(myMessageListener)
.subscribe();
}
//异步发送消息
private static void seend_asyn(PulsarClient client) throws PulsarClientException{
Producer<byte[]> producer=client.newProducer()
.topic(“my-topic”)
.create();
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
Scanner input=new Scanner(System.in);
for (int i=0;i<100;i++) {
String str=input.next();
producer.sendAsync(str.getBytes()).thenAccept(msgId -> {
System.out.println(“Message with ID " + msgId + str+” successfully sent");
});
}
}