Service Registration and Discovery Nacos for SpringCloudAlibaba

1. Preface

Nacos is Alibaba's new open source project that enables fast dynamic service discovery, service configuration, service metadata, and traffic management.

This blog focuses on service registration and discovery.

There is also an equally good service registration and discovery component in SpringCloud: Eureka. But it's closed, which is one of the reasons why I want to learn Nacos.

If you also want to know Eureka, go to: Service Registration and Discovery for SpringCloud Eureka+Client Feign . Individually, I think the process of building and using the two is very similar.

Core similarities:

  1. Introducing dependencies
  2. Configure Registry Address
  3. adding annotations

The biggest difference is:

  1. How to set up the server
  • Eureka Server is built manually by itself
  • Nacos Server needs to be built from source or downloaded directly

Another important piece of information about Nacos Server

Deployment: Three deployment modes for different usage scenarios

  1. Single machine mode: convenient for local testing
  2. Cluster mode: for production environments
  3. Multi-cluster mode: for multiple data centers

Data source: Two data sources that can be specified in the configuration file

  1. Derby: A database embedded in the application (currently the default data source)
  2. MySQL: Free open source relational database (version requires 5.6.5+)

Nacos Server Version Selection: Current stable version recommended by the official website is 1.2.1


2. Source Code

GitHub address: https://github.com/intomylife/SpringCloud


3. Environment

  • JDK 1.8 +
  • Maven 3.2.x +
  • SpringBoot 2.0.6.RELEASE
  • SpringCloud Finchley.SR2
  • SpringCloudAlibaba 2.0.2.RELEASE

4. Development Tools

  • IntelliJ IDEA

5. Body

5.1 commons Project

5.1.1 commons Project - POM Files

<?xml version="1.0" encoding="UTF-8"?>
<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>

	<!-- 3-coordinate -->
	<groupId>com.zwc</groupId>
	<artifactId>discovery-commons</artifactId>
	<version>1.0.0</version>

	<!-- Project name and description -->
	<name>discovery-commons</name>
	<description>Public Works</description>

	<!-- Packing Method -->
	<packaging>jar</packaging>

	<!-- stay properties Declare the appropriate version information below, and then dependency Use when referencing below ${} This version can be introduced jar Packed -->
	<properties>
		<!-- Code -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- jdk -->
		<java.version>1.8</java.version>

		<!-- SpringBoot -->
		<platform-bom.version>Cairo-SR3</platform-bom.version>
		<!-- SpringCloud -->
		<spring-cloud-dependencies.version>Finchley.SR2</spring-cloud-dependencies.version>
		<!-- SpringCloudAlibaba -->
		<spring-cloud-alibaba-dependencies.version>2.0.2.RELEASE</spring-cloud-alibaba-dependencies.version>
	</properties>

	<!-- Join Dependency -->
	<dependencies>
		<!-- springboot Start Dependency -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
			<!-- Exclude dependencies -->
			<exclusions>
				<exclusion>
					<groupId>ch.qos.logback</groupId>
					<artifactId>*</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.apache.logging.log4j</groupId>
					<artifactId>*</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- springboot web rely on -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- Exclude dependencies -->
			<exclusions>
				<exclusion>
					<groupId>ch.qos.logback</groupId>
					<artifactId>*</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.apache.logging.log4j</groupId>
					<artifactId>*</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- log4j2 rely on -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
	</dependencies>

	<!-- rely on jar Package Version Management Manager -->
	<!-- If dependencies In dependency I have no declaration version Element, then maven Find the version declaration here. -->
	<!-- If so, it will be inherited; If not, you will get an error telling you that there is no version information -->
	<!-- Priority: If dependencies In dependency Version information already declared will not take effect here -->
	<dependencyManagement>
		<dependencies>
			<!-- SpringBoot -->
			<dependency>
				<groupId>io.spring.platform</groupId>
				<artifactId>platform-bom</artifactId>
				<version>${platform-bom.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<!-- SpringCloud -->
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud-dependencies.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<!-- SpringCloudAlibaba -->
			<dependency>
				<groupId>com.alibaba.cloud</groupId>
				<artifactId>spring-cloud-alibaba-dependencies</artifactId>
				<version>${spring-cloud-alibaba-dependencies.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<!-- Plug-in Dependency -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
  • Introduce some shared dependencies

5.1.2 commons Project-Project Structure

springcloudalibaba-nacos-discovery/discovery-commons/
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zwc
        │           └── core
        └── resources
            └── application.properties

5.2 service Project

There are five modules under this project:

apply name port describe
discovery-flyway-service 8082 Auxiliary Engineering (Automatically create databases and tables)
discovery-master-service / Registry (The Registry Project here is actually the source code for Nacos, put into the project just to find it)
discovery-provider-first-service 8090 Provider 1 Service Project (Providing Services to Outside)
discovery-provider-second-service 8091 Provider No. 2 Service Project (External Service Provision)
discovery-consumer-service 8080 Consumer Services Engineering (Remote Call Services)

Detailed description:

discovery-flyway-service: The foreword describes two data sources for Nacos Server, MySQL is used here; With MySQL as the data source, you need to build some basic tables and insert some basic data, which requires manual manipulation. However, for convenience, I "simplified" these "dull" operations: just start the project. Perhaps the only thing to note is that my local MySQL account password is root, 123456, and if it doesn't match yours, it's in application. Change it in the properties configuration file.

discovery-master-service: The source code of Nacos Server is simply copied and pasted in this project, which is put into the project for easy access. Another reason is that you need to specify MySQL as the data source in Nacos Server's configuration file and configure connection information for the MySQL database. However, for convenience, I have corrected the configuration information in Nacos Server's source code. Perhaps the only thing to note is that my local MySQL account password is root, 123456, and if it doesn't match yours, it's in nacos-1.2.1/distribution/conf/application. Lines 25,26 in the properties configuration file were changed. Nacos-1.2.1/distribution/conf/application. Properrties is the default configuration file built from the source code, so modify the corresponding configuration information in the source code first to facilitate the use of scripts to quickly start the Nacos Server service later.

discovery-provider-first-service: as a provider, to provide a service to the outside world, the specific content of the service is to output a sentence and the port number of the current service. Note that the application names (spring.application.name) of the two providers are identical.

discovery-provider-second-service: as a provider, to provide a service to the outside world, the specific content of the service is to output a sentence and the port number of the current service. Note that the application names (spring.application.name) of the two providers are identical.

discovery-consumer-service: As a consumer, call a service remotely, that is, call the services provided by the two providers above.


Other supplementary notes:


5.2.1 discovery-flyway-service

5.2.1.1 discovery-flyway-service-POM file

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <!-- Inherit parent -->
    <parent>
        <groupId>com.zwc</groupId>
        <artifactId>discovery-service</artifactId>
        <version>1.0.0</version>
    </parent>

    <!-- 3-coordinate -->
    <groupId>com.zwc</groupId>
    <artifactId>discovery-flyway-service</artifactId>
    <version>1.0.0</version>

    <!-- Project Name Description -->
    <name>discovery-flyway-service</name>
    <description>Auxiliary Engineering (Automatically create databases and tables)</description>

    <!-- Packing Method -->
    <packaging>jar</packaging>

    <!-- stay properties Declare the appropriate version information below, and then dependency Use when referencing below ${} This version can be introduced jar Packed -->
    <properties>
        <!-- ali Connection Pool -->
        <druid.version>1.1.9</druid.version>
    </properties>

    <!-- Join Dependency -->
    <dependencies>
        <!-- Database Access Dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- mysql rely on -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- ali Connection pool dependency -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- Database Version Management Dependency -->
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
    </dependencies>

    <!-- Plug-in Dependency -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • The purpose and role of this project is to automatically create databases and tables, so database and flyway-related dependencies are introduced

5.2.1.2 discovery-flyway-service-application. Properties profile

# port
server.port=8082


# data source
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/nacos_config?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456


## Flway Note: Configuration can be completely unused
### The location of the sql script, defaulting to classpath:db/migration. Can be specified manually
#spring.flyway.locations=classpath:db/migration
###  Specify the data source, if not specified, the configured primary data source will be used
#spring.flyway.url=jdbc:mysql://127.0.0.1:3306/nacos_config?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
### Flyway managed Schema list, case sensitive. Default Schema for Default Connection
### If the library name is explicitly specified here, then in spring. Flway. The library name specified in the URL connection will be invalid
#spring.flyway.schemas=nacos_config
### User name
#spring.flyway.user=root
### Password
#spring.flyway.password=123456
### On, on by default
#spring.flyway.enabled=true
  • Configured basic information to connect to the database, remember to change if account password does not match yours
  • Since flyway takes configuration information of the data source by default, here are all the comments about flyway configuration. The main reason is that if you use my source code test, the information of the data source can be changed one less place. My local MySQL password is 123456. You may not be the same as me.

5.2.1.3 discovery-flyway-service - Automatically create database

package com.zwc.flyway.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @ClassName InitDatabaseConfig
 * @Desc TODO   Automatically create database
 * @Date 2020/6/21 8:38 PM
 * @Version 1.0
 */
@Configuration
public class InitDatabaseConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(InitDatabaseConfig.class);

    /**
     * Read connection information for database in configuration file
     */
    /**
     * Driver Name
     */
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    /**
     * address
     */
    @Value("${spring.datasource.url}")
    private String url;
    /**
     * User name
     */
    @Value("${spring.datasource.username}")
    private String username;
    /**
     * Password
     */
    @Value("${spring.datasource.password}")
    private String password;


    /*
      * @ClassName InitDatabaseConfig
      * @Desc TODO  Create a database
      * @Date 2020/6/22 8:58 AM
      * @Version 1.0
     */
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        LOGGER.info("==================================== InitDatabaseConfig -> dataSource -> Start creating database ====================================");
        // Database Connection Object
        Connection connection = null;
        Statement statement = null;
        try {

            // An error will occur if you try to connect to a database that does not exist, so connect here without a database name
            String connectionUrl = url.replace(("/" + (url.substring(0, url.indexOf("?"))).substring(((url.substring(0, url.indexOf("?"))).lastIndexOf("/")) + 1)), "");
            // Truncate the database name from the connection address
            String databaseName = (url.substring(0, url.indexOf("?"))).substring(((url.substring(0, url.indexOf("?"))).lastIndexOf("/")) + 1);

            // Set Driver
            Class.forName(driverClassName);
            // Connect to database
            connection = DriverManager.getConnection(connectionUrl, username, password);
            statement = connection.createStatement();

            // Create a database
            statement.executeUpdate("create database if not exists `" + databaseName + "` default character set utf8mb4 COLLATE utf8mb4_general_ci");

        }catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("==================================== InitDatabaseConfig -> dataSource -> Error creating database:" + e.getMessage() + " ====================================");
        }finally {
            try {
                // Close Connection
                statement.close();
                connection.close();
            }catch (SQLException e) {
                LOGGER.info("==================================== InitDatabaseConfig -> dataSource -> Error closing database:" + e.getMessage() + " ====================================");
            }
            LOGGER.info("==================================== InitDatabaseConfig -> dataSource -> Finish creating database ====================================");
        }

        // create data source
        DruidDataSource druidDataSource = new DruidDataSource();
        // set up data sources
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        // Return to Data Source
        return druidDataSource;
    }

}
  • Label the custom configuration class with @Configuration to initialize when the application context loads

5.2.1.4 discovery-flyway-service - Automatically create new data tables

Since the flyway-core dependency was introduced, you only need to place the initialization sql in the db/migration directory that flyway will read by default. Details can be found in Source code If you view it in, you won't paste it out to take up space.

5.2.1.5 discovery-flyway-service - Start project

  1. After confirming and modifying the connection information of the database, start the project; The project stops automatically when it is found to be started. As long as there are no errors, this is normal and the console prints the following log information:
2020-07-04 18:35:34.120  INFO 2036 --- [           main] c.zwc.flyway.config.InitDatabaseConfig   : ==================================== InitDatabaseConfig -> dataSource -> Start creating database ====================================
2020-07-04 18:35:34.347  INFO 2036 --- [           main] c.zwc.flyway.config.InitDatabaseConfig   : ==================================== InitDatabaseConfig -> dataSource -> Finish creating database ====================================
  1. When you refresh the local library in the MySQL Graphical Connection Tool, you find that there is one more nacos_config database, open the database, you can see that some basic tables have been created automatically
  2. Then, the discovery-flyway-service project is finished

5.2.2 discovery-master-service

Only the source code of Nacos Server in this project, there are not too many build instructions. The only thing to note is the database connection account password mentioned above. If you are not root, 123456, you can modify it.

But here's how to quickly build this source code. Of course, Nacos's official documentation has been written in great detail, adding a wave of commands that can be "encapsulated" once more to quickly start the Nacos Server service.

There are two different scenarios scripted for local quick development testing and daily use, which are placed in the project's script In directory

springcloudalibaba-nacos-discovery/
├── discovery-commons
├── discovery-service
└── script
    ├── daily-use
    │   ├── nacos-start.sh
    │   └── nacos-stop.sh
    └── quick-start
        ├── nacos-install.bat
        ├── nacos-install.sh
        ├── nacos-start.bat
        ├── nacos-start.sh
        ├── nacos-stop.bat
        └── nacos-stop.sh

quick-start directory-Quick start:

  1. Open with IDEA springcloudalibaba-nacos-discovery project
  2. Click Terminal Terminal Entry at the bottom of IDEA
  3. Enter the project root directory
MacBook-Pro:springcloudalibaba-nacos-discovery zouwencong$ pwd
/Users/zouwencong/JavaWork/my_spring_cloud/SpringCloud/springcloudalibaba-nacos-discovery
MacBook-Pro:springcloudalibaba-nacos-discovery zouwencong$ ls -all
total 32
drwxr-xr-x   7 zouwencong  staff    224 Jun 25 21:57 .
drwxr-xr-x  18 zouwencong  staff    576 Jul  3 13:54 ..
-rw-r--r--@  1 zouwencong  staff  12292 Jul  2 09:47 .DS_Store
drwxr-xr-x  10 zouwencong  staff    320 Jul  4 18:58 .idea
drwxr-xr-x  11 zouwencong  staff    352 Jun 28 16:08 discovery-commons
drwxr-xr-x  14 zouwencong  staff    448 Jul  2 16:41 discovery-service
drwxr-xr-x   5 zouwencong  staff    160 Jun 22 17:51 script
MacBook-Pro:springcloudalibaba-nacos-discovery zouwencong$ 
  1. If you are a Mac user, enter the command Chmod +x script/quick-start/nacos-install first. Sh, and then enter the command. / script/quick-start/nacos-install.sh
  2. If you are a Windows user, enter the command script\quick-start\nacos-install.bat
  3. The first build will take a little longer, and I've spent about two or three minutes here myself, because I'm going to Maven to download SpringCloudAlibaba's dependencies
  4. If you are a Mac user, the following log will appear after executing the corresponding command (intercepting the last critical section):
...Omit Part...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 38.467 s
[INFO] Finished at: 2020-07-04T19:42:13+08:00
[INFO] Final Memory: 110M/1588M
[INFO] ------------------------------------------------------------------------
...Omit Part...
nacos is starting with standalone
nacos is starting,you can check the /Users/zouwencong/Downloads/SpringCloud-master/springcloudalibaba-nacos-discovery/discovery-service/discovery-master-service/nacos-1.2.1/distribution/target/naco-server-1.2.1/nacos/logs/start.out
[INFO] ----------------------------- end --------------------------------------
  1. If you are a Windows user, the following log will appear after executing the corresponding command (intercepting the last critical section):
...Omit Part...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:18 min
[INFO] Finished at: 2020-07-04T19:52:11+08:00
[INFO] ------------------------------------------------------------------------
...Omit Part...
2020-07-04 19:52:22,620 INFO Nacos started successfully in stand alone mode.

2020-07-04 19:52:22,857 INFO Initializing Servlet 'dispatcherServlet'

2020-07-04 19:52:22,865 INFO Completed initialization in 7 ms
  1. Nacos Server starts successfully and visits the Nacos Server home page: http://localhost:8848/nacos
  2. Account password: nacos, nacos
  3. There are also stop scripts here
  4. If you are a Mac user, enter the command Chmod +x script/quick-start/nacos-stop first. Sh, and then enter the command. / script/quick-start/nacos-stop.sh
  5. If you are a Windows user, you find that there is no place for the current Terminal box to enter, so to stop, click the + (New Session) button first, then type the command script\quick-start\nacos-stop.bat
  6. So if you want to start again, because this is all built here, use the startup scripts separately
  7. If you are a Mac user, enter the command Chmod +x script/quick-start/nacos-start first. Sh, and then enter the command. / script/quick-start/nacos-start.sh
  8. If you are a Windows user, enter the command script\quick-start\nacos-start.bat

daily-use directory-Daily use:

We may often use the Nacos Server service in future projects, just like Redis and MySQL, when starting as a service, first copy the directory just compiled and built (discovery-master-service/nacos-1.2.1/distribution/target/nacos-server-1.2.1/nacos) locally. Since it's a daily service, set up the log directory again

  1. Open conf/application under the directory just copied (discovery-master-service/nacos-1.2.1/distribution/target/nacos-server-1.2.1/nacos). Properties profile
  2. Ctrl + F search server.tomcat.basedir
  3. You can then specify the directory path to store the logs

Since starting Nacos Server in Windows does not require specifying parameters, it is in the bin directory under the directory just copied (discovery-master-service/nacos-1.2.1/distribution/target/nacos-server-1.2.1/nacos). The bat script can be used by double-clicking directly; For convenience in Mac, there is also a script for everyday use, how to use it

  1. copy springcloudalibaba-nacos-discovery Script/daily-use/nacos-start in the project. SH script file and script/daily-use/nacos-stop.sh script file to desktop
  2. Assign permission to execute: chmod +x nacos-start.sh, chmod +x nacos-stop.sh
  3. Right-click nacos-start.sh file
  4. Open Mode->Other...
  5. Enable: Select all applications
  6. Check always opens this way
  7. Click Utilities
  8. Double-click terminal
  9. nacos-stop.sh is also set once
  10. Once set up, you can now start or stop the Nacos Server service with a double-click
  11. Of course, I don't know where you will copy the built directory, so the specific directory in the script needs to be modified accordingly
  12. Nacos-start. SH ->Line 20
  13. Nacos-stop. SH ->Line 8

5.2.3 discovery-provider-first-service

5.2.3.1 discovery-provider-first-service - POM file

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <!-- Inherit parent -->
    <parent>
        <groupId>com.zwc</groupId>
        <artifactId>discovery-provider-first-service</artifactId>
        <version>1.0.0</version>
    </parent>

    <!-- 3-coordinate -->
    <groupId>com.zwc</groupId>
    <artifactId>discovery-provider-first-service-core</artifactId>
    <version>1.0.0</version>

    <!-- Project Name Description -->
    <name>discovery-provider-first-service-core</name>
    <description>Provider 1 Service Project - core</description>

    <!-- Packing Method -->
    <packaging>jar</packaging>

    <!-- stay properties Declare the appropriate version information below, and then dependency Use when referencing below ${} This version can be introduced jar Packed -->
    <properties>

    </properties>

    <!-- Join Dependency -->
    <dependencies>
        <!-- commons Project Dependency -->
        <dependency>
            <groupId>com.zwc</groupId>
            <artifactId>discovery-commons</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- api Project Dependency -->
        <dependency>
            <groupId>com.zwc</groupId>
            <artifactId>discovery-provider-first-service-api</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- Provider Consumer -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

    <!-- Plug-in Dependency -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • Joining the spring-cloud-starter-alibaba-nacos-discovery dependency means registering yourself with Nacos Server

5.2.3.2 discovery-provider-first-service-application. YML Profile

# port
server:
  port: 8090

spring:
  application:
    # apply name
    name: say-hello
  cloud:
    nacos:
      discovery:
        # Registry Address
        server-addr: 127.0.0.1:8848
        # User name
        username: nacos
        # Password
        password: nacos
  • Note that the port where the registry address is configured here is 8848, the service port of Nacos Server
  • There are two provider projects, only here the ports are inconsistent, where the port is 8090 and the other port is 8091. Let's not go into that again
  • The two providers are engineered to achieve load balancing
  • spring.application.name: the name of the application, which is required when called by the consumer
  • Note that the Nacos Server username and password are also configured here because I am discovery-master-service/nacos-1.2.1/distribution/conf/application. Nacos is included in the properties configuration file. Core. Auth. Enabled set to true, in fact, the default is false off; You must specify a valid username and password when you open it, otherwise you will get an error

5.2.3.3 discovery-provider-first-service - controller front-end controller

package com.zwc.first.api;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName SayHelloController
 * @Desc TODO   Say Hello
 * @Date 2019/5/15 15:28
 * @Version 1.0
 */
@RestController
public class SayHelloController {

    /*
     * @ClassName SayHelloController
     * @Desc TODO   Read Ports in Configuration File
     * @Date 2019/5/15 15:49
     * @Version 1.0
     */
    @Value("${server.port}")
    private String port;

    /*
     * @ClassName SayHelloController
     * @Desc TODO   Say Hello
     * @Date 2019/5/15 15:30
     * @Version 1.0
     */
    @RequestMapping("/hello")
    public String hello(){
        return "Hello Spring Cloud Alibaba!!! port: " + port;
    }

}
  • Provide a service: Output Hello and Port

5.2.3.4 discovery-provider-first-service-startup class

package com.zwc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class DiscoveryProviderFirstServiceCoreApplication {

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

}
  • Adding the @EnableDiscoveryClient annotation indicates that the service is registering itself with the registry

5.2.3.5 discovery-provider-first-service - Start project

  1. Access after successful project startup http://localhost:8090/hello See the output Hello Spring Cloud Alibaba!!! port:8090
  2. Refresh http://localhost:8848/nacos/#/serviceManagement (Registry) You can see that the service has been registered
service name Group name Number of clusters Number of instances Number of health instances Trigger protection threshold operation
say-hello DEFAULT_GROUP 1 1 1 false Details|Sample Code|Delete
  1. Similarly, there is a provider project that just has inconsistent ports and starts up
  2. Access after successful project startup http://localhost:8091/hello See the output Hello Spring Cloud Alibaba!!! port:8091
  3. Refresh again http://localhost:8848/nacos/#/serviceManagement (Registry) You can see that there are two providers for the same service
service name Group name Number of clusters Number of instances Number of health instances Trigger protection threshold operation
say-hello DEFAULT_GROUP 1 2 2 false Details|Sample Code|Delete

5.2.4 discovery-consumer-service

5.2.4.1 discovery-consumer-service-POM file

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <!-- Inherit parent -->
    <parent>
        <groupId>com.zwc</groupId>
        <artifactId>discovery-consumer-service</artifactId>
        <version>1.0.0</version>
    </parent>

    <!-- 3-coordinate -->
    <groupId>com.zwc</groupId>
    <artifactId>discovery-consumer-service-core</artifactId>
    <version>1.0.0</version>

    <!-- Project Name Description -->
    <name>discovery-consumer-service-core</name>
    <description>Consumer Service Engineering - core</description>

    <!-- Packing Method -->
    <packaging>jar</packaging>

    <!-- stay properties Declare the appropriate version information below, and then dependency Use when referencing below ${} This version can be introduced jar Packed -->
    <properties>

    </properties>

    <!-- Join Dependency -->
    <dependencies>
        <!-- commons Project Dependency -->
        <dependency>
            <groupId>com.zwc</groupId>
            <artifactId>discovery-commons</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- api Project Dependency -->
        <dependency>
            <groupId>com.zwc</groupId>
            <artifactId>discovery-consumer-service-api</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- Provider Consumer -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- feign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

    <!-- Plug-in Dependency -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • Consistent with the provider, adding a spring-cloud-starter-alibaba-nacos-discovery dependency means registering yourself with Nacos Server
  • And you also need to join Feign to start by relying on spring-cloud-starter-openfeign to indicate that you will call other services remotely

5.2.4.2 discovery-consumer-service-application. YML Profile

# port
server:
  port: 8080

spring:
  application:
    # apply name
    name: service-feign
  cloud:
    nacos:
      discovery:
        # Registry Address
        server-addr: 127.0.0.1:8848
        # User name
        username: nacos
        # Password
        password: nacos

# Open Circuit Breaker
feign:
  hystrix:
    enabled: true
  • Note that the port where the registry address is configured here is 8848, the service port of Nacos Server
  • spring.application.name: The name of the application, which is used when it is called by consumers. It can also be consumed while consuming
  • Note that the Nacos Server username and password are also configured here because I am discovery-master-service/nacos-1.2.1/distribution/conf/application. Nacos is included in the properties configuration file. Core. Auth. Enabled set to true, in fact, the default is false off; You must specify a valid username and password when you open it, otherwise you will get an error
  • The hystrix fusing function needs to be actively turned on for it to take effect

5.2.4.3 discovery-consumer-service-service call

package com.zwc.consumer.feign;

import com.zwc.consumer.feign.fallback.FeignApiFallBack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @ClassName FeignApi
 * @Desc TODO   Call Api-Interface with Feign
 * @Date 2019/5/15 16:11
 * @Version 1.0
 */
@FeignClient(value = "say-hello", fallback = FeignApiFallBack.class)
public interface FeignApi {

    /*
     * @ClassName FeignApi
     * @Desc TODO   Call the remote hello() method
     * @Date 2019/5/15 16:17
     * @Version 1.0
     */
    @RequestMapping("/hello")
    String hello();

}
  • Specify which service to call with value = "say-hello" in the @FeignClient comment
  • say-hello is the provider's spring.application.name: application name
  • Through fallback = FeignApiFallBack in the @FeignClient comment. Class to specify the method to invoke when fusing
  • The FeignApiFallBack is the implementation class for this interface (FeignApi), and the corresponding implementation is the method invoked at the time of the fuse.
  • String hello();: You can see that this method is the one in the provider SayHelloController, but here it is defined as an interface
  • Note that you need to have the same return value, the same method name, and the same parameters as the provider

5.2.4.4 discovery-consumer-service - Fallback(FeignApiFallBack)

package com.zwc.consumer.feign.fallback;

import com.zwc.consumer.feign.FeignApi;
import org.springframework.stereotype.Component;

/*
 * @ClassName FeignApi
 * @Desc TODO   fallback
 * @Date 2019/5/20 23:21
 * @Version 1.0
 */
@Component
public class FeignApiFallBack implements FeignApi {

    /*
     * @ClassName FeignApiFallBack
     * @Desc TODO   Executes when a call to a remote hello() method fails
     * @Date 2019/5/20 23:31
     * @Version 1.0
     */
    @Override
    public String hello() {
        return "Oh! Call say-hello fail.";
    }

}
  • Delegate this class to Spring administration using the @Component annotation
  • Implement FeignApi interface, provide corresponding method when fusing

5.2.4.5 discovery-consumer-service-controller front-end controller (consumer service)

package com.zwc.consumer.controller;

import com.zwc.consumer.feign.FeignApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName FeignController
 * @Desc TODO   Call Api-Front End Controller with Feign
 * @Date 2019/5/15 16:18
 * @Version 1.0
 */
@RestController
public class FeignController {

    @Autowired(required = false)
    private FeignApi feignApi;

    /*
     * @ClassName FeignController
     * @Desc TODO   Call the remote hello() method
     * @Date 2019/5/15 16:20
     * @Version 1.0
     */
    @RequestMapping("/feign")
    public String feign(){
        return feignApi.hello();
    }

}
  • Assemble a Bean using the @Autowired annotation and invoke the service through the methods in the Bean
  • This exposes the interface by calling the provider's service

5.2.4.6 discovery-consumer-service-startup class

package com.zwc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DiscoveryConsumerServiceCoreApplication {

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

}
  • Adding the @EnableDiscoveryClient annotation indicates that the service is registering itself with the registry
  • Adding the @EnableFeignClients annotation indicates that the Feign function is turned on for remote calls

5.2.4.7 discovery-consumer-service - Start project

  1. Multiple access after successful project startup http://localhost:8080/feign
  2. You can find Hello Spring Cloud Alibaba output in turn!!! Port:8090 and Hello Spring Cloud Alibaba!!! port:8091
  3. Load balancing is now achieved
  4. Refresh again http://localhost:8848/nacos/#/serviceManagement (Registry) You can see that there is one more consumer at this time
service name Group name Number of clusters Number of instances Number of health instances Trigger protection threshold operation
service-feign DEFAULT_GROUP 1 1 1 false Details|Sample Code|Delete
say-hello DEFAULT_GROUP 1 2 2 false Details|Sample Code|Delete

5.3 service Project-Project Structure

springcloudalibaba-nacos-discovery/discovery-service/
├── discovery-consumer-service
│   ├── discovery-consumer-service-api
│   ├── discovery-consumer-service-core
│   ├── mvnw
│   ├── mvnw.cmd
│   └── pom.xml
├── discovery-flyway-service
│   ├── mvnw
│   ├── mvnw.cmd
│   ├── pom.xml
│   └── src
├── discovery-master-service
│   ├── mvnw
│   ├── mvnw.cmd
│   ├── nacos-1.2.1
│   └── pom.xml
├── discovery-provider-first-service
│   ├── discovery-provider-first-service-api
│   ├── discovery-provider-first-service-core
│   ├── mvnw
│   ├── mvnw.cmd
│   └── pom.xml
├── discovery-provider-second-service
│   ├── discovery-provider-second-service-api
│   ├── discovery-provider-second-service-core
│   ├── mvnw
│   ├── mvnw.cmd
│   └── pom.xml
├── mvnw
├── mvnw.cmd
└── pom.xml

6. Open the project using IntelliJ IDEA

  1. Download projects from GitHub to your local location
  2. Open IntelliJ IDEA
  3. Click File -> Open
  4. Open the project directory you downloaded locally
  5. springcloudalibaba-nacos-discovery (choose to open this project)
  6. If you have a higher version of IntelliJ IDEA, you will be prompted in the lower right corner that some projects can be imported, so select one-click to import.
  7. If it is a lower version of IntelliJ IDEA, import it manually
  8. Click on the right Maven Projects entry
  9. Click + (Add Maven Projects)
  10. Select the POM for the discovery-commons project and the discovery-service project, respectively. XML file, click the Open button

Hope to help you

over




Tags: Spring Boot Spring Cloud Nacos

Posted by tr0gd0rr on Wed, 01 Jun 2022 04:50:55 +0530