主题解析

在生成或使用消息时,需要目标主题。 框架会查找以下有序位置以确定主题(在第一次查找时停止):spring-doc.cadn.net.cn

当通过默认机制之一找到主题时,无需在 produce 或 consume API 上指定主题。spring-doc.cadn.net.cn

当找不到主题时,API 将相应地引发异常。spring-doc.cadn.net.cn

1. 用户指定

传递到正在使用的 API 中的主题具有最高优先级(例如。PulsarTemplate.send("my-topic", myMessage)@PulsarListener(topics = "my-topic").spring-doc.cadn.net.cn

2. 消息类型默认

当没有主题传递到 API 中时,系统会查找为正在生成或使用的消息类型配置的消息类型到主题映射。spring-doc.cadn.net.cn

映射可以使用spring.pulsar.defaults.type-mappings财产。 以下示例使用application.yml配置在消费或生成时使用的默认主题FooBar消息:spring-doc.cadn.net.cn

spring:
  pulsar:
    defaults:
      type-mappings:
        - message-type: com.acme.Foo
          topic-name: foo-topic
        - message-type: com.acme.Bar
          topic-name: bar-topic
message-type是 Message 类的完全限定名称。
如果消息(或Publisherinput) 为null,框架将无法从中确定主题。如果您的应用程序可能会发送null消息。

2.1. 通过 annotation 指定

当没有主题传递到 API 中,并且没有配置自定义主题映射时,系统会查找@PulsarMessage对正在生成或使用的消息的类的注释。 默认主题可以通过topic属性。spring-doc.cadn.net.cn

以下示例配置在生成或使用Foo:spring-doc.cadn.net.cn

@PulsarMessage(topic = "foo-topic")
record Foo(String value) {
}

属性占位符和 SPEL 表达式在@PulsarMessage注解 例如:spring-doc.cadn.net.cn

@PulsarMessage(topic = "${app.topics.foo}")
record Foo(String value) {
}

@PulsarMessage(topic = "#{someBean.getTopic()}")
record Bar(String value) {
}

2.2. 自定义主题解析器

添加映射的首选方法是通过上述属性。 但是,如果需要更多控制,您可以通过证明自己的实现来替换默认解析器,例如:spring-doc.cadn.net.cn

@Bean
public MyTopicResolver topicResolver() {
	return new MyTopicResolver();
}

3. 生产者全局默认值

最终查询的位置(生产时)是系统范围的生产者默认主题。 它是通过spring.pulsar.producer.topic-name属性,并且spring.pulsar.reactive.sender.topic-name属性。spring-doc.cadn.net.cn

4. Consumer 全局默认值

查询的最后一个位置(使用时)是系统范围的使用者默认主题。 它是通过spring.pulsar.consumer.topicsspring.pulsar.consumer.topics-pattern属性,以及spring.pulsar.reactive.consumer.topicsspring.pulsar.reactive.consumer.topics-pattern属性。spring-doc.cadn.net.cn