Spring cloud learning notes

Take grain College as an example

Link: Shang Silicon Valley_ Cereal Academy - micro service + whole stack online education practical project_ Beep beep beep_ bilibili

1, What is micro service

1. Origin of microservices

Microservice architecture style is a way to use a set of small services to develop a single application. Each service runs in its own process and communicates using lightweight mechanisms, usually HTTP API s. These services are built based on business capabilities and can be deployed independently through automatic deployment mechanisms. These services are implemented in different programming languages, Different data storage technologies at the first level and maintain a minimum of centralized management

2. Why do you need microservices

In the traditional IT industry, software is mostly a stack of various independent systems. In summary, the problems of these systems are poor scalability, low reliability and high maintenance cost. Later, SOA Service is introduced. However, due to the early use of bus mode in SOA, this bus mode is strongly bound to a certain technology stack, such as J2EE. This makes it difficult to connect the legacy systems of many enterprises, the switching time is too long, the cost is too high, and the convergence of the stability of the new system also takes some time.  

3. Differences between microservices and monomer architectures

(1) All modules of the single architecture are coupled together, resulting in a large amount of code and difficult maintenance.

          Each module of microservice is equivalent to a separate project, the amount of code is significantly reduced, and the problems encountered are relatively easy to solve.

(2) All modules of the single architecture share a database, and the storage mode is relatively single.

          Each module of microservice can use different storage methods (for example, some use redis, some use mysql, etc.), and the database is also a database corresponding to a single module.

(3) The technology used in the development of all modules of single architecture is the same.

          Each module of microservice can use different development technologies, and the development mode is more flexible.  

4. Essence of micro service

(1) In fact, the key to microservices is not just the microservices themselves, but the system should provide a set of basic architecture, which enables microservices to be deployed, run and upgraded independently. Moreover, this system architecture also makes microservices and microservices "loosely coupled" in structure and unified in function. This so-called "unified whole" shows a unified style interface, unified authority management, unified security policy, unified online process, unified log and audit methods, unified scheduling mode, unified access entrance and so on.
(2) The purpose of microservices is to effectively split applications and realize agile development and deployment.
(3) Microservices advocate the idea that teams should be inter operated, not integrated. Inter operate defines the boundaries and interfaces of the system, makes the whole stack in a team, and makes the team autonomous. The reason is that if the team is established in this way, the communication cost will be maintained within the system, each subsystem will be more cohesive, the mutual dependency coupling can be weakened, and the cross system communication cost can be reduced.

5. What kind of projects are suitable for microservices

Microservices can be divided according to the independence of business functions. If the services provided by the system are very low-level, such as operating system kernel, storage system, network system, database system, etc., these systems are low-level, and there is a close cooperation relationship between functions. If they are forcibly divided into smaller service units, the integration workload will rise sharply, Moreover, this artificial cutting can not bring real business isolation, so it can not be deployed and run independently, so it is not suitable to be made into micro services.

6. What is Spring Cloud

Spring Cloud is a collection of frameworks. It makes use of the development convenience of Spring Boot to simplify the development of distributed system infrastructure, such as service discovery, service registration, configuration center, message bus, load balancing, fuse, data monitoring, etc., which can be started and deployed with one click with the development style of Spring Boot. Spring does not repeatedly manufacture wheels. It just combines the relatively mature and practical service frameworks developed by various companies, re encapsulates them through the SpringBoot style, shields the complex configuration and implementation principles, and finally leaves a set of distributed system development toolkit that is easy to understand, deploy and maintain for developers

7. What is the relationship between spring cloud and Spring Boot

Spring Boot is a set of rapid configuration scaffolds of spring, which can quickly develop a single micro service based on Spring Boot. Spring Cloud is a development tool based on Spring Boot; Spring Boot focuses on a single micro service individual that is fast and easy to integrate. Spring Cloud focuses on the overall service governance framework; Spring Boot uses the concept that default is greater than configuration. Many integration schemes have been selected for you. You can't configure without configuration. A large part of Spring Cloud is implemented based on Spring Boot and must be developed based on Spring Boot. You can use Spring Boot alone to develop projects, but Spring Cloud is inseparable from Spring Boot.

8.Spring Cloud related basic service components

Service discovery - Netflix Eureka    (Nacos)

Service invocation - Netflix Feign  

Fuse - Netflix Hystrix  

Service gateway - Spring Cloud    GateWay  

Distributed configuration - Spring Cloud Config   (Nacos)

Message bus - Spring Cloud Bus   (Nacos)

9. Version of spring cloud

Spring Cloud does not have a familiar digital version number, but corresponds to a development code.

Cloud codeBoot Version (train)Boot Version (tested)lifecycle
Angle1.2.xincompatible with 1.3EOL in July 2017
Brixton1.3.x1.4.xJuly 2017
Camden1.4.x1.5.x-
Dalston1.5.xnot expected 2.x-
Edgware1.5.xnot expected 2.x-
Finchley2.0.xnot expected 1.5.x-
Greenwich2.1.x
Hoxton2.2.x

The development code seems to have no rules, but in fact, the initial letters are in order. For example, Dalston version can be referred to as version D, and the corresponding Edgware version can be referred to as version E.

Small version

Spring Cloud mini versions are divided into:

SNAPSHOT: SNAPSHOT version, which can be modified at any time

M: MileStone, M1 indicates the first MileStone version. Generally, PRE is marked at the same time, indicating the preview version.

SR: Service Release, SR1 refers to the first official version, and GA: (generalyavailable) is generally marked at the same time, indicating a stable version

2, Nacos

1. Basic concepts

(1)Nacos   It is a new open source project launched by Alibaba. It is a dynamic service discovery, configuration management and service management platform that is easier to build cloud native applications. Nacos   Dedicated to helping you discover, configure, and manage microservices. Nacos   It provides a set of easy-to-use feature sets to help you quickly realize dynamic service discovery, service configuration, service metadata and traffic management. Nacos   Help you build, deliver, and manage your microservice platform more quickly and easily.   Nacos   It is to build a modern application architecture centered on "service"   (e.g. microservice paradigm, cloud native paradigm)   Service infrastructure.

(2) Common registries:

1. Eureka (native, 2.0 encounters performance bottleneck and stops maintenance)

2. Zookeeper (support, professional independent products. E.g. dubbo)

3. Consul (native, GO language development)

4. Nacos

be relative to   Spring Cloud Eureka   Come on, Nacos   More powerful. Nacos = Spring Cloud Eureka + Spring Cloud Config

Nacos   Can be with   Spring, Spring Boot, Spring Cloud   Integrated and can replace   Spring Cloud Eureka, Spring Cloud Config

-   adopt   Nacos Server   and   spring-cloud-starter-alibaba-nacos-discovery   Realize the registration and discovery of services.

(3) Nacos is a middleware with service as the main service object. Nacos supports all mainstream service discovery, configuration and management.

Nacos mainly provides the following four functions:

one   Service discovery and service health monitoring

two   Dynamic configuration service

three   Dynamic DNS Service

four   Service and metadata management

(4) Nacos structure diagram

 

  2.nacos download and installation

(1) Download address: https://github.com/alibaba/nacos/releases

(2) Start the nacos service

- Linux/Unix/Mac

Start command (standalone stands for stand-alone mode, non cluster mode)

Start command: sh startup.sh -m standalone

- Windows

Startup command: cmd startup.cmd   Or double-click the startup.cmd run file.

visit: http://localhost:8848/nacos

User name and password: nacos/nacos

  2, Service registration

1. Configure pom dependency of Nacos client

<!--Service registration-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. Add service configuration information

Configure application.properties and add the configuration information of registering the Nacos service in the client micro service

# nacos service address
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

3. Add Nacos client annotation

Add an annotation in the client microservice startup class

@EnableDiscoveryClient

4. Start the client micro service

Start registry

Start the registered microservices, and you can see the registered microservices in the Nacos service list

 

  3, Feign

1. Basic concepts

  • Feign is a declarative and templated HTTP client developed by Netflix. Feign can help us call HTTP API more quickly and gracefully
  • Feign supports multiple annotations, such as feign's own annotations or JAX_RS annotation, etc
  • Spring Cloud has enhanced Feign, enabling Feign to support Spring MVC annotations and integrate Ribbon and Eureka, making Feign more convenient to use
  • Spring Cloud Feign is based on Netflix   Feign implementation integrates Spring Cloud Ribbon and Spring Cloud Hystrix. In addition to providing the powerful functions of the two, it also provides a declarative way of defining Web service clients
  • Spring cloud feign helps us define and implement the definition of dependent service interfaces. Under the implementation of spring cloud feign, you only need to create an interface and configure it with annotations to complete the interface binding of the service provider, which simplifies the development of self encapsulating the service call client when using the Spring Cloud Ribbon.

  2. Implement service invocation

(1) Add pom dependency

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

(2) Add annotations to the startup class on the caller side

@EnableFeignClients

(3) Create packages and interfaces

Create client package

The @FeignClient annotation is used to specify which service to invoke the function, which is consistent with the name of the service being invoked.

@The GetMapping annotation is used to map the address of the invoked microservice.

@The PathVariable annotation must specify the parameter name, otherwise an error will occur

@The Component annotation prevents the idea from reporting an error when injecting CodClient in other locations

@FeignClient("service-vod")
@Component
public interface VodClient {
    @DeleteMapping(value = "/eduvod/vod/video/{videoId}")
    public R removeVideo(@PathVariable("videoId") String videoId);
}

(4) Invoke microservice

Calling client in call end serviceImpl

4, Hystrix

1. Basic concepts
(1) Spring Cloud call interface procedure

Spring Cloud   In terms of interface calls, the following components will be used:

Feign  -----> Hystrix  —> Ribbon  —> Http Client(apache http components   perhaps   Okhttp)   The specific interaction process is shown in the figure below:

  •   Interfaced request call when calling the interface modified by @ FeignClient annotation, convert the request into Feign's request instance feign.Request within the framework and submit it to the Feign framework for processing
  • Feign  : Transformation request feign is a lightweight framework for HTTP request invocation. It can invoke HTTP requests in the way of Java interface annotation, encapsulating the HTTP invocation process.
  • Hystrix: fuse handling mechanism   The call relationship of Feign will be intercepted by the hystrix agent. For each Feign call request, hystrix will package it as HystrixCommand and participate in the flow control and fusing rules of hystrix. If the request determines that the fuse needs to be blown, hystrix will blow directly, throw an exception, or use FallbackFactory to return the fuse Fallback result; If passed, the call request is passed to the Ribbon component.
  • Ribbon: service address selection   After the request is delivered to the ribbon, the ribbon will select the appropriate service instance from the list according to the service list maintained by itself and the service quality of the service, such as average response time and Load, combined with specific rules, select the machine, and then deliver the information request of the machine instance to the Http Client, HttpClient client to execute the real Http interface call;
  • HttpClient  : The Http client actually executes the Http call. If the service address has been specified according to the request passed by the upper Ribbon, the Http client starts to execute the real Http request

(2) Hystrix concept

Hystrix   It is used by distributed systems to provide delay and fault tolerance functions to ensure that complex distributed systems can still have their elasticity in the face of inevitable failure.

For example, there are many services in the system. When some services are unstable, the user threads using these services will be blocked. If there is no isolation mechanism, the system may hang up at any time, resulting in great risks. Spring cloud uses Hystrix components to provide circuit breaker, resource isolation and self-healing functions. The following figure shows that service B triggered the circuit breaker to prevent cascading failure

  2.feign is used in combination with Hystrix

(1) Add dependency in pom

    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <!--hystrix Dependency, mainly with  @HystrixCommand -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--Service registration-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--Service call-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

(2)   Add a hystrix configuration to the configuration file

#Turn on the fuse mechanism
feign.hystrix.enabled=true
# Set the hystrix timeout, which is 1000ms by default
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000

(3) Create the implementation class of fuse in the client package

@Component
public class VodFileDegradeFeignClient implements VodClient {
    @Override
    public R removeVideo(String videoId) {
        return R.error().message("time out");
    }

    @Override
    public R removeVideoList(List videoIdList) {
       return R.error().message("time out");
    }
}

(4) Add annotation

@FeignClient(name = "service-vod", fallback = VodFileDegradeFeignClient.class)

5, Gateway gateway

1. Introduction to API gateway

API   The reason for the emergence of the gateway is the emergence of the microservice architecture. Different microservices generally have different network addresses, and external clients may need to call the interfaces of multiple services to complete a business requirement. If the client is allowed to communicate directly with each microservice, there will be the following problems:

(1) The client will request different microservices many times, which increases the complexity of the client.

(2) There are cross domain requests, which are relatively complex to process in certain scenarios.

(3) Authentication is complex, and each service needs independent authentication.

(4) It is difficult to refactor. With the iteration of the project, it may be necessary to re divide the microservices. For example, you might merge multiple services into one or split a service into multiple. If the client communicates directly with the microservice, the refactoring will be difficult to implement.

(5) Some microservices may use firewalls  /  Browser unfriendly protocol, direct access will be difficult.

These problems can be solved with the help of   API   Gateway solution. API   The gateway is an intermediate layer between the client and the server. All external requests go through the gateway first   API   Gateway layer. That is, API   In terms of implementation, business logic is more considered, while security, performance and monitoring can be entrusted to   API   Gateway, which not only improves business flexibility, but also does not lack security

2.Spring Cloud Gateway

Spring Cloud gateway is a gateway officially developed by spring based on Spring 5.0, Spring Boot2.0, Project Reactor and other technologies. Spring Cloud gateway aims to provide a simple, effective and unified API routing management method for microservice architecture. As a gateway in Spring Cloud ecosystem, Spring Cloud gateway aims to replace Netflix Zuul, which not only provides a unified routing method, It also provides the basic functions of the gateway based on the Filer chain, such as security, monitoring / embedding point, current limiting, etc

  3. Core concepts of spring cloud gateway

The gateway provides API full hosting services and rich API management functions to assist enterprises in managing large-scale APIs to reduce management costs and security risks, including protocol adaptation, protocol forwarding, security policies, anti brushing, traffic, monitoring logs, etc. Generally speaking, the URL or interface information exposed by the gateway is collectively referred to as routing information. If you have developed gateway middleware or used Zuul, you will know that the core of the gateway is Filter and Filter Chain (Filter responsibility chain). Sprig Cloud Gateway also has the concepts of routing and Filter. Here are some important concepts in Spring Cloud Gateway.

(1) Routing. Routing is the most basic part of the gateway. The routing information consists of an ID, a destination URL, a set of assertions and a set of filters. If the asserted route is true, the requested URL and configuration match

(2) Assertions. Assertion function in Java 8. The input type of the assertion function in the Spring Cloud Gateway is ServerWebExchange in the spring 5.0 framework. The assertion function in Spring Cloud Gateway allows developers to define and match any information from http request, such as request header and parameters.

(3) Filter. A standard Spring webFilter. There are two types of filters in Spring cloud gateway: Gateway Filter and Global Filter. The filter will modify the request and response

  As shown in the figure above, the Spring cloud Gateway sends a request. Then, find the route matching the request in the Gateway Handler Mapping and send it to the Gateway web handler. The Handler sends the request to our actual service through the specified filter chain, executes the business logic, and then returns.

4. Use

(1) Introducing dependencies in pom.xml

<dependencies>
    <dependency>
        <groupId>com.atguigu</groupId>
        <artifactId>common_utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!--gson-->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>
    <!--Service call-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
</dependencies>

(2) Write the application.properties configuration file

# Service port
server.port=8222
# service name
spring.application.name=service-gateway
# nacos service address
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#Using service discovery routing
spring.cloud.gateway.discovery.locator.enabled=true
#Service route name lowercase
#spring.cloud.gateway.discovery.locator.lower-case-service-id=true
#Set routing id
spring.cloud.gateway.routes[0].id=service-acl
#Set the uri of the route
spring.cloud.gateway.routes[0].uri=lb://service-acl
#Set the route assertion. The agent servicerId is the / auth / path of auth service
spring.cloud.gateway.routes[0].predicates= Path=/*/acl/**
#Configure service edu service
spring.cloud.gateway.routes[1].id=service-edu
spring.cloud.gateway.routes[1].uri=lb://service-edu
spring.cloud.gateway.routes[1].predicates= Path=/eduservice/**
#Configuring the service UCenter service
spring.cloud.gateway.routes[2].id=service-ucenter
spring.cloud.gateway.routes[2].uri=lb://service-ucenter
spring.cloud.gateway.routes[2].predicates= Path=/ucenterservice/**
#Configuring the service UCenter service
spring.cloud.gateway.routes[3].id=service-cms
spring.cloud.gateway.routes[3].uri=lb://service-cms
spring.cloud.gateway.routes[3].predicates= Path=/cmsservice/**
spring.cloud.gateway.routes[4].id=service-msm
spring.cloud.gateway.routes[4].uri=lb://service-msm
spring.cloud.gateway.routes[4].predicates= Path=/edumsm/**
spring.cloud.gateway.routes[5].id=service-order
spring.cloud.gateway.routes[5].uri=lb://service-order
spring.cloud.gateway.routes[5].predicates= Path=/orderservice/**
spring.cloud.gateway.routes[6].id=service-order
spring.cloud.gateway.routes[6].uri=lb://service-order
spring.cloud.gateway.routes[6].predicates= Path=/orderservice/**
spring.cloud.gateway.routes[7].id=service-oss
spring.cloud.gateway.routes[7].uri=lb://service-oss
spring.cloud.gateway.routes[7].predicates= Path=/eduoss/**
spring.cloud.gateway.routes[8].id=service-statistic
spring.cloud.gateway.routes[8].uri=lb://service-statistic
spring.cloud.gateway.routes[8].predicates= Path=/staservice/**
spring.cloud.gateway.routes[9].id=service-vod
spring.cloud.gateway.routes[9].uri=lb://service-vod
spring.cloud.gateway.routes[9].predicates= Path=/eduvod/**
spring.cloud.gateway.routes[10].id=service-edu
spring.cloud.gateway.routes[10].uri=lb://service-edu
spring.cloud.gateway.routes[10].predicates= Path=/eduuser/**

yml file

server:
  port: 8222
spring:
  application:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
      - id: SERVICE-ACL
        uri: lb://SERVICE-ACL
        predicates:
        - Path=/*/acl/** # Path matching
      - id: SERVICE-EDU
        uri: lb://SERVICE-EDU
        predicates:
        - Path=/eduservice/** # Path matching
      - id: SERVICE-UCENTER
        uri: lb://SERVICE-UCENTER
        predicates:
        - Path=/ucenter/** # Path matching
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

(3) Gateway related configuration

① Gateway solves cross domain problems

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

② Global Filter

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //The api interface of grain college, the verification user must log in
        if(antPathMatcher.match("/api/**/auth/**", path)) {
            List<String> tokenList = request.getHeaders().get("token");
            if(null == tokenList) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
//                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
//                if(!isCheck) {
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response);
//                }
            }
        }
        //Internal service interface, external access is not allowed
        if(antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response);
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "Authentication failed");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //Specify the code, otherwise Chinese garbled code will appear in the browser
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}

6, Introduction to configuration center

1,Spring Cloud Config

Spring Cloud Config   It provides the support scheme of server and client for the external configuration of distributed system. On the configured server side, you can manage the central location of external properties for applications in all environments. Spring Environment in client and server concepts   and   PropertySource   Keep abstractions synchronized,   They are ideal for spring applications, but can be used with applications running in any language. As applications move from development to testing through production in the deployment pipeline, you can manage the configuration between these environments and ensure that applications have everything they need to run when migrating. The default implementation of the server storage back-end uses git, so it can easily support the configuration environment of marked version, and can be accessed by various tools for managing content. It's easy to add alternative implementations and plug them in with spring configuration.

Spring Cloud Config   It includes two parts: client and server. The server provides the storage of configuration files and provides the contents of configuration files in the form of interface. The client obtains data through the interface and initializes its own application according to this data. Spring cloud uses git or svn to store configuration files. Git is used by default.

2. Replace Config with Nacos

Nacos   Can be with   Spring, Spring Boot, Spring Cloud   Integrated and can replace   Spring Cloud Eureka, Spring Cloud Config. adopt   Nacos Server   and   spring-cloud-starter-alibaba-nacos-config   Realize the dynamic change of configuration.

(1) Application scenario

In the process of system development, developers usually separate some parameters and variables that need to be changed from the code for independent management and exist in the form of independent configuration files. The purpose is to make static system artifacts or deliverables (such as   WAR,JAR   Package, etc.) better adapt to the actual physical operating environment. Configuration management is generally included in the process of system deployment and is completed by the system administrator or operation and maintenance personnel. Configuration change is an effective means to adjust the behavior of the system during operation.

If the unified configuration center is not used in the microservice architecture, the following problems exist:

-   The configuration files are scattered in various projects, which is inconvenient to maintain

-   Configure content security and permissions

-   After updating the configuration, the project needs to be restarted

nacos configuration center: centralized management of system configuration (editing, storage and distribution), dynamic update without restart, rollback of configuration (change management, historical version management, change audit) and other configuration related activities.

3. Read the configuration file of the Nacos configuration center

① Create unified profile in Nacos

Click the Create button

  Enter configuration information

 

 

Data ID   The complete rule format is as follows

${prefix}-${spring.profile.active}.${file-extension}

- prefix   spring.application.name is configured for the project by default   The value of (i.e. Nacos provider) can also be configured through the configuration item   spring.cloud.nacos.config.prefix.

-   spring.profiles.active=dev   It is the corresponding to the current environment   profile.   Note: when spring.profiles.active   When null, the corresponding connector  -  Will not exist, dataId   The splicing format of becomes ${prefix}. ${file extension}

- file-exetension   To configure the data format of the content, you can use the configuration item spring.cloud.nacos.config.file-extension   To configure. Currently only supported   properties   and   yaml   Type.

Take the service statistics module as an example

(1) Introduce dependency in service

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

  (2) Create the bootstrap.properties configuration file

#Configuration center address
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
#spring.profiles.active=dev
# This configuration affects the dataId in the unified configuration center
spring.application.name=service-statistics

 

Supplement: loading order of springboot configuration file

In fact, yml and properties files have the same principle, and either yml or properties exist in a project. yml is recommended, which is more concise.

bootstrap and application
(1) Loading order
This mainly describes the loading sequence of application and bootstrap.

bootstrap.yml (bootstrap.properties) is loaded first
Load after application.yml (application.properties)
bootstrap.yml is used for the boot phase of the application context.

bootstrap.yml is loaded by the parent Spring ApplicationContext.

The parent ApplicationContext is loaded before using application.yml.

(2) Configuration difference
Both bootstrap.yml and application.yml can be used to configure parameters.

bootstrap.yml can be understood as some system level parameter configurations, which are generally unchanged.
application.yml can be used to define the application level.

Namespace switching environment

In actual development, there are usually multiple sets of different environments (only public by default). At this time, different environments can be created according to the specified environment   namespce, for example, three different environments: development, test and production, use one set   nacos   The following three different clusters can be built   namespace. In order to achieve multi environment isolation.

Create namespace

 

  By default, there is only public, and the dev, test, and prod namespaces are created

 

Clone configuration

(1) Switch to the configuration list:

 

 

You can find that there are four namespaces: public (default) and three namespaces (prod, dev and test) added by ourselves. You can click to view the configuration file under each namespace. Of course, there is only one configuration under public.

By default, the project will be found in public   Service name. properties file.

Next, also add a nacos-provider.properties configuration in the dev namespace. There are two ways:

First, switch to the dev namespace and add a new configuration file. Disadvantages: similar items need to be configured repeatedly in each environment

Second, add and modify the configuration directly through clone. recommend

 

  Click Edit: modify the configuration content and change the port number to 8013 for differentiation

 

  In the project module, modify bootstrap.properties and add the following configuration

spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.profiles.active=dev
# This configuration affects the dataId in the unified configuration center, which has been configured before
spring.application.name=service-statistics
spring.cloud.nacos.config.namespace=13b5c197-de5b-47e7-9903-ec0538c9db01

  The value of namespace is:

 

Multi profile loading

In some cases, multiple configuration files need to be loaded. Suppose there are three configuration files under the dev namespace: service-statistics.properties, redis.properties and jdbc.properties

 

  Add configuration, load multiple configuration files

 

spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.profiles.active=dev
# This configuration affects the dataId in the unified configuration center, which has been configured before
spring.application.name=service-statistics
spring.cloud.nacos.config.namespace=13b5c197-de5b-47e7-9903-ec0538c9db01
spring.cloud.nacos.config.ext-config[0].data-id=redis.properties
# Enable dynamic refresh configuration, otherwise the configuration file will be modified and the project will not be aware of it
spring.cloud.nacos.config.ext-config[0].refresh=true
spring.cloud.nacos.config.ext-config[1].data-id=jdbc.properties
spring.cloud.nacos.config.ext-config[1].refresh=true

Tags: Spring Cloud Microservices Cloud Native

Posted on Sat, 06 Nov 2021 08:58:21 -0400 by bfranco