Skip to content

Latest commit

 

History

History
184 lines (129 loc) · 6.08 KB

File metadata and controls

184 lines (129 loc) · 6.08 KB

06 - Build a reactive Spring Boot microservice using Cosmos DB

This guide is part of the Azure Spring Cloud training

Build a reactive Spring Boot microservice that uses the Spring reactive stack and is bound to a Cosmos DB database in order to access a globally-distributed database with optimum performance.


Prepare the Cosmos DB database

From Section 00, you should already have a CosmosDB account named sclabc-<unique string>.

  • Click on the "Data Explorer" menu item
    • Expand the container named azure-spring-cloud-cosmosdb.

    • In that container, expand the container named City.

    • Click on "Items" and use the "New Item" button to create some sample items:

      {
          "name": "Paris, France"
      }
      {
          "name": "London, UK"
      }

Data explorer

Create a Spring Webflux microservice

The microservice that we create in this guide is available here.

To create our microservice, we will use https://start.spring.io/ with the command line:

curl https://start.spring.io/starter.tgz -d dependencies=webflux,cloud-eureka,cloud-config-client -d baseDir=city-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -

We use the Spring Webflux, Eureka Discovery Client and the Config Client Spring Boot starters.

Add the Cosmos DB API

In the application's pom.xml file, add the Cosmos DB dependency just after the spring-cloud-starter-netflix-eureka-client dependency:

        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-cosmos</artifactId>
            <version>4.5.0</version>
        </dependency>

Add Spring reactive code to get the data from the database

Next to the DemoApplication class, create a City domain object:

package com.example.demo;

class City {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Then, in the same location, create a new CityController class that will be used to query the database.

This class will get its Cosmos DB configuration from the Azure Spring Cloud service binding that we will configure later.

package com.example.demo;

import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.FeedResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.annotation.PostConstruct;
import java.util.List;

@RestController
public class CityController {

    @Value("${azure.cosmosdb.uri}")
    private String cosmosDbUrl;

    @Value("${azure.cosmosdb.key}")
    private String cosmosDbKey;

    @Value("${azure.cosmosdb.database}")
    private String cosmosDbDatabase;

    private CosmosAsyncContainer container;

    @PostConstruct
    public void init() {
        container = new CosmosClientBuilder()
                .endpoint(cosmosDbUrl)
                .key(cosmosDbKey)
                .buildAsyncClient()
                .getDatabase(cosmosDbDatabase)
                .getContainer("City");
    }

    @GetMapping("/cities")
    public Flux<List<City>> getCities() {
        CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
        return container.queryItems("SELECT TOP 20 * FROM City c", options, City.class)
                .byPage()
                .map(FeedResponse::getResults);
    }
}

Create the application on Azure Spring Cloud

As in 02 - Build a simple Spring Boot microservice, create a specific city-service application in your Azure Spring Cloud instance:

az spring-cloud app create -n city-service

Bind the Cosmos DB database to the application

Azure Spring Cloud can automatically bind the Cosmos DB database we created to our microservice.

  • Go to "Apps" in your Azure Spring Cloud instance.
  • Select the city-service application
  • Go to Service bindings
  • Click on `Create service binding``
    • Give your binding a name, for example cosmosdb-city
    • Select the Cosmos DB account and database we created and keep the default sql API type
    • In the drop-down list, select the primary master key
    • Click on Create to create the database binding

Bind Cosmos DB database

Deploy the application

You can now build your "city-service" project and send it to Azure Spring Cloud:

cd city-service
./mvnw clean package -DskipTests
az spring-cloud app deploy -n city-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..

Test the project in the cloud

  • Go to "Apps" in your Azure Spring Cloud instance.
    • Verify that city-service has a Discovery status which says UP(1),DOWN(0). This shows that it is correctly registered in Spring Cloud Service Registry.
    • Select city-service to have more information on the microservice.
  • Copy/paste the "Test Endpoint" that is provided.

You can now use cURL to test the /cities endpoint, and it should give you the list of cities you created. For example, if you only created Paris, France and London, UK like it is shown in this guide, you should get:

[[{"name":"Paris, France"},{"name":"London, UK"}]]

If you need to check your code, the final project is available in the "city-service" folder.


⬅️ Previous guide: 05 - Build a Spring Boot microservice using Spring Cloud features

➡️ Next guide: 07 - Build a Spring Boot microservice using MySQL