本文主要是介绍pulsar: 生产者同步发送消息和异步发送消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、同步发送
package cn.edu.tju.test1;import org.apache.pulsar.client.api.*;public class BasicProducer01 {private static String SERVER_4 = "xx.xx.xx.xx";public static void main(String[] args) throws PulsarClientException {PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://" + SERVER_4 + ":6650").build();Producer<String> stringProducer = client.newProducer(Schema.STRING).topic("my-topic").create();stringProducer.send("this is a book.");stringProducer.close();client.close();}
}
二、异步发送
package cn.edu.tju.test1;import org.apache.pulsar.client.api.*;import java.util.function.BiConsumer;public class BasicProducer02 {private static String SERVER_4 = "xx.xx.xx.xx";public static void main(String[] args) throws PulsarClientException {PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://" + SERVER_4 + ":6650").build();Producer<String> stringProducer = client.newProducer(Schema.STRING).topic("my-topic").create();stringProducer.sendAsync("this is a book").whenComplete(new BiConsumer<MessageId, Throwable>() {@Overridepublic void accept(MessageId messageId, Throwable throwable) {System.out.println("消息发送成功,id 为: " + messageId);try {client.close();System.out.println("close client......");} catch (Exception ex){System.out.println(ex.getMessage());}}});}
}
这篇关于pulsar: 生产者同步发送消息和异步发送消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!