This topic provides an example on how to develop and debug Spring Cloud applications that are used as a provider and a consumer respectively in an on-premises environment, deploy the applications on Serverless App Engine (SAE), and perform service registration and discovery. This topic also describes the process in which the consumer calls the provider.

Background information

  • If you are not familiar with Spring Cloud and only have basic knowledge about Spring and Maven, this topic guides you through the process of registering and discovering services for Spring Cloud applications, and calling providers as a consumer through Spring Cloud Alibaba Nacos Discovery.
  • If you are familiar with service registries in Spring Cloud such as Eureka, Consul, and ZooKeeper, but you have not used the registry Nacos Discovery of Spring Cloud Alibaba, you only need to replace the dependencies and configurations of the service registries with the dependencies and configurations of Spring Cloud Alibaba Nacos Discovery without the need to modify any code.

    Spring Cloud Alibaba Nacos Discovery also implements the standard interfaces and specifications of Spring Cloud Registry. You can use the service the same way you use Spring Cloud to perform access service registration and discovery.

  • If you are familiar with the procedure for using the open source Spring Cloud Alibaba Nacos Discovery component to register and discover services for Spring Cloud applications, you can deploy the applications on SAE to use the commercial version of service registration and discovery capabilities provided by SAE.

SAE service registry

The SAE service registry provides Spring Cloud Alibaba Nacos Discovery that is the general availability (GA) version of the open source Nacos Server. You can use the GA version of the SAE service registry for applications that are developed based on Spring Cloud Alibaba Nacos Discovery.

Compared with Nacos, Eureka, and Consul, the SAE service registry provides the following advantages:

  • Components are shared. This reduces the deployment, management, and maintenance costs of Nacos, Eureka, or Consul.
  • Links are encrypted for calls during service registration and discovery. This protects your services from being discovered by unauthorized applications.
  • The SAE service registry is integrated into other components of SAE to provide a complete set of microservice solutions, such as environment isolation and canary release.

When you deploy an application on SAE, the SAE service registry automatically specifies the following information at a higher priority: Nacos Server IP address, service port, namespace, AccessKey pair, and Context-path.

Preparations

  • Download Maven and set the environment variables.
  • Start Nacos Server.
    1. Download and decompress the Nacos Server package.
    2. Go to the nacos/bin directory and start Nacos Server.
      • Linux, UNIX, or macOS: Run the sudo sh startup.sh -m standalone command.
      • Windows: Run the startup.cmd -m standalone command.
      Note standalone indicates that the startup.cmd file is run in standalone mode, not cluster mode. By default, the startup.cmd file is started in cluster mode. If you double-click the startup.cmd file to run the file in a Windows system, the startup fails. In this case, you must configure MODE="standalone" in the startup.cmd file. For more information, see Quick Start for Nacos.

Step 1: Create a provider

Create a provider application project in an on-premises environment, add dependencies, enable service registration and discovery, and then specify the Nacos server as the service registry.

  1. Create a Maven project named nacos-service-provider.
  2. Add dependencies to the pom.xml file.

    For more information, see nacos-service-provider. The following sample code provides an example on how to add the Spring Boot 2.1.4.RELEASE and Spring Cloud Greenwich.SR1 dependencies:

    Note Spring Boot 2.4 or later is not supported. Spring Cloud Alibaba 2.2.6.RELEASE (client version 1.4.2) is supported.
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>                  

    In this example, Spring Cloud Greenwich is used. The version of Spring Cloud Alibaba for Spring Cloud Greenwich is 2.1.1.RELEASE.

    • The version of Spring Cloud Alibaba for Spring Cloud Finchley is 2.0.1.RELEASE.
    • If you use Spring Cloud Edgware, the Spring Cloud Alibaba version is 1.5.1.RELEASE.
      Note The Spring Cloud Edgware release reached the end of life (EOL). We recommend that you do not use this release to develop applications.
  3. In src\main\java, create a package named com.aliware.edas.
  4. In the com.aliware.edas package, create a startup class named ProviderApplication for the provider, and add the following sample code.

    The @EnableDiscoveryClient annotation is used to enable the service registration and discovery feature for the provider application.

        package com.aliware.edas;
    
        import org.springframework.boot.SpringApplication;
        import org.springframework.boot.autoconfigure.SpringBootApplication;
        import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
        @SpringBootApplication
        @EnableDiscoveryClient
        public class ProviderApplication {
    
            public static void main(String[] args) {
                SpringApplication.run(ProviderApplication.class, args);
            }
        }             
  5. In the com.aliware.edas package, create EchoController.

    In EchoController, specify /echo/{string} as the URL mapping and GET as the HTTP method. Obtain the method parameter from the URL path, and echo the received parameter.

        package com.aliware.edas;
    
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RestController;
    
        @RestController
        public class EchoController {
            @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
            public String echo(@PathVariable String string) {
                return string;
            }
        }              
  6. In src\main\resources, create a file named application.properties and add the following configuration to application.properties to specify the IP address of Nacos Server.
        spring.application.name=service-provider
        server.port=18081
        spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848               

    In the preceding configuration, 127.0.0.1 indicates the IP address of your Nacos Server. If your Nacos Server is deployed on another server, you must change the value to the IP address of the server. If you have other requirements, add the required configurations to the application.properties file. For more information, see Configuration items.

  7. Verify the result.
    1. Execute the main function of ProviderApplication in the nacos-service-provider project to start the provider.
    2. Log on to the on-premises Nacos Server console at http://127.0.0.1:8848/nacos.
      The default username and password that can be used to log on to the Nacos Server console are nacos.
    3. In the left-side navigation pane, choose Service Management > Services.
      You can view that service-provider is displayed in the service list. You can also query the details of the service in Details.

Step 2: Create a consumer

This section describes the service registration feature, and how Nacos Server works with RestTemplate and FeignClient.

  1. Create a Maven project named nacos-service-consumer.
  2. Add dependencies to the pom.xml file.

    For more information, see nacos-service-consumer.

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>        
  3. In src\main\java, create a package named com.aliware.edas.
  4. In the com.aliware.edas package, configure RestTemplate and FeignClient.
    1. In the com.aliware.edas package, create an interface class named EchoService, add the @FeignClient annotation, and then specify the HTTP URL and HTTP method.
      package com.aliware.edas;
      
      import org.springframework.cloud.openfeign.FeignClient;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      
      @FeignClient(name = "service-provider")
      public interface EchoService {
          @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
          String echo(@PathVariable("str") String str);
      }                   
    2. In the com.aliware.edas package, create a startup class named ConsumerApplication and add the related configurations.
      • Add the @EnableDiscoveryClient annotation to enable service registration and discovery.
      • Add the @EnableFeignClients annotation to enable FeignClient.
      • Add the @LoadBalanced annotation to integrate RestTemplate with service discovery.
      package com.aliware.edas;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
      import org.springframework.cloud.client.loadbalancer.LoadBalanced;
      import org.springframework.cloud.openfeign.EnableFeignClients;
      import org.springframework.context.annotation.Bean;
      import org.springframework.web.client.RestTemplate;
      
      @SpringBootApplication
      @EnableDiscoveryClient
      @EnableFeignClients
      public class ConsumerApplication {
      
          @LoadBalanced
          @Bean
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      
          public static void main(String[] args) {
              SpringApplication.run(ConsumerApplication.class, args);
          }
      }
  5. In the com.aliware.edas package, create a class named TestController to view and verify the service discovery feature.
        package com.aliware.edas;
    
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.client.RestTemplate;
    
        @RestController
        public class TestController {
    
            @Autowired
            private RestTemplate restTemplate;
            @Autowired
            private EchoService echoService;
    
            @RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET)
            public String rest(@PathVariable String str) {
                return restTemplate.getForObject("http://service-provider/echo/" + str,
                        String.class);
            }
    
            @RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET)
            public String feign(@PathVariable String str) {
                return echoService.echo(str);
            }
    
        }           
  6. In src\main\resources, create a file named application.properties and add the following configuration to application.properties to specify the IP address of Nacos Server.
        spring.application.name=service-consumer
        server.port=18082
        spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

    In the preceding configuration, 127.0.0.1 indicates the IP address of Nacos Server. If your Nacos Server is deployed on another server, you must change the value to the IP address of the server. If you have other requirements, add the required configurations in the application.properties file. For more information, see Configuration items.

  7. Verify the result.
    1. Execute the main function of ConsumerApplication in the nacos-service-consumer project to start the consumer application.
    2. Log on to the on-premises Nacos Server console at http://127.0.0.1:8848/nacos.
      The default username and password that can be used to log on to the Nacos Server console are nacos.
    3. In the left-side navigation pane, choose Service Management > Services. You can view that service-consumer is displayed in the service list. You can also query the details of the service in Details.

Step 3: Test the result in an on-premises environment

Initiate a call from the consumer to the provider in an on-premises environment and test the result.

  • On Linux, UNIX, or macOS, run the following commands:
    curl http://127.0.0.1:18082/echo-rest/rest-rest
    curl http://127.0.0.1:18082/echo-feign/feign-rest
  • On Windows, enter http://127.0.0.1:18082/echo-rest/rest-rest and http://127.0.0.1:18082/echo-feign/feign-rest in the browser.

Step 4: Deploy the applications on SAE

After you develop and test your application in an on-premises environment, you can create the application as a package and deploy the package on SAE. For more information, see Create applications.
Important
  • You cannot create an empty application in SAE. You must create an application in the console.
  • If you use a JAR package to deploy an application, set Application Runtime Environment to Standard Java Application Runtime Environment.
  • If you use a WAR package to deploy an application, set Application Runtime Environment to apache-tomcat-XXX.

When you deploy an application on SAE, the SAE service registry specifies the following information at a higher priority: Nacos server IP address, service port, namespace, AccessKey pair, and Context-path. You do not need to configure additional settings. You can retain or delete the original configurations.

Step 5: Verify the result

  1. Bind a Server Load Balancer (SLB) instance to the application that is deployed on SAE. For more information, see Bind an Internet-facing SLB instance.
  2. Enter the public endpoint in the address bar of your browser and initiate a call request on the homepage of the application.
  3. View service call data in the SAE console.
    1. Log on to the SAE console.
    2. In the left-side navigation pane, click Applications. In the top navigation bar, select a region. Then, click the name of an application.
    3. In the left-side navigation pane of the Basic Information page of the consumer application, choose Application Monitoring > Application Overview to get an overview of the service call data.
    If call data is detected, the service call is successful.

Configuration items

Configuration itemKeyDefault valueDescription
Server IP addressspring.cloud.nacos.discovery.server-addrNoneThe IP address and the port to which Nacos Server listens.
Service namespring.cloud.nacos.discovery.service${spring.application.name}The name of the service.
Network interface controller (NIC) namespring.cloud.nacos.discovery.network-interfaceNoneIf no IP addresses are specified, the IP address of the NIC is registered. If this configuration item is not specified, the IP address of the first NIC is used by default.
Registered IP addressspring.cloud.nacos.discovery.ipNoneThe registered IP address is assigned a higher priority than the ENI name during configuration.
Registered portspring.cloud.nacos.discovery.port-1You do not need to specify the registered port. The system automatically detects the port.
Namespacespring.cloud.nacos.discovery.namespaceNoneIsolation of the registration process in different environments. For example, the isolation of resources, such as configurations and services, in the development environment, test environment, and production environment.
Metadataspring.cloud.nacos.discovery.metadataNoneThis metadata must be configured in the JSON Map format. You can specify service-related metadata based on your business requirements.
Clusterspring.cloud.nacos.discovery.cluster-nameDEFAULTThe name of the Nacos cluster.
Endpointspring.cloud.nacos.discovery.endpointNoneThe domain name of a service in the region. You can dynamically retrieve the server address by using this domain name. You do not need to specify this configuration item when you deploy the service on SAE.
Enable Ribbon integrationribbon.nacos.enabledtrueDisable Ribbon integration based on your business requirements.

For information about Spring Cloud Alibaba Nacos Discovery, see Nacos Discovery.