Spring Cloud Alibaba

Introduction to the

Spring Cloud Alibaba is committed to providing a one-stop solution for microservice development. This project contains the necessary components for developing distributed application services that developers can easily use through the Spring Cloud programming model.

Relying on Spring Cloud Alibaba, you only need to add some annotations and a little configuration, you can plug Spring Cloud application into Alibaba distributed application solution, and quickly build distributed application system through Ali middleware.

The main function

  • Service traffic limiting degradation: Default support for WebServlet, WebFlux, OpenFeign, RestTemplate, Spring Cloud Gateway, Zuul, Dubbo and RocketMQ traffic limiting degrade function access, You can modify traffic limiting degradation rules in real time through the console at runtime and view the Metrics of traffic limiting degradation.
  • Service Registration and Discovery: It ADAPTS to the Spring Cloud Service Registration and Discovery standard and integrates Ribbon support by default.
  • Distributed configuration management: Supports external configuration in distributed systems, and automatically refreshes configuration changes.
  • Message driven capabilities: Build message driven capabilities for microservice applications based on Spring Cloud Stream.
  • Distributed t Transactions: Solve distributed transaction problems efficiently and without intrusion to the business using the @GlobalTransactional annotation.
  • Ali Cloud object storage: Ali Cloud provides massive, secure, low-cost and highly reliable cloud storage services. Supports storage and access of any type of data in any application, anytime, anywhere.
  • Distributed task scheduling: provides second-level, precise, highly reliable, and highly available scheduled (Cron expression based) task scheduling services. It also provides a distributed task execution model, such as grid tasks. Grid tasks allow quantum tasks to be evenly distributed to all workers (schedulerx-client) for execution.
  • Ali Cloud SMS service: global SMS service, friendly, efficient and intelligent interconnection communication capabilities, help enterprises quickly build customer access channels.

Included components

Sentinel

Alibaba’s open source products take traffic as the entry point to protect the stability of services from multiple dimensions such as flow control, circuit breaker downgrade and system load protection.

Nacos

Alibaba open source product, a dynamic service discovery, configuration management and service management platform that makes it easier to build cloud native applications.

RocketMQ

Apache RocketMQ™ is a Java-based high-performance, high-throughput distributed message and flow computing platform.

Dubbo

Apache Dubbo™ is a high-performance Java RPC framework.

Seata

Alibaba open source product, an easy to use high-performance microservices distributed transaction solution.

Alibaba Cloud OSS

Ali Cloud Object Storage Service (OSS) is a massive, secure, low-cost and highly reliable cloud Storage Service provided by Ali Cloud. You can store and access any type of data in any application, anytime, anywhere.

Alibaba Cloud SchedulerX

A distributed task scheduling product developed by Ali middleware team supports periodic tasks and fixed time point triggering tasks.

Alibaba Cloud SMS

The global short message service and friendly, efficient and intelligent interconnection communication capabilities help enterprises quickly build customer access channels.

Nacos

Introduction to the

In the Stage of SpringCloudNetflix, we used Eureka as the server for service registration and discovery. Now let’s change and replace this scheme with Nacos component provided by SpringCloud Alibaba. Check out the official website first

Nacos is dedicated to helping you discover, configure, and manage microservices. Nacos provides an easy-to-use feature set that helps you quickly implement dynamic service discovery, service configuration, service metadata, and traffic management.

Nacos helps you build, deliver, and manage microservices platforms more agile and easily. Nacos is the service infrastructure for building modern “service” centric application architectures (e.g., microservices paradigm, cloud native paradigm).

Key features of Nacos include:

  • Service discovery and service health monitoring

    Nacos supports DNs-based and RPC-based service discovery. After a Service provider registers a Service using a native SDK, OpenAPI, or a separate Agent TODO, Service consumers can use DNS TODO or HTTP&API to find and discover services.

    Nacos provides real-time health checks on services to prevent requests from being sent to unhealthy hosts or service instances. Nacos supports health checks at the transport layer (PING or TCP) and the application layer (e.g. HTTP, MySQL, user-defined). Nacos provides two health check modes: Agent report mode and server active check mode for complex cloud environments and network topologies, such as VPCS and edge networks. Nacos also provides a unified health check dashboard to help you manage service availability and traffic based on health status.

  • Dynamically configured service

    Dynamically configured services allow you to manage application configuration and service configuration for all environments in a centralized, external, and dynamic manner.

    Dynamic configuration eliminates the need to redeploy applications and services when configuration changes, making configuration management more efficient and agile.

    Centralized configuration management makes it easier to implement stateless services and make it easier for services to scale flexibly on demand.

    Nacos provides an easy-to-use UI (sample console Demo) to help you manage the configuration of all your services and applications. Nacos also provides a number of out-of-the-box configuration management features including configuration version tracking, Canary publishing, one-click rollback configuration, and client configuration update status tracking to help you more securely manage configuration changes and reduce the risks associated with configuration changes in a production environment.

  • Dynamic DNS Service

    The dynamic DNS service supports weighted routing, enabling you to implement load balancing at the middle layer, flexible routing policies, traffic control, and simple DNS resolution services on the data center Intranet. Dynamic DNS services also make it easier for you to implement DNS protocol-based service discovery to help eliminate the risk of coupling to vendor-proprietary service discovery apis.

    Nacos provides some simple DNS APIs TODO to help you manage your service’s associated domain name and available IP:PORT list.

  • Services and their metadata management

    Nacos enables you to manage all services and metadata in your data center from a microservices platform construction perspective, including managing service descriptions, life cycles, static dependency analysis of services, health of services, traffic management of services, routing and security policies, SLA of services, and most importantly metrics statistics.

Nacos map

  • Feature diagram: The feature demands of the problem domain to be solved will be comprehensively introduced from functional features and non-functional features
  • Architecture big picture: Quick access to the world of Nacos through clear architecture
  • Business Picture: The business scenarios that can be supported with the current features, and their best practices
  • Ecological picture: Systematically combs the relationship between Nacos and mainstream technology ecology
  • Advantages: Show the core competitiveness of Nacos
  • Strategic picture: The macro advantages of Nacos should be explained from strategic to tactical level

Nacos concept

NOTE: Nacos introduces some basic concepts that will help you understand and use Nacos products properly.

Services (Service)

A service is a software function or set of software functions (such as the retrieval of specific information or the execution of a set of operations) that can be reused by different clients for different purposes (such as through cross-process network calls). Nacos support mainstream ecological Service, such as Kubernetes Service, gRPC | Dubbo RPC Service or Spring Cloud RESTful Service.

Service Registry

Service registry, which is a database of services, instances, and metadata. Service instances are registered with the service registry at startup and unregistered at shutdown. Clients of services and routers query the service registry to find available instances of services. The service registry may invoke the health check API of the service instance to verify that it can handle the request.

Service Metadata

Service metadata refers to data describing services, including endpoints, service labels, service version numbers, service instance weights, routing rules, and security policies

Service Provider

An application that provides reusable and callable services

Service Consumer

The application that initiates a call to a service

The Configuration (Configuration)

In the process of system development, some parameters and variables that need to be changed are usually separated from the code and managed independently, existing in the form of independent configuration files. The goal is to make static system artifacts or deliverables (such as wars, JARS, etc.) better match the actual physical operating environment. Configuration management is usually performed by system administrators or O&M personnel during system deployment. Configuration change is one of the effective means to adjust the behavior of the system at run time.

Configuration Management

In a data center, all configuration-related activities such as editing, storing, distributing, change management, historical version management, and change audit are collectively referred to as configuration management.

Naming Service

Provide the mapping management service between the “name” of all objects and entities in the distributed system and the associated metadata. For example, ServiceName -> Endpoints Info, Distributed Lock Name -> Lock Owner/Status Info, DNS Domain Name -> IP List, Service discovery and DNS are two scenarios of name services.

Configuration Service

A service provider that provides dynamic configuration or metadata and configuration management during service or application execution.

Architecture diagram

More self-inspection official Internet bar!

Nacos starts fast

0. Select a version

You can find descriptions of the features supported by each release in Nacos’s Release Notes and blog, and the current stable release recommended for September 5, 2020 is 1.3.1.

1. Prepare the environment

Nacos relies on the Java environment to run. If you build and run Nacos from code and need to configure the Maven environment for this, make sure you install it in one of the following versions:

  1. The 64-bit OS supports Linux, Unix, Mac, and Windows. Linux, Unix, and Mac are recommended.
  2. 64-bit JDK 1.8+; Download & Configure.
  3. Maven 3.2 x +; Download & Configure.

2. Download the source code or install the package

Download the source code from Github

git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U  
ls -al distribution/target/

// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin
Copy the code

Download the compressed package after compilation

You can download the nacos-server-$version.zip package from the latest stable version.

  unzip nacos-server-$versionZip or tar -xvf nacos-server-$version.tar.gz
  cd nacos/bin
Copy the code

3. Start the server

Linux/Unix/Mac

Startup command (standalone stands for standalone mode, not cluster mode):

sh startup.sh -m standalone
Copy the code

If you are using Ubuntu, or if you run the script, an error message [[symbol cannot be found, try the following:

bash startup.sh -m standalone
Copy the code

Windows

Start command:

startup.cmd -m standalone
Copy the code

Or double-click the startup. CMD file to run it.

4. Access tests

Open the browser to http://localhost:8848/nacos, you can access the service, the default password is nacos/nacos

Spring Cloud Alibaba Nacos Config

Nacos provides key/value stores for storing configuration and other metadata, providing server-side and client-side support for externalizing configuration in distributed systems. Using Spring Cloud Alibaba Nacos Config, you can centrally manage the external property configuration of your Spring Cloud application in Nacos Server.

Spring Cloud Alibaba Nacos Config is an alternative to Config Server and Client. Concepts on the client and server have consistent abstractions with Spring Environment and PropertySource, and the configuration is loaded into the Spring Environment during a special Bootstrap phase. As the application moves through the deployment pipeline from development to test to production, you can manage the configuration between these environments and ensure that the application has everything it needs to run at migration time.

Quick start

1. Add the following configuration to nacOS

Data ID: nacos-config.properties

Group  :    DEFAULT_GROUP

Configuration format:    Properties

Configuration contents:   user.name=nacos-config-properties
            user.age=90
Copy the code

Note that datAID is extended with Properties (the default file extension).

Create the NacOS Config client

The pom. XML configuration file is as follows


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3. RELEASE</version>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-alibaba-dependencies</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>hello-spring-cloud-alibaba-dependencies</name>
    <description>Create unified dependency management</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.3. RELEASE</spring-boot.version>
        <! -- Spring Settings -->
        <spring-cloud.version>Hoxton SR8</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.1. RELEASE</spring-cloud-alibaba.version>
    </properties>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <! -- Compiler plugin, set JDK version -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>

            <! Configure the manifest file and add the jar dependencies to the lib package.
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <addMavenDescriptor>false</addMavenDescriptor>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <configuration>
                            <archive>
                                <manifest>
                                    <! -- Add directory entries -->
                                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                                    <addClasspath>true</addClasspath>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <! -- resource -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>

            <! -- install -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
            </plugin>

            <! -- clean -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
            </plugin>


            <! -- dependency -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <! -- Java Document Generate -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <! -- YUI Compressor (CSS/JS compression)
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>yuicompressor-maven-plugin</artifactId>
                    <version>1.5.1</version>
                    <executions>
                        <execution>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>compress</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <encoding>UTF-8</encoding>
                        <jswarn>false</jswarn>
                        <nosuffix>true</nosuffix>
                        <linebreakpos>30000</linebreakpos>
                        <force>true</force>
                        <includes>
                            <include>**/*.js</include>
                            <include>**/*.css</include>
                        </includes>
                        <excludes>
                            <exclude>**/*.min.js</exclude>
                            <exclude>**/*.min.css</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <! -- Resource File Configuration -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>

</project>
Copy the code

application.yml

spring:
  application:
    name: nacos-config You need to find the corresponding configuration file based on it
  cloud:
    nacos:
      config:
        server-addr: localhost:8848   # nacos address
        file-extension: yaml   # file suffix, default is properties, custom configuration is required to find the correct configuration
  profiles:
    active: develop		Declare the configured environment
Copy the code

Add the corresponding code to the startup class to get the configuration information

// When the dynamic configuration is refreshed, it is updated to the Enviroment, so the configuration is fetched from the Enviroment every second
// String userName = applicationContext.getEnvironment().getProperty("user.name");
            String currentEnv = applicationContext.getEnvironment().getProperty("current.env");
// String userAge = applicationContext.getEnvironment().getProperty("user.age");
// System.err.println("user name :" + userName + "; age: " + userAge);
            System.out.println(currentEnv);
            TimeUnit.SECONDS.sleep(1);
Copy the code

At this point, nacos-config is configured for simple use.

3. Supports user-defined namespace configuration

First take a look at the Namespace concept of Nacos, the concept of Nacos

Used for configuration isolation of tenant granularity. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.

Without a clear use ${spring. Cloud. Nacos. Config. The namespace} specify the namespace. The default is public, if need to specify, using spring. Cloud. Nacos. Config. To specify the namespace

spring:
  application:
    name: nacos-config
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        namespace: 419519c2-cdfd-4905-b754-9b709313d83f # specify a namespace
Copy the code

Besides spring. Cloud. Nacos. Config. The value of the namespace is namespace corresponding id, id value can be obtained in nacos console. Do not select another Namespae when adding the configuration. Otherwise, the correct configuration will not be read.

Supports the configuration of user-defined groups

Without explicitly specify ${spring. Cloud. Nacos. Config. Group} configuration, use DEFAULT_GROUP by default. If you need to customize your own Group, you can perform the following configuration:

spring:
  application:
    name: nacos-config
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        group: TEST_GROUP  # specify a group
  profiles:
    active: develop
Copy the code

When adding configuration Group values must be and spring. Cloud. Nacos. Config. Group configuration values are consistent.

There are some other features, interested in their own official website to check it

Spring Cloud Alibaba Nacos Discovery

The project provides seamless integration with Nacos for Spring Boot applications in service registration and discovery through automatic configuration and other idioms of the Spring programming model. With a few simple annotations, you can quickly register a service and use the 11.1-tested Nacos component as a service registry for large-scale distributed systems.

Service registry Discovery: Nacos Discovery Starter

Service discovery is one of the most critical components in microservices architecture. It would be very difficult to manually configure the service list of all service providers for each client, and it would be difficult to dynamically scale the service. The Nacos Discovery Starter helps you automatically register your services with the Nacos server and dynamically sense and refresh the list of services for a service instance. In addition, the Nacos Discovery Starter registers some metadata information about the service instance itself – such as host, port, health check URL, home page, etc. – with Nacos

Start a Provider application

The pom. XML configuration file is as follows


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.wujie</groupId>
        <version>0.0.1 - the SNAPSHOT</version>
        <artifactId>hello-spring-cloud-alibaba-dependencies</artifactId>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-alibaba-nacos-provider</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>hello-spring-cloud-alibaba-nacos-provider</name>
    <description>Create a NACOS service provider</description>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0. RELEASE</version>
                <configuration>
                    <mainClass>
                        com.wujie.hello.spring.cloud.alibaba.nacos.provider.HelloSpringCloudAlibabaNacosProviderApplication
                    </mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

application.yml

server:
  port: 8761

spring:
  application:
    name: hello-spring-cloud-alibaba-nacos-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code

Add to the startup class@EnableDiscoveryClientannotations

@SpringBootApplication
@EnableDiscoveryClient
public class HelloSpringCloudAlibabaNacosProviderApplication {

    public static void main(String[] args) { SpringApplication.run(HelloSpringCloudAlibabaNacosProviderApplication.class, args); }}Copy the code

Write a TestController test

@RestController
public class TestController {
    @RequestMapping("/hi")
    public String sayHi(@RequestParam("msg")String msg){
        return "hello nacos discovery "+msg; }}Copy the code

Start the project and look at nacOS to see that the service is already in the list of services

Go to http://localhost:8761/hi? MSG =nacos Returns successfully

At this point a service provider is successful.

Start a Consumer For RestTemplate application

In this case, our Consumer needs to consume the Provider’s services, so we can still use RestTemplate or Fegin as before. Let’s try using RestTemplate+LoadBalanceClient

The pom.xml file is as follows


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.wujie</groupId>
        <version>0.0.1 - the SNAPSHOT</version>
        <artifactId>hello-spring-cloud-alibaba-dependencies</artifactId>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-alibaba-nacos-rest-consumer</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>hello-spring-cloud-alibaba-nacos-rest-consumer</name>
    <description>Demo project for Spring Boot</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1. RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0. RELEASE</version>
                <configuration>
                    <mainClass>
                        com.wujie.hello.spring.cloud.alibaba.nacos.rest.consumer.HelloSpringCloudAlibabaNacosRestConsumerApplication
                    </mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

application.yml

spring:
  application:
    name: hello-spring-cloud-alibaba-nacos-rest-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
server:
  port: 8762
Copy the code

Modify the startup class as follows

@SpringBootApplication
@EnableDiscoveryClient
public class HelloSpringCloudAlibabaNacosRestConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloSpringCloudAlibabaNacosRestConsumerApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(a){
        return newRestTemplate(); }}Copy the code

Write the TestController test class

@RestController
public class TestController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Value("${spring.application.name}")
    private String name;
    @RequestMapping("/hi")
    public String sayHi(a){
        ServiceInstance choose = loadBalancerClient.choose("hello-spring-cloud-alibaba-nacos-provider");
        String url = String.format("http://%s:%s/hi? msg=%s",choose.getHost(),choose.getPort(),name);
        System.out.println("request uri:"+url);
        returnrestTemplate.getForObject(url,String.class); }}Copy the code

Start the service and visit http://localhost:8762/hi to get the following results

In this example, we inject an instance of LoadBalancerClient, manually instantiate a RestTemplate, and inject the configuration value of Spring.application. name into the application. The purpose is to display the currently configured application name when invoking the service provided by the Provider.

So far we have successfully invoked the Provider service using the RestTemplate.

Start a Consumer For Fegin application

The pom.xml file is as follows


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.wujie</groupId>
        <version>0.0.1 - the SNAPSHOT</version>
        <artifactId>hello-spring-cloud-alibaba-dependencies</artifactId>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-alibaba-nacos-feign-consumer</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>hello-spring-cloud-alibaba-nacos-feign-consumer</name>
    <description>Create consumers based on fegin calls</description>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.5. RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0. RELEASE</version>
                <configuration>
                    <mainClass>
                        com.wujie.hello.spring.cloud.alibaba.nacos.feign.consumer.HelloSpringCloudAlibabaNacosFeignConsumerApplication
                    </mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

application.yml

spring:
  application:
    name: hello-spring-cloud-alibaba-nacos-feign-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
  management:
    endpoints:
      web:
        exposure:
          include: "*"
server:
  port: 8763
Copy the code

Add to the startup class@EnableFeignClientsannotations

@SpringBootApplication
@EnableFeignClients
public class HelloSpringCloudAlibabaNacosFeignConsumerApplication {

    public static void main(String[] args) { SpringApplication.run(HelloSpringCloudAlibabaNacosFeignConsumerApplication.class, args); }}Copy the code

Write a Client interface and add@FeignClientannotations

@FeignClient(value = "hello-spring-cloud-alibaba-nacos-provider")
public interface TestClient {
    @RequestMapping("/hi")
    String sayHi(@RequestParam("msg")String msg);
}
Copy the code

Write TestController

@RestController
public class TestController {
    @Autowired
    TestClient testClient;
    @Value("${spring.application.name}")
    private String name;
    @RequestMapping("/hi")
    public String sayHi(a){
        returntestClient.sayHi(name); }}Copy the code

After starting the service, start one more service provider to test load balancing:

Visit http://localhost:8763/hi: refresh you can see the port number is constantly changing

More configuration items about Nacos Starter

The starter configuration items for spring-cloud-starter-Alibaba-nacos-Discovery are as follows:

Configuration items Key The default value instructions
Server address spring.cloud.nacos.discovery.server-addr There is no Nacos Server starts the LISTENING IP address and port
The service name spring.cloud.nacos.discovery.service ${spring.application.name} Name the current service
Service group spring.cloud.nacos.discovery.group DEFAULT_GROUP Sets the group to which the service belongs
The weight spring.cloud.nacos.discovery.weight 1 The value ranges from 1 to 100. A larger value indicates a larger weight
The network card name spring.cloud.nacos.discovery.network-interface There is no If the IP address is not configured, the registered IP address is the IP address of this NIC. If this parameter is not configured, the IP address of the first NIC is used by default
Registered IP address spring.cloud.nacos.discovery.ip There is no Highest priority
Registered port spring.cloud.nacos.discovery.port - 1 By default, no configuration is required and automatic detection is performed
The namespace spring.cloud.nacos.discovery.namespace There is no One common scenario is the separation of registration between different environments, such as isolation of resources (such as configurations and services) between development test environments and production environments.
AccessKey spring.cloud.nacos.discovery.access-key There is no When you want to go to Ali Cloud, ali cloud above a cloud account name
SecretKey spring.cloud.nacos.discovery.secret-key There is no When you want to go on Ali cloud, ali cloud above a cloud account password
Metadata spring.cloud.nacos.discovery.metadata There is no Using the Map format, users can customize metadata related to services as required
Log file name spring.cloud.nacos.discovery.log-name There is no
The cluster spring.cloud.nacos.discovery.cluster-name DEFAULT Configure to Nacos cluster name
Access point spring.cloud.nacos.discovery.enpoint UTF-8 An inbound domain name of a service in a region through which you can dynamically obtain the server address
Whether to integrate Ribbon ribbon.nacos.enabled true It is usually set to true
Whether to enable Nacos Watch spring.cloud.nacos.discovery.watch.enabled true You can set it to false to turn off watch