Technology Sharing

SpringCloud

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. What is Microservices

1. Basic concepts

Microservices are aArchitectural Style(Different from monolithic architecture, vertical architecture, distributed architecture, SOA architecture), the application is divided into smaller, process-driven services.

2. Characteristics of Microservices

  1. Lightweight: Split complex systems or services vertically, with each microservice focusing on solving specific problems.
  2. Low coupling: The split services are independent of each other in terms of code, resources, and environment, and can be independently developed, tested, deployed, and maintained, which is beneficial to the stability of the system (reducing the impact when problems occur) and expansion (more convenient resource evaluation and lower risk when expanding resources).
  3. Cross-platform: Different microservices can use different development languages ​​and can run in different environments.

2. What is SpringCloud

1. Basic concepts:

Spring Cloud is aMicroservices FrameworkIt provides a series of distributed system solutions. It provides microservice development and deployment, service registration and discovery, service governance, and service operation and maintenance capabilities in a componentized manner.

2. Common components:

1)Spring Cloud Netflix:

Eureka: Registration Center

Ribbon: Load Balancing

Feign: Remote calls

Hystrix: Service Circuit Breaker

Zuul/Gateway: Gateway

2)Spring Cloud Config: A centralized configuration management tool that externalizes application configuration and can be used for Spring or non-Spring applications.

3)Spring Cloud Bus: Event and message bus for propagating state changes or configuration change events in the cluster.

4)Spring Cloud Consul: Service discovery and configuration tool that integrates seamlessly with Docker containers.

5)Spring Cloud Security: A security toolkit that provides support for application security and authentication.

6)Spring Cloud Sleuth: Distributed call chain tracing, compatible with Zipkin, HTrace, and ELK tracing.

7)Spring Cloud Cluster: Leader election is implemented through abstraction of Zookeeper, Redis, and Consul.

8)Spring Cloud Data Flow: Microservice orchestration that can be easily used through a drag-and-drop interface or REST API.

9)Spring Cloud Stream: A lightweight event-driven microservices framework for quickly building applications that connect to external systems.

10)Spring Cloud Task: A short-term microservice framework that quickly builds applications that complete batch data processing tasks.

3. Steps to use SpringCloud components

springcloud tutorial-- 3. Microservice fuse mechanism, detailed explanation of the use of circuit breaker hystrix_How to configure java fuse-CSDN blog

springcloud tutorial-- 4. Detailed explanation of the use of gateway zuul_zuul usage tutorial-CSDN blog

1. Hystrix (fuse, downgrade, current limiting)

1) What is its function?

existIn distributed systemsIf a service node fails or the network fails, the caller may be blocked and waited. If the timeout is set too long, the caller's resources may be exhausted. This in turn leads to resource exhaustion in the caller's upstream system, which eventually leads toSystem Avalanche. Circuit breaking can effectively prevent service avalanche.

If you encounter a sudden increase in traffic, the general approach is toNon-core business functionsService degradation measures are adopted to protect the normal service of core business functions, and for core functional services, current limiting measures are required.

2) Does it happen on the client or server?

Service fuse:generallyIt occurs on the server side (the purpose is to make the caller fail quickly). When a service times out or fails, it causes a fuse, similar to a fuse in real life. (Sometimes it can also be configured on the client side to make itself fail quickly when a service call is found to be abnormal);
Service degradation: generally occurs on the client side. Considering the overall website request load, when a service is fused or shut down, the service will no longer be called; (sometimes it can also be configured on the server side to downgrade non-core functions to protect core functions when the system has sudden traffic);

Current limiting: usually occurs on the server side;

3) How to use

  • Fuse:

@EnableCircuitBreaker : Enabled in applicationFuse

        @HistrixCommand(fallbackMethod="xxxFallback",commandProperties = {
}) : The fuse annotation is added to the downgrade annotation, and the fuse condition is filled in commandProperties = {}. The specific fuse condition can be clickedHystrixPropertiesManager类Check.

  1. @HystrixCommand(fallbackMethod = "xxxFallback",commandProperties = {
  2. //20秒内出现3个请求,失败率为30%,就会触发熔断,30秒内不再发送调用
  3. // 条件一: 请求数量达到3个
  4. @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "3"),
  5. // 条件二: 每20秒一个判断单位
  6. @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT,value = "20000"),
  7. // 条件三: 失败率30%
  8. @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "30"),
  9. // 结果: 熔断后, 30秒内不再请求远程服务
  10. @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "30000")
  11. })
  • Downgrade:

Create a new xxxFallbackFactory class to implement FallbackFactory and override the create method. Define the downgrade method in create.

@FeignCliend(fallbackFactory=xxxFallbackFactory.class): Histrix is ​​integrated into Feign

Or specify the fallback method directly on the method: @HistrixCommand(fallbackMethod="xxxFallback")

  • Limiting:

        1、Current limiting strategy:

1) Signal current limiting

Semaphores are used to control the number of threads that can run concurrently. The number of internal virtual permits is specified through the constructor.

If semaphore isolation technology is used, each time a request is received, the service's own thread directly calls the dependent service. The semaphore is equivalent to a checkpoint. After each thread passes the checkpoint, the number of semaphores decreases by 1. When it reaches 0, the thread is no longer allowed to pass, but the fallback logic is directly executed and returned. To put it bluntly, it is just a current limit.

A semaphore can be understood as acounter,The counter counts the number of requests currently being processed. When the counter value reaches the set value, subsequent requests will not be accepted (or downgraded). It is necessary to wait until the counter value is less than the set value before subsequent requests can be processed.

  1. @HystrixCommand(
  2. commandProperties= {
  3. @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"),
  4. @HystrixProperty(name="execution.isolation.semaphore.maxConcurrentRequests", value="20")
  5. },
  6. fallbackMethod = "errMethod"
  7. )

2) Thread pool current limiting

  1. @HystrixCommand(
  2. commandProperties = {
  3. @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD")
  4. },
  5. threadPoolKey = "createOrderThreadPool",
  6. threadPoolProperties = {
  7. @HystrixProperty(name = "coreSize", value = "20"),
  8. @HystrixProperty(name = "maxQueueSize", value = "100"),
  9. @HystrixProperty(name = "maximumSize", value = "30"),
  10. @HystrixProperty(name = "queueSizeRejectionThreshold", value = "120")
  11. },
  12. fallbackMethod = "errMethod"
  13. )

Please note here:javaIn the thread pool, if the number of threads exceedscoreSize, thread creation requests will be prioritized into the queue, and if the queue is full, threads will continue to be created until the number of threads reachesmaximumSize, and then adopt the rejection strategy. But there is one more parameter in the thread pool configured by hystrixqueueSizeRejectionThreshold,ifqueueSizeRejectionThreshold < maxQueueSize, the number of queues reachesqueueSizeRejectionThresholdThe rejection strategy will be adopted, somaximumSizeFailed. IfqueueSizeRejectionThreshold > maxQueueSize, the number of queues reachesmaxQueueSizehour,maximumSizeis valid, the system will continue to create threads until the number reachesmaximumSize

      2. The difference between semaphore current limiting and thread pool current limiting:

1) Performance level: The semaphore uses the original thread, which consumes little performance;

2) System stability: Thread pools are isolated, and problems with one thread pool will not affect other thread pools;

3) Synchronous and asynchronous: Because the semaphore uses the original thread, it is synchronous and blocked.

        3. Current limiting strategy usage scenarios:

When the number of requests is very dense, resulting in high thread isolation overhead, it is recommended to use semaphores to reduce the load. This is usually used to deal with non-network requests (no need to call external services). In other scenarios, it is recommended to use thread pools.

4) What are the differences among them?

Current limiting is just current limiting. As long as the flow limit is not exceeded, the service is still available (different from circuit breaking), and it does not necessarily have to be downgraded (it can also throw an exception of exceeding the flow limit for the caller to handle it). So the following is just a description of the difference between circuit breaking and downgrading:

  • Different concepts

Circuit breaker means that the entire service is unavailable (focusing on self-protection), downgrade is the next best option (focusing on the bottom line), and current limiting means that the traffic cannot exceed a certain amount.

  • Different trigger mechanisms

By default, if hystrix detects that the failure rate of requests exceeds 50% within 10 seconds, it will trigger the circuit breaker mechanism. Then, it will retry the request to the microservice every 5 seconds. If the microservice cannot respond, it will continue to use the circuit breaker mechanism. If the microservice is reachable, it will close the circuit breaker mechanism and resume normal requests.

By default, hystrix will trigger the downgrade mechanism under the following four conditions:

  1. Method throws HystrixBadRequestException
  2. Method call timeout
  3. The fuse opens to intercept calls
  4. The thread pool, queue, or semaphore is full
  • Different affiliation

The downgrade mechanism may be called when the circuit breaker is broken, but the circuit breaker mechanism is usually not called when the circuit breaker is downgraded.Because circuit breaker is a global approach that disables services to ensure system stability, while downgrade is a second-best option that provides a backup solution, so their relationships are different (circuit breaker &gt; downgrade).

2. Feign and RestTemplate

Link content summary:

  1. Add starter dependencies;
  2. Add annotation: @EnableFeignClients;
  3. Create a Feign interface:

        @FeignClient(name="eureka-HA",fallbackFactory=DeptClientServiceFallbackFactory.class)

Springcloud Tutorial - 1. Quickly build an entry-level demo, just read this one_Ye Juyan-GitCode Open Source CommunityWithout further ado, follow me and start your SpringCloud experience. First, review the basic components of microservices: [Picture here] Producer: Provides services Consumer: Consumes services Service registration/discovery center: Service registration, discovery, and monitoring So, first understand the basic architecture of springcloud microservices: Producer (client), Consumer (client), Service registration/discovery center (server) Ye Juyan GitCode Open Source Communityicon-default.png?t=N7T8https://gitcode.csdn.net/65e840841a836825ed78b9d0.html?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MzI1MTQ3NiwiZXhwIjoxNzIxMTM0MjcwLCJpYXQiOjE3MjA1Mjk0NzAsInVzZXJuYW1lIjoicXFfMTk5NTIwMjkifQ.7co5oRDfDrxtdqIsV-9AjJacdbURh-cikj5Rtxt7Z1c

3. Use of Zuul

refer to:

SpringBoot project architecture practice "Gateway Zuul construction" -CSDN blog

4. Use of Eureka, the registration center

refer to:

SpringBoot project architecture practice "parent project construction and registration center construction" _java build springboot parent project startup -CSDN blog

4. Working Principle of SpringCloud

1. Eureka working principle:

  1. Service registration: When the service provider starts, it will send a registration request to the Eureka server, including the service's IP address, port number, service name, etc. After receiving the registration request, the Eureka server will save the service information to the memory and provide a service registration information query function to the outside world.

  2. Service discovery: When a service consumer needs to call other services, it will send a service discovery request to the Eureka server to obtain a list of instances of the required service. After receiving the request, the Eureka server will return a list of instances of the corresponding service, including the service's IP address, port number, and other information. The service consumer selects one of the service instances to call (load balancing) based on the returned list of instances.

  3. Heartbeat health check: The service provider will periodically send heartbeat packets to the Eureka server to prove that its service is in normal operation. If the Eureka server does not receive a heartbeat packet from a service instance within a period of time, it will consider the service instance to be down and remove it from the service list.

5. SpringCloud underlying source code

1. Gateway Zuul source code

SpringBoot project architecture practice "Gateway Zuul construction" -CSDN blogArticle browsing and reading 227 times. Chapter 3 Gateway Zuul Construction Preface: 1. Main functions Zuul mainly provides dynamic routing (built-in ribbon implementation) and filtering (can be used as unified authentication filter, gray release filter, blacklist and whitelist IP filter, service current limiting filter (can be implemented with Sentinel)) functions; 2. The difference with spring cloud GateWay belongs to the gateway solutions provided by two different open source organizations. Spring cloud GateWay uses non-blocking API, built-in current limiting filter, supports long connection (such as websockets), and is better than Zuul in high concurrency and slow backend service response scenarios...https://blog.csdn.net/qq_19952029/article/details/124285479

2. Registration Center Eureka Source Code

3. Circuit breaker Histrix source code

4. Configuration Center Config Source Code

5. Load balancing Ribbon source code

6. Microservice calls Feign source code

6. How does SpringCloud implement distributed transactions

Seata TCC model practice (Part 2) - Alibaba Cloud Developer CommunitySeata TCC mode practice (Part 2)icon-default.png?t=N7T8https://developer.aliyun.com/article/1053737?spm=5176.26934562.main.1.799c6a03T45SJ9The above blog post does not solve the suspension problem, which can be judged by different status indicators.

https://www.cnblogs.com/lilpig/p/16613226.htmlicon-default.png?t=N7T8https://www.cnblogs.com/lilpig/p/16613226.html

1. TCC mode role

TM: transaction manager, generated with the @GlobalTransaction annotation.

TC: Coordinator

RM: Participant

The whole process is:

TM proxies your global transaction and registers with TC before starting execution
TM starts executing each branch transaction in the global transaction, and RM registers and reports the branch transaction and execution status to TC
After the branch transaction is executed, TM sends a request to TC to commit or rollback the global transaction.

2. The meaning of TCC resource reservation, submission, and rollback.

Reservation means locking the database resources and updating them to an intermediate state, which will be changed to an effective state when the second-stage commit is performed after confirmation.Both involve operating databasesTherefore, there may be cases where confirmation and rollback fail, which require manual processing. This can be solved by recording logs, compensating and retrying, etc.

3. Advantages and disadvantages of TCC

Advantages of TCC mode

  1. Direct submission in one stage, no DB lock, no other locks, good performance
  2. The reservation and recovery logic is written by yourself, does not depend on the database, and can be used in non-transactional databases

Disadvantages of TCC mode

  1. Complex coding
  2. Weak consistency
  3. becauseConfirmandCancelIt may also fail, and this process needs to be handled
  4. Some businesses are not suitable for the TCC model. For example, placing an order is a process of adding a new line, so it is neither possible nor necessary to use TCC.

4. XA mode

Strong consistency, by coordinating when each participant's local transaction is committed and rolled back.

Advantages of XA mode

  1. Easy to implement, because most databases already support XA transactions, Seata only needs to do simple packaging
  2. Strong consistency

Disadvantages of XA Mode

  1. Each transaction needs to wait for all transactions to complete, occupying the database lock, resulting in poor performance and low availability.
  2. If the database does not support XA transactions, it cannot be used

5. AT mode

Weak consistency