gpt4 book ai didi

spring - Azure 服务总线 - Spring Boot 禁用自动启动 (com.microsoft.azure : azure-servicebus-spring-boot-starter)

转载 作者:行者123 更新时间:2023-12-04 08:07:10 25 4
gpt4 key购买 nike

我有以下实现来使用 Spring Boot 应用程序使用来自 Azure 服务总线的消息,但是我希望能够使用 Spring boot 配置文件属性控制 ServiceBusConsumer 自动开始监听主题

application.yaml 中类似的内容

 servicebus.consumer.enable=false

它应该禁止 ServiceBusConsumer 监听主题,并且我应该能够使用 REST API 启动 ServiceBusConsumer - 例如:./api/servicebus/consumer/start?

import com.microsoft.azure.servicebus.ExceptionPhase;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.IMessageHandler;
import com.microsoft.azure.servicebus.ISubscriptionClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Log4j2
@Component
class ServiceBusConsumer implements Ordered {

private final ISubscriptionClient iSubscriptionClient;

ServiceBusConsumer(ISubscriptionClient isc) {
this.iSubscriptionClient = isc;
}

@EventListener(ApplicationReadyEvent.class)
public void consume() throws Exception {

this.iSubscriptionClient.registerMessageHandler(new IMessageHandler() {

@Override
public CompletableFuture<Void> onMessageAsync(IMessage message) {
log.info("received message " + new String(message.getBody()) + " with body ID " + message.getMessageId());
return CompletableFuture.completedFuture(null);
}

@Override
public void notifyException(Throwable exception, ExceptionPhase phase) {
log.error("eeks!", exception);
}
});

}

@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}

最佳答案

您可以通过添加 @ConditionalOnProperty 注释来有条件地创建 ServiceBusConsumer bean,以确保仅在 servicebus.consumer.enabled 时创建该 bean =true:

@Log4j2
@Component
@ConditionalOnProperty(prefix = "servicebus.consumer", name = "enabled")
class ServiceBusConsumer implements Ordered {
...
}

关于spring - Azure 服务总线 - Spring Boot 禁用自动启动 (com.microsoft.azure : azure-servicebus-spring-boot-starter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66168872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com