一、导入pulsar依赖
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.9.2</version>
</dependency>
二、pulsar配置(示例为yml文件)
pulsar:
url: pulsar://192.168.0.1:30000
topic: topic1,topic2
subscription: topicGroup
三、生产者示例代码
@Component
public class TestPulsarProducer {
private static final Logger log = LoggerFactory.getLogger(TestPulsarProducer.class);
@Value("${pulsar.url}")
private String url;
@Value("${pulsar.topic}")
private String topic;
PulsarClient client = null;
Producer<byte[]> producer = null;
@PostConstruct
public void initPulsar() throws Exception{
client = PulsarClient.builder()
.serviceUrl(url)
.build();
producer = client.newProducer()
.topic(topic.split(",")[0])
.enableBatching(true)
.compressionType(CompressionType.LZ4)
.batchingMaxPublishDelay(10, TimeUnit.MILLISECONDS)
.sendTimeout(0, TimeUnit.SECONDS)
.batchingMaxMessages(1000)
.maxPendingMessages(1000)
.blockIfQueueFull(true)
.roundRobinRouterBatchingPartitionSwitchFrequency(10)
.batcherBuilder(BatcherBuilder.DEFAULT)
.create();
}
public void sendMsg(String key, String data){
CompletableFuture<MessageId> future = producer.newMessage()
.key(key)
.value(data.getBytes()).sendAsync();
future.handle((v, ex) -> {
if (ex == null) {
log.info("Message persisted2: {}", data);
} else {
log.error("发送Pulsar消息失败msg:【{}】 ", data, ex);
}
return null;
});
log.info("Message persisted: {}", data);
}
}
四、消费者代码
@Component
public class AlarmPulsarConsumer {
private static final Logger log = LoggerFactory.getLogger(AlarmPulsarConsumer.class);
@Value("${pulsar.url}")
private String url;
@Value("${pulsar.topic}")
private String topic;
@Value("${pulsar.subscription}")
private String subscription;
private PulsarClient client = null;
private Consumer consumer = null;
@PostConstruct
public void initPulsar() throws Exception{
try{
client = PulsarClient.builder()
.serviceUrl(url)
.build();
consumer = client.newConsumer()
.topic(topic.split(","))
.subscriptionName(subscription)
.subscriptionType(SubscriptionType.Shared)
.subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
.negativeAckRedeliveryDelay(60, TimeUnit.SECONDS)
.subscribe();
new Thread(()->{
AlarmPulsarConsumer alarmPulsarConsumer = SpringUtils.getBean(AlarmPulsarConsumer.class);
try{
alarmPulsarConsumer.start();
}catch(Exception e){
log.error("消费Pulsar数据异常,停止Pulsar连接:", e);
alarmPulsarConsumer.close();
}
}).start();
}catch(Exception e){
log.error("Pulsar初始化异常:",e);
throw e;
}
}
private void start() throws Exception{
while (true) {
Message message = consumer.receive();
String[] keyArr = message.getKey().split("_");
String jsons = new String(message.getData());
if (StringUtils.isNotEmpty(json)) {
try{
wsSend(type, strategyId, camId, camTime, json,depId,alarmType,target);
}catch(Exception e){
log.error("消费Pulsar数据异常,key【{}】,json【{}】:", message.getKey(), json, e);
}
}
consumer.acknowledge(message);
}
}
public void wsSend(Integer type, Integer strategyId, String camId, Long camTime, String json,Long depId,Integer alarmType,Integer target) {
}
public void close(){
try {
consumer.close();
} catch (PulsarClientException e) {
log.error("关闭Pulsar消费者失败:",e);
}
try {
client.close();
} catch (PulsarClientException e) {
log.error("关闭Pulsar连接失败:",e);
}
}
}