pulsar: 批量接收消息

接收消息时,和kafka类似,如果topic有多个分区,则只能保证分区内数据的接收有序,不能保证全局有序。

一、发送消息

package cn.edu.tju.test1;



import org.apache.pulsar.client.api.*;

public class BatchProducer01 {
    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();
        for(int i = 0; i < 97; i ++){
            stringProducer.send("this is a good book." + i);
        }
        stringProducer.close();
        client.close();
    }
}

二、批量接收消息

package cn.edu.tju.test1;



import org.apache.pulsar.client.api.*;

public class BatchConsumer01 {

    private static String SERVER_4 = "xx.xx.xx.xx";

    public static void main(String[] args) throws Exception{
        BatchReceivePolicy batchReceivePolicy = new BatchReceivePolicy.Builder()
                .maxNumMessages(5).build();
        PulsarClient client = PulsarClient.builder()
                .serviceUrl("pulsar://"  + SERVER_4 + ":6650")
                .build();

        Consumer<String> consumer = client.newConsumer(Schema.STRING)
                .batchReceivePolicy(batchReceivePolicy)
                .subscriptionName("my-sub")
                .topic("my-topic")
                .subscribe();

        while (true){
            Messages<String> messages = consumer.batchReceive();
            System.out.println(messages.size());
            for(Message msg : messages){
                System.out.println(msg.getValue());
            }
        }


    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值