引言

说到分布式系统,消息中间件可以说是整个架构的“交通枢纽”——它让系统组件之间不再紧耦合,同时还能扛住高并发、保证数据不丢。在众多消息中间件里,Apache Pulsar 算是近几年很受关注的一个新面孔。它既继承了 Kafka 的高吞吐能力,又在存储和延迟上做了不少优化,逐渐成了不少企业级项目的首选。今天这篇文章,我们就来聊聊怎么在 Spring Boot 应用里把 Pulsar 集成进来,搭一套高性能的消息系统。

一、Apache Pulsar 简介

1.1 核心特性

1.2 架构组成

二、Spring Boot 集成 Apache Pulsar

2.1 添加依赖

集成第一步,先把依赖加进来。在 pom.xml 里引入 Pulsar 客户端和 Spring Boot Web 的依赖:


    org.apache.pulsar
    pulsar-client
    3.0.0


    org.springframework.boot
    spring-boot-starter-web

2.2 配置 Pulsar 连接

接下来,配置 Pulsar 的连接信息。在 application.yml 里写上服务地址:

spring:
  pulsar:
    client:
      service-url: pulsar://localhost:6650
    admin:
      service-url: http://localhost:8080

2.3 发送消息

直接上代码,创建一个消息发送服务。这里用 @PostConstruct@PreDestroy 来管理客户端和生产者生命周期,省心的做法:

import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;
import org.springframework.stereotype.Service;
import ja vax.annotation.PostConstruct;
import ja vax.annotation.PreDestroy;
import ja va.util.concurrent.CompletableFuture;
@Service
public class PulsarProducerService {
    private PulsarClient client;
    private Producer producer;
    @PostConstruct
    public void init() throws Exception {
        client = PulsarClient.builder()
                .serviceUrl("pulsar://localhost:6650")
                .build();
        producer = client.newProducer(Schema.STRING)
                .topic("persistent://public/default/my-topic")
                .create();
    }
    public void sendMessage(String message) throws Exception {
        producer.send(message);
    }
    public CompletableFuture sendAsyncMessage(String message) {
        return producer.sendAsync(message);
    }
    @PreDestroy
    public void close() throws Exception {
        if (producer != null) {
            producer.close();
        }
        if (client != null) {
            client.close();
        }
    }
}

2.4 消费消息

消费端同样简单,用 messageListener 处理消息,消费完记得确认:

import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.SubscriptionType;
import org.springframework.stereotype.Service;
import ja vax.annotation.PostConstruct;
import ja vax.annotation.PreDestroy;
import ja va.util.concurrent.TimeUnit;
@Service
public class PulsarConsumerService {
    private PulsarClient client;
    private Consumer consumer;
    @PostConstruct
    public void init() throws Exception {
        client = PulsarClient.builder()
                .serviceUrl("pulsar://localhost:6650")
                .build();
        consumer = client.newConsumer(Schema.STRING)
                .topic("persistent://public/default/my-topic")
                .subscriptionName("my-subscription")
                .subscriptionType(SubscriptionType.Exclusive)
                .messageListener((consumer, msg) -> {
                    try {
                        System.out.println("Received message: " + new String(msg.getData()));
                        consumer.acknowledge(msg);
                    } catch (Exception e) {
                        consumer.negativeAcknowledge(msg);
                    }
                })
                .subscribe();
    }
    @PreDestroy
    public void close() throws Exception {
        if (consumer != null) {
            consumer.close();
        }
        if (client != null) {
            client.close();
        }
    }
}

三、高级特性

3.1 消息分区

该说不说,消息分区是提高并行度的好手段。通过指定 key,Pulsar 会把消息路由到对应分区:

producer = client.newProducer(Schema.STRING)
        .topic("persistent://public/default/my-partitioned-topic")
        .create();
// 发送消息到指定分区
producer.newMessage()
        .value("Hello Pulsar")
        .key("key1") // 基于key分区
        .send();

3.2 消息批处理

想要提高吞吐量,批处理是个利器。把多条消息攒在一起发,网络开销少了很多:

producer = client.newProducer(Schema.STRING)
        .topic("persistent://public/default/my-topic")
        .batchingEnabled(true)
        .batchingMaxMessages(1000)
        .batchingMaxPublishDelay(10, TimeUnit.MILLISECONDS)
        .create();

3.3 事务支持

Pulsar 支持事务,这在需要保证消息原子性的时候特别有用。比如一次发送多条消息,要么全部成功,要么全部回滚:

// 开启事务
Transaction txn = client.newTransaction()
        .withTransactionTimeout(1, TimeUnit.MINUTES)
        .build()
        .get();
// 在事务中发送消息
producer.newMessage(txn)
        .value("Hello Transaction")
        .send();
// 提交事务
txn.commit().get();

3.4 死信队列

消息消费失败怎么办?死信队列就是个兜底方案。设置最大重试次数,超过次数就扔到死信主题里,方便后续排查:

consumer = client.newConsumer(Schema.STRING)
        .topic("persistent://public/default/my-topic")
        .subscriptionName("my-subscription")
        .deadLetterPolicy(DeadLetterPolicy.builder()
                .maxRedeliverCount(10)
                .deadLetterTopic("persistent://public/default/my-dlq")
                .build())
        .subscribe();

四、实践应用

4.1 订单处理系统

在订单处理场景里,Pulsar 可以很好地串联起各个服务:

  1. 订单创建时,把订单消息发到 Pulsar
  2. 订单处理服务消费消息,进行后续处理
  3. 处理结果再发到另一个主题,供下游服务使用

4.2 实时数据分析

实时数据分析是另一个典型场景。前端采集的用户行为数据通过 Pulsar 流入,流处理服务实时消费分析,结果写入数据库或缓存:

  1. 前端采集用户行为数据,发送到 Pulsar
  2. 流处理服务消费数据,进行实时分析
  3. 分析结果存储到数据库或缓存

五、性能优化

5.1 生产者优化

5.2 消费者优化

5.3 集群配置优化

六、常见问题与解决方案

问题原因解决方案
消息发送失败网络连接问题检查网络连接,配置重试机制
消息消费延迟消费者处理速度慢增加消费者数量,优化处理逻辑
系统吞吐量低配置不合理优化批处理设置,调整集群配置
消息丢失未正确处理确认确保消费后正确确认消息

七、总结

坦率说,Apache Pulsar 在消息中间件这个领域里,算是一个后起之秀。它把高吞吐、低延迟、持久化存储这些特性集于一身,特别适合用来构建高性能的分布式系统。通过 Spring Boot 和 Pulsar 的集成,我们可以快速搭建一套可靠的消息系统,满足各种业务场景的需求。

在实际项目中,关键是根据业务场景和系统需求,合理配置 Pulsar 的各项参数,把性能优化到位。同时,可观测性也不能忽视——及时发现和解决问题,才能保证系统稳定运行。

希望这篇文章能帮你更快地上手 Spring Boot 与 Pulsar 的集成。具体怎么用,还得看你的业务场景,灵活运用 Pulsar 的各种特性,才能构建出真正可靠、高效的消息系统。

本文转载于:https://www.jb51.net/program/362226vi9.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。