SpringCloudAlibaba 2021.0.1 – Complete project construction (Nacos + OpenFeign + Getway + Sentinel)

Table of Contents

1. Complete construction of SpringCloudAlibaba project

1.1. Initialization project

1.1.1. Create project

1.1.2. Configure the pom.xml of the parent project

1.1.3. Create submodules

1.2. user microservice

1.2.1. Configuration pom.xml

1.2.2. Create application.yml configuration file

1.2.3. Create startup class

1.2.4. Testing

1.3. product microservice

1.3.1. Configuration pom.xml

1.3.2. Create application.yml configuration file

1.3.3. Create startup class

1.3.4. Testing

1.4. Introduce OpenFeign to make remote calls

1.4.1. Introducing dependencies

1.4.2. Implement remote calling

1.5. User microservice integration Sentinel

1.5.1. Introducing sentinel dependency

1.5.2. Configure sentinel in application.yml

1.5.3. Testing

1.6. Gateway microservice

1.6.1. Configuration pom.xml

1.6.2. Create application.yml and configure the gateway

1.6.3. Create startup class

1.6.4. Testing

1.7. nacos implementation configuration center

1.7.1. Suggestions

1.7.2. Introduce nacos configuration center dependency

1.7.3. Create configuration on nacos


1. Complete construction of SpringCloudAlibaba project

1.1, initialization project

1.1.1, create project

a) First create an empty project with a customized name.

Ps:

1. Instead of creating an empty project, you can directly create a Maven project as the parent project, and then delete the src directory.

2. There is also a more convenient management method, which is to directly create a Spring Boot project as the parent project, so that you can introduce the dependencies in advance, and then only leave pom.xml, .gitinore, and .idea.

b) Create the parent module of the entire project under the empty project just now

c) The src under the parent project can be deleted, but it is useless.

d) Finally, directly use IDEA to open the parent project under the empty project (otherwise the Java file will not take effect)

1.1.2, configure the pom.xml of the parent project

a) Introducing dependencies If there is no syntax prompt, you can add the index like this

b) Configuration dependencies are as follows

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springcloud_alibaba_parent</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--Configuration version information-->
    <properties>
        <java.version>8</java.version>
        <spring-cloud.version>Hoxton.SR8</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.5.RELEASE</spring-cloud-alibaba.version>
    </properties>


    <!--parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
    </parent>

    <dependencies>
        <!--Basically every project needs logs-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <!--Management dependency specifications-->
    <dependencyManagement>
        <dependencies>

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

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

        </dependencies>
    </dependencyManagement>

</project>

Ps: The corresponding instructions for each version of SpringCloud Alibaba, SpringCloud, and SpringBoot are as follows

https://github.com/alibaba/spring-cloud-alibaba/wiki/Release Notes

For example, following the above documentation, here is an updated version style (stable).

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <java.version>1.8</java.version>
        <mybatis-spring-boot.version>2.3.1</mybatis-spring-boot.version>
        <mysql.version>5.1.49</mysql.version>
        <spring-cloud.version>2021.0.1</spring-cloud.version>
        <spring-cloud-alibaba.version>2021.0.1.0</spring-cloud-alibaba.version>
    </properties>

    <!--Maintain dependencies-->
    <dependencyManagement>
        <dependencies>

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

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

            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-spring-boot.version}</version>
            </dependency>

            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>

            <!--spring-boot-test-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

            <!--mybatis-test-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter-test</artifactId>
                <version>${mybatis-spring-boot.version}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

1.1.3, Create submodule

Create 4 modules under the parent project

  • user: User microservice (case).
  • product: product microservice (case).
  • gateway: gateway microservice.
  • model: module microservice, used to manage entity classes, public dependencies (for example, both user microservices and product microservices require spring web dependencies, then you only need to put this dependency in the model, and then introduce it in user and product respectively. model module)

1.2, user microservice

1.2.1, configuration pom.xml

The dependencies required by user microservices are as follows (introduced on demand):

 <dependencies>

        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--nacos-discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!--openFeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>


    </dependencies>

Ps: Don’t introduce so many at the beginning, introduce them as needed! Especially the nacos config configuration dependency, if it is introduced and not used, an error will be reported!

1.2.2, Create application.yml configuration file

Configure port number and nacos address

server:
  port: 8090

spring:
  application:
    name: user
  cloud:
    nacos:
      server-addr: localhost:8890

1.2.3. Create startup class

@SpringBootApplication
@EnableDiscoveryClient // nacos service discovery (can be omitted)
public class UserApplication {

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

}

Start the user microservice and you can see that the service exists in nacos

1.2.4, test

Create UserController as follows

@Slf4j
@RestController
@RequestMapping
public class UserController {

    @Value("${server.port}")
    private int port;

    @GetMapping("/user")
    public String user() {
        log.info("user ok! port={}", port);
        return "user ok! port=" + port;
    }

}

The postman test results are as follows:

1.3, product microservice

1.3.1, configuration pom.xml

The dependencies required by user microservices are as follows (introduced on demand):

 <dependencies>

        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--nacos-discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!--openFeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>


    </dependencies>

Ps: Don’t introduce so many at the beginning, introduce them as needed! Especially the nacos config configuration dependency, if it is introduced and not used, an error will be reported!

1.3.2, Create application.yml configuration file

Configure port number and nacos address

server:
  port: 8091

spring:
  application:
    name: product
  cloud:
    nacos:
      server-addr: localhost:8890

1.3.3. Create startup class

@SpringBootApplication
@EnableDiscoveryClient //can be omitted
public class ProductApplication {

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

}

Start the user microservice and you can see that the service exists in nacos

1.3.4, test

Create UserController as follows

@Slf4j
@RestController
@RequestMapping
public class UserController {

    @Value("${server.port}")
    private int port;

    @GetMapping("/user")
    public String user() {
        log.info("user ok! port={}", port);
        return "user ok! port=" + port;
    }

}

The postman test results are as follows:

1.4. Introducing OpenFeign for remote calling

1.4.1, introduce dependencies

Introduce the openfeign dependency into the user microservice (this is just an example, in actual development, it will be introduced as needed).

 <!--openFeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Note: Since higher versions of SpringCloud Feign (such as springcloud 2021.0.1) do not use Ribbon but spring-cloud-loadbalancer, you need to reference spring-cloud-loadbalancer or downgrade the version

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

1.4.2, implement remote call

a) Create a product microservice feign interface in the user microservice

@FeignClient("product")
public interface ProductClient {

    @GetMapping("/product")
    String product();

}

b) Open the feign client in the startup class

@SpringBootApplication
@EnableDiscoveryClient // nacos service discovery (can be omitted)
@EnableFeignClients // Enable openfeign remote calling
public class UserApplication {

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

}

c) If it is a higher version of SpringCloud, you need to use SpringCloud LoadBalencer for load balancing.

Specifically add the @LoadBalancerClient annotation: Add the @LoadBalancerClient annotation on the Service class that calls the service, and specify the service name. In this way, the load balancer will select the appropriate service instance to call based on the configured properties. For example:

as follows:

@FeignClient(value = "service-name", configuration = LoadBalancerClientConfig.class)
public interface MyService {
    @LoadBalanced //Enable load balancing
    @GetMapping("/endpoint")
    String getEndpointData();
}

d) Make remote calls in UserController.

 @GetMapping("/user")
    public String user() {
        log.info("user ok! port={}", port);
        //remote call product
        String result = productClient.product();
        log.info("Remote call result: {}", result);
        return "user ok! port=" + port;
    }

The execution results are as follows:

1.5, user microservice integration Sentinel

1.5.1, introduce sentinel dependency

Introduce sentinel dependency into user microservice

 <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

1.5.2. Configure sentinel in application.yml

server:
  port: 8090

spring:
  application:
    name: user
  cloud:
    nacos:
      server-addr: localhost:8890
    sentinel:
      eager: true # Trigger sentinel immediately
      transport:
        dashboard: localhost:8891

1.5.3, test

a) Open sentinel console

b) Set the flow control rule to 1 second / 3 clicks.

c) Current limiting takes effect after testing

1.6, Gateway Microservice

1.6.1, configuration pom.xml

 <dependencies>

        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

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

    </dependencies>

If you are using a higher version of springcloud (for example, 2020.1.0), then the ribbon load balancing in the gateway has been removed, so you need to introduce springcloud loadbalancer as the load balancing of the gateway.

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

After introducing this dependency, cache warnings may be reported. Just introduce two dependencies.

 <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

1.6.2. Create application.yml and configure the gateway

server:
  port: 18080

spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: localhost:8890
    gateway:
      routes:
        - id: users_router
          # uri: http://localhost:9090 no load balancing
          uri: lb://user # lb represents load balancing
          predicates:
            -Path=/user

        - id: products_router
          #uri: http://localhost:9091
          uri: lb://product
          predicates:
            -Path=/product

In addition, if the configuration is cross-domain, it is as follows:

server:
  port: 18080

spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: localhost:8890
    gateway:
      routes:
        - id: users_router
          # uri: http://localhost:9090 no load balancing
          uri: lb://user # lb represents load balancing
          predicates:
            -Path=/user

        - id: products_router
          #uri: http://localhost:9091
          uri: lb://product
          predicates:
            -Path=/product
      globalcors: # Global cross-domain processing
        cors-configurations:
          '[/**]':
            allowedMethods: "*"
            allowedHeaders: "*"
            allowedOriginPatterns: "*" # 2.4 and later versions cannot be written as allowedOrigin
            allowCredentials: true

1.6.3, Create startup class

@SpringBootApplication
@EnableDiscoveryClient //(can be omitted)
public class GatewayApplication {

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

}

1.6.4, test

Access the user microservice and product microservice through the gateway

1.7, nacos implementation configuration center

1.7.1, Suggestion

Generally speaking, only three components are used in the initial development of the project: nacos registration center, gateway, and openFeign declarative remote calling.

It is worth noting that you should not use the nacos configuration center before the initial project development is completed for the following reasons:

  1. Because once you need to change any configuration, you still need to open nacos to modify it, which is easy to distract. It is recommended to use the application.yml in the project first.
  2. If you introduce dependencies but do not configure them, an error will be reported.

1.7.2, introduce nacos configuration center dependency

Here we take the user microservice as an example and introduce the nacos configuration center dependency.

 <!--nacos config-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

Note: SpringCloudAlibaba later versions (such as springcloud-alibaba 2021.0.1.0) will ignore the bootstrap.yml file, so the following configuration needs to be added

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>

1.7.3, Create configuration on nacos

a) Create a namespace on nacos

b) Select the newly created namespace demo1 in configuration management

c) Create a new configuration file, and then put all the configuration information in the user microservice yml on nacos for unified management, and then click Publish

Ps: Do not have comments in the configuration content! Sinkhole!

d) Create the bootstrap.yml configuration file to pull the configuration file on nacos.

# Who is the remote configuration center?
spring:
  cloud:
    nacos:
      server-addr: localhost:8890
      config:
        # Which namespace in nacos to use
        namespace: 0e48f075-ad88-4700-a422-d315a81f9ced
        # Which group in nacos to use
        group: user
        #Which dataId in nacos to use 1.name + file suffix 2.file name + env + suffix
        name: user-prod
        file-extension: yml

Ps: The original application.yml can be deleted.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skills treeHomepageOverview 16,929 people are learning the system