pulsar java IO生产消费消息,java栈和堆面试

创建client 连接


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");

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值