Develop a Spring Integration with Azure Storage Queue application using Visual Studio Code and Azure CLI authentication - hui1110/azure-sdk-for-java GitHub Wiki

Develop a Spring Integration with Azure Storage Queue application using Visual Studio Code and Azure CLI authentication

This blog describes how to develop a Spring Integration with Azure Storage Queue application using Visual Studio Code and Azure CLI authentication.

Introduction

What is Azure Storage Queue

Azure Queue Storage is a service for storing large numbers of messages. You access messages from anywhere in the world via authenticated calls using HTTP or HTTPS. A queue message can be up to 64 KB in size. A queue may contain millions of messages, up to the total capacity limit of a storage account. Queues are commonly used to create a backlog of work to process asynchronously.

What is an IDE and why Visual Studio Code

An integrated development environment or IDE is an application that facilitates the development of new applications. They are designed to cover all programming tasks in one place, providing a central interface with all the tools a developer needs, such as a code editor, compiler, debugger, or automation tools.

Since its release, Visual Studio Code (VSCode) has achieved tremendous growth in the developer community due to its multi-platform, multi-language, free, and open code. It is an extension that adds support for almost any programming language and turns it into a powerful IDE.

What You Need

In VSCode we will need to install the following extensions:

Provision Azure Resources

  1. See this article, create a storage account.

  2. Create a queue in the newly created storage account.

  3. Refer to this article to assign your Azure AD user, group, or service principal (application) the Storage Queue Data Contributor role.

Create a Spring Integration with Azure Storage Queue application with Spring Initializr

To create the initial structure of the Spring Boot project we will use Spring Initializr, which will generate a Spring base project with all the options we have selected.

We can also use Spring Initializr from VSCode, launching the command palette with Ctrl+Shift+P and executing the Spring Initializr command: Create a Maven Project...

img

NOTE: When we select both Azure Storage and Spring Integration, the starter spring-cloud-azure-starter-integration-storage-queue will be added to the pom.xml file.

We extract the zip file generated with Spring Initializr and open the folder from Visual Studio Code.

For this guide we will use Maven, Java 17, Spring Boot 2.7.5, Azure Storage, Spring Integration and Spring Web as dependencies.

Code the application

IMPORTANT: Before starting the following, See this article Authenticating with Azure CLI.

  1. Configure the following properties in application.yml:

    spring.cloud.azure.storage.queue.account-name=<your_storage_account_name>
  2. Write your Java code.

Controller code can refer to the following:

@RestController
public class SendController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendController.class);
    private static final String STORAGE_QUEUE_NAME ="<storage_queue_name>";
    private static final String OUTPUT_CHANNEL = "output";

    @Autowired
    StorageQueueOutboundGateway storageQueueOutboundGateway;
    
    @PostMapping("/messages")
    public String send(@RequestParam("message") String message) {
        storageQueueOutboundGateway.send(message);
        return message;
    }

    @Bean
    @ServiceActivator(inputChannel = OUTPUT_CHANNEL)
    public MessageHandler messageSender(StorageQueueTemplate storageQueueTemplate) {
        DefaultMessageHandler handler = new DefaultMessageHandler(STORAGE_QUEUE_NAME, storageQueueTemplate);
        handler.setSendCallback(new ListenableFutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                LOGGER.info("Message was sent successfully.");
            }

            @Override
            public void onFailure(Throwable ex) {
                LOGGER.info("There was an error sending the message.");
            }
        });
        return handler;
    }
    
    @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL)
    public interface StorageQueueOutboundGateway {
        void send(String text);
    }
}

The receiving message code can refer to the following:

@Service
public class ReceiveService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReceiveService.class);
    private static final String STORAGE_QUEUE_NAME = "<storage_queue_name>";
    private static final String INPUT_CHANNEL = "input";

    @Bean
    @InboundChannelAdapter(channel = INPUT_CHANNEL, poller = @Poller(fixedDelay = "1000"))
    public StorageQueueMessageSource storageQueueMessageSource(StorageQueueTemplate storageQueueTemplate) {
        return new StorageQueueMessageSource(STORAGE_QUEUE_NAME, storageQueueTemplate);
    }
    
    @ServiceActivator(inputChannel = INPUT_CHANNEL)
    public void messageReceiver(byte[] payload, @Header(AzureHeaders.CHECKPOINTER) Checkpointer checkpointer) {
        String message = new String(payload);
        LOGGER.info("New message received: '{}'", message);
        checkpointer.success()
            .doOnError(Throwable::printStackTrace)
            .doOnSuccess(t -> LOGGER.info("Message '{}' successfully checkpointed", message))
            .block();
    }
}

See storage-queue-integration-sample for more details.

Run and verify

Run the application using Maven

In your terminal, run mvn clean spring-boot:run to start the application.

Verify this application

  1. Send a POST request
 curl -X POST http://localhost:8080/messages?message=hello
  1. Verify in your app’s logs that similar messages were posted:
 New message received: 'hello'
 Message 'hello' successfully checkpointed

Conclusion

As we have seen, if the DefaultAzureCredential account has been authenticated via the Azure CLI az login command, then that account will be used for authentication.

DefaultAzureCredential is suitable for most scenarios where the application ends up running in the Azure cloud, it will authenticate through the following mechanisms in order.

img

The ChainedTokenCredential class provides the ability to chain together multiple credential instances so that they are tried sequentially when authenticating, as described here.

⚠️ **GitHub.com Fallback** ⚠️