Allanh
Allanh

Reputation: 507

How to listen a queue all the time in azure service bus and intercept each message

I have a ServiceBus in azure with two queues: The first one is where the client send messages(I need to intercept the messages. QUEUE_IN) and the second one is the queue where the client receive the messages I sent when I finish to process the messages in the first one(QUEUE_OUT).

I need to listen all the time the QUEUE_IN and when they sent a message process it and sent a message to the QUEUE_OUT with the result.

The problem I have is that I'm not able to intercept the messages in the QUEUE_IN, when I run the program I know there are messages in the queue but the program is not able to see them.

private void recibirMensaje() throws Exception {   
        QueueClient queueIn= new QueueClient(new ConnectionStringBuilder(stringConection, nameQueue),
                ReceiveMode.PEEKLOCK);
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        this.interceptMessage(queueIn, executorService);
        recibirMensajeCliente.close();
        executorService.shutdown();

    }

private void interceptMessage(QueueClient queueIn, ExecutorService executorService) throws Exception {
        queueIn.registerMessageHandler(new IMessageHandler() {
            public CompletableFuture<Void> onMessageAsync(IMessage message) {
                if (message.getLabel() != null && message.getContentType() != null
                        && message.getLabel().contentEquals(etiquetaMensajes)
                        && message.getContentType().contentEquals("application/json")) {

                    byte[] body = message.getBody();
                    logger.info("Printing message{}", body);

                }
                return CompletableFuture.completedFuture(null);
            }

            public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
            }
        },
                // 1 concurrent call, messages are auto-completed, auto-renew duration
                new MessageHandlerOptions(1, true, Duration.ofMinutes(1)), executorService);


    }

I don't post the send method because I have not problema with it. I don't know how to listen all the time the queue_in and process the messages or how to know if the queue has messages to be processed and how to intercept it.

Upvotes: 2

Views: 1958

Answers (1)

Thiago Custodio
Thiago Custodio

Reputation: 18387

You'd better use Azure Functions which has native support to Service Bus Queues. It will listen to your queue and also will inject the message content for you. After that, you can use output bindings to notify consumers when the job is done.

more information: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus?tabs=java

Upvotes: 1

Related Questions