Spring 启动禁用自动启动(com.microsoft.azure:azure servicebus spring boot starter)

jecbmhm3  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(436)

我有以下实现来使用spring boot应用程序从azure服务总线使用消息,但是我希望能够控制servicebusconsumer使用spring boot profile属性自动开始侦听主题
在application.yaml中类似这样的内容

servicebus.consumer.enable=false

它应该禁止servicebusconsumer侦听主题,并且我应该能够使用RESTAPI启动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;
    }
}
insrf1ej

insrf1ej1#

您可以创建 ServiceBusConsumer 通过添加 @ConditionalOnProperty 类似这样的注解,以确保仅在 servicebus.consumer.enabled=true :

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

相关问题