Mall-Learning Organize-Basic-Distributed Components (3)

Table of contents

I. Introduction

insert image description here
Build a distributed basic environment, mainly registration center, configuration center, and gateway.

In distributed development, each microservice should register itself with the registration center when it goes online. The advantage of this is that if the order service wants to call commodity services, you can go to the registration center to see which commodity services are registered. No. 1 and No. 2, you can choose an available commodity service to call remotely.
There are many configurations for each microservice. When a commodity service is deployed on ten machines, it needs to be changed ten times to change one configuration. If it is placed in the configuration center, it only needs to be changed once, and the configuration is managed centrally.
All front-end requests first pass through the gateway, authentication, filtering, routing, etc., and the gateway requests the corresponding services.

二、Spring Cloud&Spring Cloud Alibaba

1. Introduction to Spring Cloud and Spring Cloud Alibaba

https://spring.io/projects/spring-cloud
The previous Spring Cloud used Eureka of Spring Cloud Netfix as the registration center, Spring Cloud Config as the configuration center, Spring Cloud Zuul as the gateway, and Hystrix as the circuit breaker protection.

Spring Cloud Alibaba is committed to providing a one-stop solution for microservice development. This project contains the necessary components to develop distributed application microservices, so that developers can easily use these components to develop distributed application services through the Spring Cloud programming model.
Relying on Spring Cloud Alibaba, you only need to add some annotations and a small amount of configuration to connect Spring Cloud applications to Alibaba microservice solutions, and quickly build distributed application systems through Alibaba middleware.
https://github.com/alibaba/spring-cloud-alibaba

2. Why use Spring Cloud Alibaba

Several major pain points of SpringCloud.
Some components of SpringCloud stop maintenance and update, which brings inconvenience to development. Some environments of SpringCloud are complicated to build and there is no perfect visual interface. We need a lot of
secondary development and customization
. low



Combined with SpringCloud Alibaba, our final technical solution:
SpringCloud Alibaba - Nacos: Registry (service discovery/registration)
SpringCloud Alibaba - Nacos: Configuration Center (dynamic configuration management) SpringCloud
- Ribbon: Load balancing SpringCloud -
Feign: Declarative HTTP client (calling remote services)
SpringCloud Alibaba - Sentinel: Service fault tolerance (current limiting, downgrading, circuit breaker) SpringCloud -
Gateway: API Gateway (webfl ux programming mode)
SpringCloud - Sleuth: call chain monitoring
SpringCloud Alibaba - Seata: the original Fescar, that is, distributed transaction solutions

3. Version selection

Since the interfaces and annotations of the Actuator module have changed a lot between Spring Boot 1 and Spring Boot 2, and the
upgrade of spring-cloud-commons from version 1.xx to version 2.0.0 has also undergone major changes, we adopt the version that is
consistent with the version number of SpringBoot:
 Version 1.5.x is applicable to Spring Boot 1.5.x
 Version 2.0.x is applicable to Spring Boot 2.0.x
 2 The .1.x version is for Spring Boot 2.1.x
insert image description here

4. Dependencies in the project

在 common 项目中引入如下。进行统一管理
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

insert image description here

3. Spring Cloud Alibaba-Nacos as a registration center

insert image description here

1、Nacos

It is a dynamic service discovery, configuration management and service management platform open sourced by Alibaba that makes it easier to build cloud-native applications
. He is written in java. Need to rely on java environment
Nacos document address: https://nacos.io/zh-cn/docs/quick-start.html

1) Download nacos-server

https://github.com/alibaba/nacos/releases
insert image description here

2) Start nacos-server

 Double-click the startup.cmd file in the bin
 Visit http://localhost:8848/nacos/
 Use the default nacos/nacos to log in
insert image description here

3) Register the microservice in nacos

1. First, modify the pom.xml file and import Nacos Discovery Starter.

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

insert image description here

2. In the application's /src/main/resources/application.yml configuration file

Configure the Nacos Server address in the file
insert image description here

insert image description here

insert image description here

3. Use @EnableDiscoveryClient to enable the service registration discovery function

insert image description here

4. Start the application and observe whether the nacos service list has been registered with the service

insert image description here
insert image description here
insert image description here

5. Each service has been configured with the configuration of the registration center and verified, otherwise it will be difficult to find problems in the follow-up

四、Spring Cloud Feign

1 Introduction

Feign is a declarative HTTP client whose purpose is to make remote calls easier. Feign provides templates for HTTP requests. By writing simple interfaces and inserting annotations, you can define the parameters, format, address and other information of HTTP requests.
Feign integrates Ribbon (load balancing) and Hystrix (service fusing), so that we no longer need to explicitly use these two components.
SpringCloudFeign extends the support for SpringMVC annotations on the basis of NetflixFeign. Under its implementation, we only need to create an interface and configure it with annotations to complete the interface binding to the service provider. This simplifies the development of SpringCloudRibbon's self-encapsulated service call client.

2. use

1. Introduce dependencies

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

insert image description here

2. Enable the feign function, and declare which package the remote call interface is in

@EnableFeignClients(basePackages = “com.wxn.zhenyanmall.member.feign”)

insert image description here

3. Declare the remote interface

/*

  • Tell SpringCloud that this interface is a remote client
  • Which service coupon is called remotely
  • This remote service has many functions, which function to call
  • Just copy the service name of the interface to be called, and then modify the path and add /coupon/coupon/
    *If we call the membercoupons method of the CouponFeignService interface in this service,
  • It will first go to the registration center to find the location of the remote service coupon, and then call /coupon/coupon/member/list request, the corresponding method membercoupons
  • This implements the remote call
  • */

@FeignClient(“coupon”)

insert image description here

4. Test the remote call in the member

insert image description here

5. An error was reported when starting the member, because multiple versions of spring-boot were introduced

insert image description here

insert image description here

6. Remote call execution process

1. Write a normal interface in coupon

insert image description here

2. Add @EnableFeignClients(basePackages = “com.wxn.zhenyanmall.member.feign”) to the controller where the member wants to call other services remotely

insert image description here

3. Create an interface for remote calls

insert image description here

4. Call coupon interface in member

insert image description here

insert image description here

insert image description here

Five, Spring Cloud Alibaba Nacos as a configuration center

https://github.com/alibaba/spring-cloud-alibaba/blob/2022.x/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md

bootstrap.properties is loaded prior to application.properties

1. Pom.xml introduces Nacos Config Starter.

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

2. Configure in /src/main/resources/bootstrap.properties of the application

Configure Nacos Config metadata in the configuration file

spring.application.name=coupon
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
主要配置应用名和配置中心地址

insert image description here
If the configuration center has the coupon.properties configuration, it will read the configuration inside, and the configuration name is generally the application name + properties

3. Add configuration in nacos

Create an application name.properties configuration file in nacos and write the configuration
insert image description here
insert image description here

Nacos Config data structure
Nacos Config mainly uses dataId and group to uniquely determine a configuration.
When Nacos Client obtains data from Nacos Server, it calls this interface ConfigService.getConfig(String dataId, String group, long timeoutMs).
Spring Cloud application obtains data
dataID: In Nacos Config Starter, the splicing format of dataId is as follows
${prefix} - ${spring.profiles.active} .file − extensionprefix defaults to the value of spring . application . name, and can also be configured through the configuration item spring . cloud . nacos . config . prefix. spring . profiles . active is the profile corresponding to the current environment. Note that when the active profile is empty, the corresponding connector − will not exist, and the splicing format of data I d becomes {file-extension} prefix. The default is the value of spring.application.name, and it can also be configured through the configuration item spring.cloud.nacos.config.prefix. spring.profiles.active is the profile corresponding to the current environment. Note that when the activeprofile is empty, the corresponding connector - will also not exist, and the splicing format of dataId becomesfileex t e n s i o n p re f i x defaults to the value of sp r in g . a ppl i c a t i o n . name , and can also be configured through the configuration item sp r in g . c l o u d . na cos . co n f i g . p re f ix to configure. s p r in g . p ro f i l es . a c t i v e is the p ro f i l e corresponding to the current environment Note that when a c t i v e p ro f i l e is empty, the corresponding connectorIt will also not exist, and the splicing format of d a t a I d becomes {prefix}.${file-extension}
file-extension is the data format of the configuration content, which can be
configured through the configuration item spring.cloud.nacos.config.file-extension. Currently only the properties type is supported.
Group:
Group defaults to DEFAULT_GROUP, which can be configured through spring.cloud.nacos.config.group.

4. Use @Value and @RefreshScope in the application

insert image description here

insert image description here

After completing the above two steps, the application will obtain the corresponding configuration from Nacos Config and add it to the PropertySources of Spring Environment. Here we use the @Value annotation to inject the corresponding configuration into
the userName and age fields of SampleController, and add @RefreshScope to enable the dynamic refresh function
@RefreshScope
class SampleController { @Value(“ user . name “ ) Stringuser Name ; @Value ( "{user.name}") String userName; @Value("
user.name")StringuserName;@Value("{user.age}”)
int age;
}

5. Advanced

1. Core concepts

Namespace:
Used for tenant granular configuration isolation. The configuration of the same Group or Data ID can exist under different namespaces. One of the common scenarios of Namespace is the separation and isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) in development and test environments and production environments.
Configuration set:
A collection of related or unrelated configuration items is called a configuration set. In the system, a configuration file is usually a configuration set, which contains the configuration of all aspects of the system. For example, a configuration set may contain configuration items such as data source, thread pool, and log level Configuration
set ID:
ID of a certain configuration set in Nacos. The configuration set ID is one of the dimensions by which configurations are organized. Data IDs are often used to organize configuration sets for partitioned systems. A system or application can contain multiple configuration sets, and each configuration set can be identified by a meaningful name. Data ID usually adopts the naming rules of Java-like packages (such as com.taobao.tc.refund.log.level) to ensure global uniqueness. This naming rule is not mandatory.
Configuration grouping:
A group of configuration sets in Nacos, which is one of the dimensions of organizing configurations. Group configuration sets by a meaningful string (such as Buy or Trade) to distinguish configuration sets with the same Data ID. When you create a configuration on Nacos, if you do not fill in the name of the configuration group, the name of the configuration group defaults to DEFAULT_GROUP. Common scenarios for configuration grouping: Different applications or components use the same configuration type, such as database_url configuration and MQ_topic configuration.

insert image description here
insert image description here
insert image description here

2. Principle

Automatic injection:
NacosConfigStarter implements the org.springframework.cloud.bootstrap.config.PropertySourceLocator
interface, and sets the priority to the highest.
During the startup phase of the Spring Cloud application, it will actively obtain the corresponding data from the Nacos Server, convert the obtained
data into a PropertySource and inject it into the PropertySources attribute of the Environment, so using
the @Value annotation can also directly obtain the configuration content of the Nacos Server.
Dynamic refresh:
By default, Nacos Config Starter adds a monitoring function to all Nacos configuration items that have successfully obtained data. When the monitoring
server configuration changes, it will trigger
the refresh method of org.springframework.cloud.context.refresh.ContextRefresher in real time.
If you need to dynamically refresh the Bean, please refer to the specifications of Spring and Spring Cloud.
It is recommended to add @RefreshScope or @ConfigurationProperties annotations to the class ,

3、加载多配置文件
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=31098de9-fa28-41c9-b0bd-c754ce319ed4
spring.cloud.nacos.config.ext-config[0].data-id=datasource.yml
spring.cloud.nacos.config.ext-config[0].refresh=false
spring.cloud.nacos.config.ext-config[0].group=dev.

insert image description here

4. Best practice of namespace and group
Each microservice creates its own namespace for isolation, and group to distinguish dev, beta, prod and other environments

6. Summary

/**

  • 1. How to use Nacos as the configuration center for unified management and configuration
  • 1), introduce dependencies,
  •     <dependency>
    
  •         <groupId>com.alibaba.cloud</groupId>
    
  •         <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    
  •     </dependency>
    
  • 2) Create a bootstrap.properties.
  •  spring.application.name=gulimall-coupon
    
  •  spring.cloud.nacos.config.server-addr=127.0.0.1:8848
    
  • 3) A default data set (Data Id) gulimall-coupon.properties needs to be added to the configuration center. Default rules, application name.properties
  • 4) Add any configuration to the application name.properties
  • 5) Dynamically obtain configuration.
  •  @RefreshScope:动态获取并刷新配置
    
  •  @Value("${配置项的名}"):获取到配置。
    
  •  如果配置中心和当前应用的配置文件中都配置了相同的项,优先使用配置中心的配置。
    
  • 2. Details
  • 1), namespace: configuration isolation;
  •  默认:public(保留空间);默认新增的所有配置都在public空间。
    
  •  1、开发,测试,生产:利用命名空间来做环境隔离。
    
  •     注意:在bootstrap.properties;配置上,需要使用哪个命名空间下的配置,
    
  •     spring.cloud.nacos.config.namespace=9de62e44-cd2a-4a82-bf5c-95878bd5e871
    
  •  2、每一个微服务之间互相隔离配置,每一个微服务都创建自己的命名空间,只加载自己命名空间下的所有配置
    
  • 2), configuration set: a collection of all configurations
  • 3) Configuration set ID: similar to the file name.
  •  Data ID:类似文件名
    
  • 4), configuration grouping:
  •  默认所有的配置集都属于:DEFAULT_GROUP;
    
  •  1111,618,1212
    
  • Use in the project: each microservice creates its own namespace, and uses configuration grouping to distinguish environments, dev, test, prod
  • 3. Load multiple configuration sets at the same time
  • 1), any configuration information of microservices, any configuration file can be placed in the configuration center
  • 2) You only need to specify which configuration files in the configuration center to load in bootstrap.properties
  • 3)、@Value,@ConfigurationProperties。。。
  • In the past, any method of SpringBoot to obtain values ​​​​from configuration files can be used.
  • Some configuration centers prefer to use the ones in the configuration center, if not, use the configuration file

*/

六、Spring Cloud Gateway

insert image description here
insert image description here

1 Introduction

The gateway is used as the entrance of traffic, and its common functions include routing forwarding, authority verification, and current limiting control. As the second-generation gateway framework officially launched by SpringCloud, springcloud gateway replaces the Zuul gateway.

insert image description here
The gateway provides fully managed API services, rich API management functions, and assists enterprises in managing large-scale APIs to reduce management costs and security risks, including protocol adaptation, protocol forwarding, security policies, anti-brush, traffic, monitoring logs and other functions.
Spring Cloud Gateway aims to provide a simple and efficient way to route APIs and provide them with aspects such as: security, monitoring/metrics and resilience, etc.
Official document address:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.3.RELEASE/single/spring-cloud-gateway.html

Spring Cloud Gateway features:
 Based on Spring5, support responsive programming and SpringBoot2.0  Support route matching
using any request attribute  Route- specific assertions and
filters




Why use an API Gateway?
The reason for the emergence of the API gateway is the emergence of the microservice architecture. Different microservices generally have different network addresses, and external clients may need to call multiple service interfaces to complete a business requirement. If the client directly communicates with each microservice, there will be the following problems:  The client will request different microservices multiple times, which increases the complexity of the client
.
 There are cross-domain requests, and the processing is relatively complicated in certain scenarios.
 Authentication is complicated, and each service requires independent authentication.
 Difficult to refactor, as the project iterates, it may be necessary to re-partition microservices. For example, it is possible to merge multiple services into one or to split one service into several. If clients communicate directly with microservices, refactoring will be difficult to implement.
 Some microservices may use firewall/browser-unfriendly protocols, and direct access will be difficult.
The above problems can be solved with the help of API gateway. The API gateway is an intermediate layer between the client and the server, and all external requests will first pass through the API gateway layer. That is to say, more business logic is considered in the implementation of API, while security, performance, and monitoring can be done by the API gateway, which not only improves business flexibility but also does not lack security: the advantages of
using the API gateway are as follows:
 Easy to monitor. Monitoring data can be collected at the gateway and pushed to external systems for analysis.
 Ease of authentication. Instead of authenticating in each microservice, authentication can be done on the gateway before forwarding the request to the backend microservices.
 Reduced the number of interactions between the client and each microservice.

2. Core concepts

 Routing. Routing is the most basic part of a gateway. Routing information consists of an ID, a destination URL, a set of assertions, and a set of Filters. If the assert route is true, then the requested URL and configuration match
the  assert. Assert function in Java8. The input type of the assertion function in 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 the http request, such as request headers and parameters.
 Filters. A standard Spring webFilter. The filters in Spring cloud gateway are divided into two types of filters, Gateway Filter and Global Filter. Filter will modify the request and response.
Working principle:
insert image description here
The client sends a request to the gateway, and the elbow HandlerMapping judges whether the request satisfies a certain route, and then sends it to the gateway's WebHandler. This WebHandler passes the request to a filter chain, and before the request reaches the target service, the pre method of all filters will be executed. After the request reaches the target service for processing, execute the post method of all filters in sequence

If certain assertions (conditions) (predicates) are met, it will be routed to the specified address (uri), using the specified filter (filter)
insert image description here

3. Use

1. Create a gateway project and introduce the gateway

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
### 2、编写网关配置文件
spring:
cloud:
gateway:
routes: - id: add_request_parameter_route
uri: https://example.org
predicates: - Query=baz
filters: - AddRequestParameter=foo, bar

3. Pay attention

 When various Predicates exist in the same route at the same time, the request must meet all the conditions at the same time to be matched by this route.
 When a request meets the predicate conditions of multiple routes, the request will only be forwarded by the first successfully matched route

4. Test

You can use postman to test the routing function of the gateway

4, Predicates

insert image description here

5. Filters

1、GatewayFilter

insert image description here

2、GlobalFilter

insert image description here

6. Project import gateway

1. Create a gateway module and introduce gateway

2. Add common dependencies

insert image description here

3. Add to the registration center and configuration center

insert image description here

4. Add gateway configuration in application.yml and test it

insert image description here

insert image description here

Because the gateway references the data source driver introduced in the public module common, and the configuration file does not need to configure the data source, resulting in an error, you only need to add @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) to the startup class, remove DataSourceAutoConfiguration.class and then you can start successfully
insert image description here
insert image description here
.

5. Then request on the page: http://localhost:88/?url=baidu

insert image description here
insert image description here
If the request is: http://localhost:88/hello?url=qq
The actual request of the gateway is: https://www.qq.com/hello, it will report that the page does not exist
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_44696532/article/details/131866708