Spring Cloud Alibaba five major components + code examples

Five major components of Spring Cloud Alibaba

Insert image description here

1. Introduction

Preface

Maintenance of the Spring Cloud Netflix department component has been discontinued, which has made the Spring community aware of the need to find new solutions to support microservices architecture. At the same time, because Alibaba has rich experience and technical practices in the field of microservices, the Spring community chose to cooperate with Alibaba to develop Spring Cloud Alibaba by integrating Alibaba's open source components and tools to replace Spring Cloud Netflix.

Spring Cloud Alibaba was initially launched as a sub-project of Spring Cloud and has now become an independent project. It integrates multiple open source components of Alibaba, such as Nacos, Sentinel, Dubbo, etc. These components have the advantages of high availability and high performance, and have been widely used within Alibaba and have undergone a large number of production verifications. Therefore, Spring Cloud Alibaba can help developers build microservice architecture more easily, providing a complete set of solutions, including service registration and discovery, configuration management, service invocation, flow control, circuit breaker degradation and other functions, as well as support for Dubbo RPC Framework support. Moreover, Spring Cloud Alibaba is constantly being updated and iterated, adding new features and improving performance.

In short, the birth of Spring Cloud Alibaba is not only to fill the vacancy of Spring Cloud Netflix department components that have stopped maintaining maintenance, but more importantly, to use Alibaba's technical strength to provide developers with more stable and efficient microservice solutions.

1.Nacos

1 Introduction

Nacos (full name Not Another Configuration Service) is a distributed configuration center and service discovery framework open sourced by Alibaba. It provides core functions such as service registration, service discovery and dynamic configuration management, which can help developers build and manage microservice architecture.

The main features of Nacos include:

  1. Service registration and discovery: Nacos provides service registration and discovery mechanisms based on DNS and HTTP/RESTful. The service provider registers its own information to the Nacos server when it starts, and the service consumer can obtain the list of available service instances by querying Nacos. In this way, service providers and consumers can be decoupled and service discovery and invocation can be performed dynamically.

  2. Configuration management: Nacos provides unified configuration management functions and supports dynamic configuration updates. Developers can store application configuration information in Nacos and then dynamically obtain the latest configuration at runtime. Nacos also supports configuration version management and grayscale release, which facilitates configuration changes and rollbacks.

  3. Service health monitoring: Nacos supports monitoring the health status of services registered on it. By sending heartbeat checks regularly, Nacos can sense the status of service instances in real time, including healthy, unhealthy and offline, for troubleshooting and governance.

  4. Dynamic DNS service: Nacos provides a dynamic DNS service to achieve load balancing of service instances by supporting weight and priority.

  5. More features: Nacos also provides visual management interface, cluster deployment, namespace isolation, permission control and other functions to meet enterprise-level needs.

In short, Nacos is a service registration, discovery, and configuration management tool for cloud native architecture, helping developers implement service governance in microservice architecture. It has been widely used within Alibaba and has become a mature and popular open source project. It is also one of the core components of Spring Cloud Alibaba.

2.Sentinel

1 Introduction

Sentinel is Alibaba's open source flow control and circuit breaker degradation component for distributed service architecture. It is designed to protect the high availability, stability and elasticity of services, and provides real-time monitoring, statistics and early warning functions to help developers manage distributed services.

Sentinel’s core features include:

  1. Traffic control: Sentinel provides a variety of traffic control strategies, such as QPS current limit, thread number limit and concurrency limit, etc., to facilitate developers to conduct fine-grained control according to business needs.

  2. Circuit breaker and downgrade: When a service abnormality or failure occurs, Sentinel can quickly circuit breaker and downgrade the service call to avoid the failure from spreading and affecting the normal operation of other services.

  3. Real-time monitoring: Sentinel provides real-time monitoring and statistics functions, which can monitor various indicators of the service, such as request response time, QPS, error rate, etc., and supports statistics and aggregation methods in multiple dimensions to detect service anomalies and problems in a timely manner.

  4. Rich application scenarios: Sentinel supports a variety of application scenarios, such as Dubbo RPC calls, HTTP interface calls, Feign clients, Spring Cloud Gateway, Spring MVC, etc., and can be applied to a variety of microservice architectures.

  5. High performance: Sentinel adopts strict limiting modes and efficient data structures when implementing flow control and circuit breaker degradation, ensuring its excellent performance and stability.

In short, Sentinel is a very practical distributed flow control and circuit breaker degradation framework that can help developers improve the robustness and stability of distributed applications. At the same time, Sentinel has also joined other open source components and tools in Alibaba's microservice ecosystem, such as Nacos, Dubbo, etc., to implement a complete set of microservice governance solutions.

3.Dubbo

1 Introduction

Dubbo (Apache Dubbo) is a high-performance, lightweight distributed service framework open sourced by Alibaba. It can help developers build and manage complex microservice architectures. Dubbo provides scalable service registration and discovery, load balancing, service invocation, fault-tolerance mechanism and other functions, making the development of distributed applications more convenient and efficient.

Dubbo’s main features include:

  1. Transparent remote procedure call (RPC): Dubbo shields the underlying network communication details, allowing developers to call remote services just like calling local methods, thereby realizing communication between distributed systems.

  2. High performance and low latency: Dubbo uses an asynchronous non-blocking communication method to provide high performance and low latency support at the network transmission level. At the same time, Dubbo also provides a variety of load balancing strategies and fault-tolerance mechanisms to provide better performance and robustness.

  3. Service registration and discovery: Dubbo provides scalable service registration centers, such as ZooKeeper, Consul, etc., to realize automatic registration and discovery of services. Developers can manage the status and metadata information of services through the configuration center.

  4. Cluster fault tolerance: Dubbo provides a variety of fault tolerance strategies, such as automatic switchover on failure, rapid error reporting on failure, and safety on failure, etc., which can cope with different fault situations and ensure high availability of services.

  5. Load balancing: Dubbo supports a variety of load balancing algorithms, such as polling, randomization, consistent hashing, etc. You can choose the appropriate load balancing strategy according to actual needs to improve the performance and scalability of the system.

  6. Highly scalable: Dubbo provides a wealth of extension points and plug-in mechanisms, which developers can customize and extend according to actual needs to adapt to different business scenarios and technology stacks.

In short, Dubbo is an excellent distributed service framework that has been widely used within Alibaba and has been recognized and used by the industry. It provides rich functions and flexible configuration options, allowing developers to build and manage complex distributed systems more conveniently.

4. RoctetMQ

1 Introduction

RocketMQ is a distributed messaging middleware open sourced by Alibaba. It has the characteristics of high reliability, high throughput and low latency. RocketMQ supports publish-subscribe mode and point-to-point mode, which is suitable for asynchronous messaging in large-scale distributed systems.

Key features of RocketMQ include:

  1. High reliability: RocketMQ provides a message storage mechanism based on master-slave replication, which can ensure the reliable delivery of messages. At the same time, RocketMQ also supports synchronous flushing and asynchronous flushing to improve the persistence and reliability of messages.

  2. High throughput: RocketMQ was designed with high throughput requirements in mind, using multi-threads to process messages concurrently, while supporting horizontal expansion and load balancing, which can meet the high concurrent message processing needs of large-scale distributed systems.

  3. Low latency: RocketMQ uses zero-copy technology and memory-mapped file technology during the message delivery process to reduce data transmission and IO overhead, thereby achieving low-latency message delivery.

  4. Distributed architecture: RocketMQ supports distributed deployment and can be horizontally expanded at the producer, consumer and message storage levels to cope with the needs of large-scale systems.

  5. Rich message model: RocketMQ provides publish-subscribe model and point-to-point model. Developers can choose the appropriate message model according to actual needs.

  6. Reliable sequential message: RocketMQ provides a reliable sequential message delivery mechanism to ensure the orderliness of messages.

  7. Monitoring and management: RocketMQ provides complete monitoring and management tools, which can monitor the production and consumption of messages in real time, as well as the running status of the cluster.

In short, RocketMQ is a distributed message middleware with powerful functions, high reliability, and high throughput. It has been widely used within the Alibaba Group and has also been widely adopted by the industry. It is suitable for various distributed architecture scenarios, such as e-commerce transaction systems, log processing systems, real-time computing, etc.

5. Set

1 Introduction

Seata is an open source distributed transaction solution, open sourced by Alibaba, which can manage and coordinate many different types of distributed transactions. Seata includes three core components: Transaction Coordinator (TC), Transaction Manager™ and Resource Manager (RM).

Seata supports a variety of distributed transaction scenarios, such as cross-database transactions, cross-service transactions, TCC transactions, etc. It achieves the reliability and consistency of global transactions by introducing the concepts of global transaction ID and branch transaction ID.

Seata’s key features include:

  1. Supports multiple distributed transaction models: Seata supports multiple transaction models, including atomic transactions, TCC (Try-Confirm-Cancel) transactions, and asynchronous compensation transactions.

  2. Scalability: Seata provides a pluggable component mechanism that can be expanded and customized according to actual needs, and supports various programming languages ​​and development frameworks.

  3. High availability: Seata supports active and backup mechanisms and automatic failover, ensuring high availability of services and data security.

  4. High performance: Seata uses an asynchronous non-blocking communication method and an efficient serialization protocol to improve system performance and throughput.

  5. Ease of use: Seata provides complete development documentation and sample code, allowing developers to quickly get started and use Seata.

In short, Seata is a powerful, highly reliable, easy-to-expand, and easy-to-use distributed transaction solution that has been widely used in the production environments of companies such as Alibaba. It can help developers solve various problems of distributed transactions and improve system reliability and performance.

6. Precautions for version control

When using Spring Cloud Alibaba components, the following are some version control considerations:

  1. Component version compatibility: Spring Cloud Alibaba is composed of multiple components, such as Nacos, Sentinel, Seata, etc. When selecting component versions, ensure good compatibility between components. You can refer to official documents or community version compatibility instructions.

  2. Spring Boot version adaptation: Spring Cloud Alibaba is closely related to Spring Boot, so you need to pay attention to the adaptation of the component version and Spring Boot version. Usually, Spring Cloud Alibaba officially provides a specific version of Spring Boot Starter to ensure that components are compatible with the corresponding Spring Boot version.

  3. Component Updates and Stability: Although new versions may contain new features and fix issues, choose versions carefully when using them in a production environment. It is recommended to give priority to versions that have been verified for long-term stability and to upgrade after sufficient testing.

  4. Community support and activity: Choose to use a widely supported and active component version to better obtain community support and resources. By checking the activity level of the GitHub repository, issue handling status, and release records, you can evaluate the health status and community support of the component.

  5. Pay close attention to the official documentation and community: Continue to pay attention to the updates of the official documentation and community to learn about the features, improvements and bug fixes of the latest version. Official documentation usually provides detailed version instructions and usage guides, which can help you better understand and use the component.

In short, when using Spring Cloud Alibaba components, reasonable selection of versions is an important factor in ensuring system stability and performance. By comprehensively considering factors such as component compatibility, Spring Boot version adaptation, stability, community support, and documentation, you can make informed version control decisions and keep up with the latest developments in components.

2. Code examples

1.Nacos

1. Service registration and service discovery

The following is a code example using Spring Cloud Alibaba and Nacos for service registration and service discovery:

  1. Add dependencies:

Add Spring Cloud Alibaba Nacos related dependencies in the pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
  1. Configure Nacos:

Configure Nacos related information in application.properties or application.yml, including the address and port of Nacos Server:

spring:
  application:
    name: your-service-name
  cloud:
    nacos:
      discovery:
        server-addr: ${
    
    nacos.server-addr}
  1. Registration service:

Add @EnableDiscoveryClient annotation to the Spring Boot main class to enable service registration and discovery functions:

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

@SpringBootApplication
@EnableDiscoveryClient
public class YourServiceApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(YourServiceApplication.class, args);
    }
}
  1. Use the service:

Use @Autowired annotation to inject DiscoveryClient into the class that needs to use the service, and use its method for service discovery:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class YourComponent {
    
    

    @Autowired
    private DiscoveryClient discoveryClient;

    public void getServiceInstances(String serviceName) {
    
    
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        // 处理服务实例列表
    }

    // 其他业务方法
}

In the above example, through the method of DiscoveryClient, all service instances of the specified service name can be obtained. You can further process the service instance list according to actual needs. getInstances

Please note that the above code example is for demonstration purposes only and does not include complete error handling and exception handling. In practical applications, corresponding improvements and improvements need to be made according to specific circumstances.

Using Spring Cloud Alibaba and Nacos for service registration and service discovery is very simple and can be achieved through configuration and annotations. At the same time, Nacos also provides other functions, such as health check, weight adjustment, etc., to help you better implement service governance.

2. Configuration management

Spring Cloud Nacos provides a simple and reliable way to centrally manage application configuration information. Here is an example of configuration management using Spring Cloud Nacos:

  1. Add dependencies:

Add Spring Cloud Alibaba Nacos related dependencies in the pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
  1. Configure Nacos:

Configure Nacos related information in the bootstrap.properties or bootstrap.yml file, including the address and port of the Nacos Server:

spring:
  application:
    name: your-application-name
  cloud:
    nacos:
      config:
        server-addr: ${
    
    nacos.server-addr}
  1. Create configuration file:

Create a configuration file in the Nacos console, which can be a configuration file in properties format or yaml format. For example, create a configuration file named your-application-name.properties or your-application-name.yml in the Nacos console and set the corresponding configuration items.

  1. Read configuration:

Use @Value annotation in the class that needs to read the configuration to inject the configuration value into the variable:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class YourComponent {
    
    

    @Value("${your.config.key}")
    private String configValue;

    // 使用 configValue 进行业务处理
}

In the above example, ${your.config.key} is the key name of the configuration item, and configValue is the variable into which the value of the configuration item is injected.

Through the above steps, your application can obtain the configuration information from Nacos and use it. When the configuration changes, Spring Cloud Nacos automatically updates the injected configuration values.

In addition to directly injecting configuration values, Spring Cloud Nacos also provides more advanced methods, such as using the @ConfigurationProperties annotation to create a configuration class and bind a set of configuration items to the class. properties to facilitate management and use.

Please note that the above example is for demonstration purposes only and does not include complete error handling and exception handling. In practical applications, corresponding improvements and improvements need to be made according to specific circumstances.

Using Spring Cloud Nacos for configuration management can easily and centrally manage the configuration information of the application, enabling the configuration to be dynamically updated, improving the flexibility and maintainability of the application.

3. Dynamic DNS service

Spring Cloud Nacos provides a dynamic DNS service that can help applications achieve service discovery and load balancing. Here is an example of dynamic DNS serving using Spring Cloud Nacos:

  1. Add dependencies:

Add Spring Cloud Alibaba Nacos related dependencies in the pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
  1. Configure Nacos:

Configure Nacos related information in application.properties or application.yml, including the address and port of Nacos Server:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: ${
    
    nacos.server-addr}
  1. Registration service:

Add @EnableDiscoveryClient annotation to the Spring Boot main class to enable service registration and discovery functions:

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

@SpringBootApplication
@EnableDiscoveryClient
public class YourServiceApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(YourServiceApplication.class, args);
    }
}
  1. Use dynamic DNS service:

In classes that need to use dynamic DNS services, you can use @LoadBalanced and RestTemplate to implement load-balanced HTTP calls:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class YourComponent {
    
    

    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    public void callOtherService() {
    
    
        String result = restTemplate.getForObject("http://your-service-name/your-api", String.class);
        // 处理调用结果
    }

    // 其他业务方法

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
    
    
        return new RestTemplate();
    }
}

In the above example, the @LoadBalanced annotation will automatically add load balancing functionality to RestTemplate. By using the service name (that is, the service name registered to Nacos) to access the APIs of other services, the effect of dynamic DNS is achieved.

Through the above steps, your application can use the dynamic DNS service provided by Spring Cloud Nacos for service discovery and load balancing. Spring Cloud Nacos will automatically manage changes in service instances and forward requests to different instances according to load balancing strategies.

It should be noted that when using the dynamic DNS service, you need to ensure that the mapping relationship between the service name and the service instance has been registered in Nacos.

Please note that the above example is for demonstration purposes only and does not include complete error handling and exception handling. In practical applications, corresponding improvements and improvements need to be made according to specific circumstances.

Using Spring Cloud Nacos' dynamic DNS service can easily implement service discovery and load balancing, improving the availability and scalability of distributed applications.

2.Sentinel

1. Flow control

The following is an example of Java code using Spring Cloud Sentinel to implement flow control:

  1. First, you need to introduce the Spring Cloud Sentinel dependency in the pom.xml file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    <version>3.0.0</version>
</dependency>
  1. In your Spring Boot application, create a method protected by flow control:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    public String hello() {
    
    
        return "Hello, World!";
    }
}
  1. Next, add Sentinel’s flow control annotation to this method@SentinelResource:
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "blockHandler")
    public String hello() {
    
    
        return "Hello, World!";
    }

    public String blockHandler(BlockException ex) {
    
    
        // 在流量控制时的处理逻辑,可以自定义返回结果或执行其他操作
        return "流量控制,访问被拒绝";
    }
}

In the above example, the @SentinelResource annotation is used to mark methods that require flow control. By setting the value attribute and specifying the resource name, you can configure and view traffic control rules in Sentinel Dashboard based on the resource name.

blockHandlerThe attribute specifies a method for defining processing logic during flow control. When the traffic reaches the limit, theblockHandler method will be executed for customized processing. In the example, the blockHandler method returns a custom result string.

The above is a Java code example using Spring Cloud Sentinel to implement flow control. You can configure more parameters and attributes in the @SentinelResource annotation according to actual needs to control traffic in a more granular manner.

2. Circuit breaker downgrade

The following is an example of Java code using Spring Cloud Sentinel to implement circuit breaker downgrade:

  1. First, you need to include the Spring Cloud Sentinel dependency in your pom.xml file, as described in the previous example.

  2. In your Spring Boot application, create a method that is circuit-breaker-downgrade-protected:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    public String hello() {
    
    
        // 模拟接口调用
        return invokeRemoteService();
    }
    
    private String invokeRemoteService() {
    
    
        // 这里可以模拟调用远程服务
        // 如果远程服务出现异常或超时,将会触发熔断降级
        throw new RuntimeException("Remote service error");
    }
}

In the example, the hello method simulates a scenario of calling a remote service. If the remote service encounters an exception or times out, an exception will be thrownRuntimeException.

  1. Next, add Sentinel’s circuit breaker downgrade annotation to this method@SentinelResource:
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    @SentinelResource(value = "hello", fallback = "fallbackHandler")
    public String hello() {
    
    
        return invokeRemoteService();
    }

    public String fallbackHandler(BlockException ex) {
    
    
        // 在熔断降级时的处理逻辑,可以返回默认值或执行其他操作
        return "熔断降级,服务不可用";
    }

    private String invokeRemoteService() {
    
    
        throw new RuntimeException("Remote service error");
    }
}

In the above example, @SentinelResource annotation is used to mark the method that needs circuit breaker downgrade. Configure and view circuit breaker rules in Sentinel Dashboard by setting the value attribute and specifying the resource name.

fallbackThe attribute specifies a method for defining the processing logic when circuit breaker is degraded. When an exception occurs in the protected method and causes a circuit breaker, the fallbackHandler method will be executed for customized processing. In the example, the fallbackHandler method returns a custom result string.

The above is an example of Java code using Spring Cloud Sentinel to implement circuit breaker downgrade. You can configure more parameters and attributes in the @SentinelResource annotation according to actual needs to more flexibly control circuit breaker rules and degradation processing.

3. System load protection

The following is an example of Java code that uses Spring Cloud Sentinel to implement system load protection:

  1. First, you need to include the Spring Cloud Sentinel dependency in your pom.xml file, as described in the previous example.

  2. In your Spring Boot application, create a method that requires system load protection:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    public String hello() {
    
    
        // TODO: 执行具体的业务逻辑
        return "Hello, World!";
    }
}

In the example, the hello method is one that requires system load protection.

  1. Next, add Sentinel’s system load protection annotation to this method@SentinelResource:
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    @SentinelResource(value = "hello", blockHandler = "blockHandler")
    public String hello() {
    
    
        // TODO: 执行具体的业务逻辑
        return "Hello, World!";
    }

    public String blockHandler(BlockException ex) {
    
    
        // 在系统负载高时的处理逻辑,可以自定义返回结果或执行其他操作
        return "系统负载高,请稍后再试";
    }
}

In the above example, the @SentinelResource annotation is used to mark methods that require system load protection. Configure and view system load protection rules in Sentinel Dashboard by setting the value attribute and specifying the resource name.

blockHandlerThe attribute specifies a method for defining processing logic when the system load is high. When the system load exceeds the limit, theblockHandler method will be triggered for custom processing. In the example, the blockHandler method returns a custom result string.

The above is an example of Java code using Spring Cloud Sentinel to implement system load protection. You can configure more parameters and attributes in the @SentinelResource annotation according to actual needs to more finely control the system load protection rules and processing logic.

4.Real-time monitoring

To implement real-time monitoring of Spring Cloud Sentinel, you can use the @SentinelResource annotation provided by Sentinel combined with the /actuator/sentinel endpoint of Spring Boot Actuator. Here is a Java code example:

  1. First, make sure you have added the relevant dependencies of Spring Cloud Sentinel and Spring Boot Actuator in the pom.xml file.

  2. In your Spring Boot application, create methods that require real-time monitoring:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    

    @GetMapping("/hello")
    @SentinelResource(value = "hello")
    public String hello() {
    
    
        // TODO: 执行具体的业务逻辑
        return "Hello, World!";
    }
}

In the example, the hello method is one that requires real-time monitoring.

  1. Configure the Spring Boot Actuator/actuator/sentinel endpoint, add the following configuration in the application.properties or application.yml file:
management.endpoints.web.exposure.include: sentinel

This will enable Sentinel’s monitoring endpoint.

  1. Start your Spring Boot application.

  2. Use a browser to accesshttp://localhost:8080/actuator/sentinel and you will see real-time monitoring data.

Through the above steps, you can monitor and manage your Spring Cloud application in real time in the Sentinel console.

Please note that if you want to configure Sentinel's real-time monitoring in a more granular manner, you can use the functions provided by Sentinel Dashboard, which provides richer monitoring and management functions. You can configure Sentinel Dashboard according to the official documentation and connect your application to the Dashboard for real-time monitoring and management.

3.Dubbo

1.RPC framework

Spring Cloud Dubbo is a microservice framework based on Dubbo RPC framework and Spring Cloud technology stack. The following is an example of RPC calling Java code based on Spring Cloud Dubbo:

  1. First, make sure you have added the relevant dependencies of Spring Cloud Dubbo in the pom.xml file.

  2. Create a service interface HelloService on the provider side:

public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we defined a simple service interface that contains a method sayHello that returns the greeting of the passed in parameters.

  1. Implement the service interface HelloService on the provider side:
@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    
    
    @Override
    public String sayHello(String name) {
    
    
        return "Hello, " + name + "!";
    }
}

In the above example, we use the @DubboService annotation to mark HelloServiceImpl as the Dubbo service provider, and use the version attribute to specify the service version number.

  1. Introduce the service interface HelloService on the consumer side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we define a service interface that is the same as the provider-side service interface and introduce it to the consumer side.

  1. Make remote calls through Dubbo on the consumer side:
@Service
public class HelloConsumer {
    
    
    @Reference(version = "1.0.0")
    private HelloService helloService;

    public void invoke() {
    
    
        String result = helloService.sayHello("Alice");
        System.out.println(result);
    }
}

In the above example, we use the @DubboReference annotation to associate the consumer-side HelloService with the provider-side service interface HelloService, and call its sayHello method.

Note: Service providers and consumers need to configure Dubbo related configurations in the application.properties or application.yml files, such as registration center address, protocol, timeout, etc.

The above is an example of RPC calling Java code based on Spring Cloud Dubbo. You can further configure and extend the functions of the Dubbo framework according to actual needs, such as adding custom filters, configuring Dubbo's cluster fault tolerance strategy, etc.

2. Service governance

In Spring Cloud Dubbo, service governance is implemented by using the registration center for service registration and discovery. The following is an example of service management Java code based on Spring Cloud Dubbo:

  1. First, make sure you have added the relevant dependencies of Spring Cloud Dubbo in the pom.xml file and configured the Dubbo registration center address.

  2. Add the @EnableDubbo annotation on the provider side:

@SpringBootApplication
@EnableDubbo
public class DubboProviderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DubboProviderApplication.class, args);
    }
}

In the above example, we use the @EnableDubbo annotation to enable Dubbo's service provider function.

  1. Create a service interface HelloService on the provider side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we defined a simple service interface that contains a method sayHello that returns the greeting of the passed in parameters.

  1. Implement the service interface HelloService on the provider side:
@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    
    
    @Override
    public String sayHello(String name) {
    
    
        return "Hello, " + name + "!";
    }
}

In the above example, we use the @DubboService annotation to mark HelloServiceImpl as the Dubbo service provider, and use the version attribute to specify the service version number.

  1. Introduce the service interface HelloService on the consumer side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we define a service interface that is the same as the provider-side service interface and introduce it to the consumer side.

  1. Make remote calls through Dubbo on the consumer side:
@Service
public class HelloConsumer {
    
    
    @Reference(version = "1.0.0")
    private HelloService helloService;

    public void invoke() {
    
    
        String result = helloService.sayHello("Alice");
        System.out.println(result);
    }
}

In the above example, we use the @DubboReference annotation to associate the consumer-side HelloService with the provider-side service interface HelloService, and call its sayHello method.

Note: Service providers and consumers need to configure Dubbo related configurations in the application.properties or application.yml files, such as registration center address, protocol, timeout, etc.

The above is an example of service management Java code based on Spring Cloud Dubbo. In actual applications, you can configure more Dubbo parameters and properties as needed, such as configuring service weights, setting load balancing policies, enabling service degradation, etc.

3. Load balancing

In Spring Cloud Dubbo, load balancing between service providers can be achieved through Dubbo's load balancing strategy. The following is an example of load balancing code based on Spring Cloud Dubbo:

  1. First, make sure you have added Spring Cloud Dubbo's related dependencies in the pom.xml file and configured Dubbo's registration center address.

  2. Add the @EnableDubbo annotation on the provider side:

@SpringBootApplication
@EnableDubbo
public class DubboProviderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DubboProviderApplication.class, args);
    }
}

In the above example, we use the @EnableDubbo annotation to enable Dubbo's service provider function.

  1. Create a service interface HelloService on the provider side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we defined a simple service interface that contains a method sayHello that returns the greeting of the passed in parameters.

  1. Implement the service interface HelloService on the provider side:
@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    
    
    @Override
    public String sayHello(String name) {
    
    
        return "Hello, " + name + "!";
    }
}

In the above example, we use the @DubboService annotation to mark HelloServiceImpl as the Dubbo service provider, and use the version attribute to specify the service version number.

  1. Introduce the service interface HelloService on the consumer side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we define a service interface that is the same as the provider-side service interface and introduce it to the consumer side.

  1. Make remote calls through Dubbo on the consumer side:
@Service
public class HelloConsumer {
    
    
    @Reference(version = "1.0.0", loadbalance = "random")
    private HelloService helloService;

    public void invoke() {
    
    
        String result = helloService.sayHello("Alice");
        System.out.println(result);
    }
}

In the above example, we use the @DubboReference annotation to associate the consumer-side HelloService with the provider-side service interface HelloService, and use the loadbalance attribute to specify the load balancing strategy as random load balancing.

Dubbo supports a variety of load balancing strategies, such as random load balancing, polling load balancing, consistent hash load balancing, etc. You can choose an appropriate load balancing strategy based on actual needs.

Note: Service providers and consumers need to configure Dubbo related configurations in the application.properties or application.yml files, such as registration center address, protocol, timeout, etc.

The above is a load balancing code example based on Spring Cloud Dubbo. You can configure and expand Dubbo's load balancing strategy according to actual conditions to meet your business needs.

4. Service downgrade

In Spring Cloud Dubbo, Dubbo's service degradation can be used to provide limited backup functionality when exceptions or failures occur. The following is an example of service degradation code based on Spring Cloud Dubbo:

  1. First, make sure you have added Spring Cloud Dubbo's related dependencies in the pom.xml file and configured Dubbo's registration center address.

  2. Add the @EnableDubbo annotation on the provider side:

@SpringBootApplication
@EnableDubbo
public class DubboProviderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DubboProviderApplication.class, args);
    }
}

In the above example, we use the @EnableDubbo annotation to enable Dubbo's service provider function.

  1. Create a service interface HelloService on the provider side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we defined a simple service interface that contains a method sayHello that returns the greeting of the passed in parameters.

  1. Implement the service interface HelloService on the provider side and add service degradation logic:
@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    
    
    @Override
    public String sayHello(String name) {
    
    
        // 模拟服务降级逻辑,当出现异常时返回固定的备用消息
        try {
    
    
            // 实际的服务逻辑
            // ...
            return "Hello, " + name + "!";
        } catch (Exception e) {
    
    
            // 异常处理,返回备用消息
            return "Sorry, the service is currently unavailable.";
        }
    }
}

In the above example, we added service degradation logic in the service provider's HelloServiceImpl. When an exception occurs in the service, a fixed backup message will be returned.

  1. Introduce the service interface HelloService on the consumer side:
public interface HelloService {
    
    
    String sayHello(String name);
}

In the above example, we define a service interface that is the same as the provider-side service interface and introduce it to the consumer side.

  1. Make remote calls through Dubbo on the consumer side:
@Service
public class HelloConsumer {
    
    
    @Reference(version = "1.0.0")
    private HelloService helloService;

    public void invoke() {
    
    
        String result = helloService.sayHello("Alice");
        System.out.println(result);
    }
}

In the above example, we use the @DubboReference annotation to associate the consumer-side HelloService with the provider-side service interface HelloService, and call its sayHello method.

Through the above code example, if an exception occurs when the service provider executes the service method, a preset backup message will be returned, achieving the effect of service degradation. You can define specific logic for service degradation based on actual business needs.

Note: Service providers and consumers need to configure Dubbo related configurations in the application.properties or application.yml files, such as registration center address, protocol, timeout, etc.

The above is an example of service downgrade code based on Spring Cloud Dubbo. You can perform customized service downgrade processing based on actual conditions to provide a better user experience.

4. RoctetMQ

1.Message publishing and subscription

Using RocketMQ for message publishing and subscription in Spring Cloud can be achieved by using the official RocketMQ client and the Spring Cloud Stream framework. Here's a basic code example:

  1. Add dependencies:
    First, add the following dependencies in thepom.xml file:
<dependencies>
    <!-- RocketMQ 客户端依赖 -->
    <dependency>
        <groupId>org.apache.rocketmq</groupId>
        <artifactId>rocketmq-client</artifactId>
        <version>4.9.1</version>
    </dependency>

    <!-- Spring Cloud Stream 相关依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>
  1. Configure RocketMQ connection information:
    Configure RocketMQ connection information in the application.properties file, for example:
spring.cloud.stream.rocketmq.binder.namesrv-addr=mq.namesrv.addr:9876
  1. Publish a message:
    Create a Service or Component of the message publisher and use RocketMQTemplate to send the message.
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

@EnableBinding(Source.class)
public class MessageProducer {
    
    

    private final Source source;

    public MessageProducer(Source source) {
    
    
        this.source = source;
    }

    public void sendMessage(String messageContent) {
    
    
        Message<String> message = MessageBuilder.withPayload(messageContent).build();
        source.output().send(message);
    }

}

In the above example, the @EnableBinding(Source.class) annotation is used to bind the message publisher, and the message is sent to RocketMQTemplate =3>Channel. output()

  1. Subscribe to messages:
    Create a Service or Component of a message subscriber, and process the received messages through annotations@StreamListener.
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;

@EnableBinding(Sink.class)
public class MessageConsumer {
    
    

    @StreamListener(Sink.INPUT)
    public void handleMessage(String message) {
    
    
        System.out.println("Received message: " + message);
        // 处理消息逻辑
    }

}

In the above example, use the @EnableBinding(Sink.class) annotation to bind the message subscriber, and use the @StreamListener(Sink.INPUT) annotation to listen to the input channel and process the received news.

Through the above steps, you can use Spring Cloud and RocketMQ to implement message publishing and subscription functions. The message sender sends the message through RocketMQTemplate, and the message receiver uses the @StreamListener annotation to process the received message. When a message is published, subscribers will automatically receive the message and process it.

2. Message persistence

The configuration of using RocketMQ for message persistence in Spring Cloud is relatively simple. You only need to add some parameters to the RocketMQ connection information. Here's a basic code example:

  1. Configure RocketMQ connection information:
    Add the following configuration items in the application.properties file to enable message persistence:
spring.cloud.stream.rocketmq.binder.namesrv-addr=mq.namesrv.addr:9876
spring.cloud.stream.rocketmq.binder.topic=topic_name
spring.cloud.stream.rocketmq.binder.producer.persistent=true

Among them, the message persistence function is enabled by settingspring.cloud.stream.rocketmq.binder.producer.persistent=true.

  1. Publish a message:
    The same as the code example when the message persistence function is not turned on, use RocketMQTemplate to send the message tooutput()Channel is enough.
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

@EnableBinding(Source.class)
public class MessageProducer {
    
    

    private final Source source;

    public MessageProducer(Source source) {
    
    
        this.source = source;
    }

    public void sendMessage(String messageContent) {
    
    
        Message<String> message = MessageBuilder.withPayload(messageContent).build();
        source.output().send(message);
    }

}
  1. Subscribe to messages:
    It is the same as the code example when the message persistence function is not turned on. It also listens to the input channel through annotations@StreamListener and processes the received news.
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;

@EnableBinding(Sink.class)
public class MessageConsumer {
    
    

    @StreamListener(Sink.INPUT)
    public void handleMessage(String message) {
    
    
        System.out.println("Received message: " + message);
        // 处理消息逻辑
    }

}

Through the above steps, you can use Spring Cloud and RocketMQ to implement message persistence. When the message is sent, after setting the persistence attribute, the message will be persisted to RocketMQ. Even if RocketMQ Broker restarts or crashes, the message can be guaranteed and will not be lost.

3. Transaction messages

To use RocketMQ for transaction message transmission in Spring Cloud, you need to rely on the spring-cloud-starter-stream-rocketmq-transaction module and use RocketMQTransactionTemplate to send transaction messages. Here's a simple code example:

  1. Add dependencies:
    Add the following dependencies in thepom.xml file:
<dependencies>
    <!-- RocketMQ 客户端依赖 -->
    <dependency>
        <groupId>org.apache.rocketmq</groupId>
        <artifactId>rocketmq-client</artifactId>
        <version>4.9.1</version>
    </dependency>

    <!-- Spring Cloud Stream 相关依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rocketmq-transaction</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>
  1. Configure RocketMQ connection information:
    Configure RocketMQ connection information in the application.properties file, for example:
spring.cloud.stream.rocketmq.binder.namesrv-addr=mq.namesrv.addr:9876
  1. Send transaction message:
    Create TransactionListener implementation class and implement three methods in it: executeLocalTransaction(), < /span>. These methods are used to perform transaction operations locally, check transaction execution status, and roll back transaction operations. checkLocalTransaction() and rollback()
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.transaction.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.transaction.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
public class MyTransactionListener implements RocketMQLocalTransactionListener {
    
    

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
    
    
        try {
    
    
            // 执行本地事务操作

            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
    
    
            // 回滚事务操作

            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
    
    
        // 检查本地事务执行状态,返回COMMIT或UNKNOW
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public void rollback(Message msg) {
    
    
        // 回滚本地事务操作
    }
}

In the above example, the executeLocalTransaction() method is implemented to perform local transaction operations. If an exception occurs, the transaction operation is rolled back by returning RocketMQLocalTransactionState.ROLLBACK; Implement the checkLocalTransaction() method to check the local transaction execution status and return RocketMQLocalTransactionState.COMMIT or RocketMQLocalTransactionState.UNKNOW. If UNKNOW is returned, the message needs to be sent again. To ensure that the message is submitted correctly in the transaction; implement the rollback() method to roll back the local transaction operation.

Next, in the message publisher, useRocketMQTransactionTemplate to send the transaction message.

import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MyTransactionProducer {
    
    

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private MyTransactionListener myTransactionListener;

    public void sendTransactionMessage(String messageContent) {
    
    
        Message<String> message = MessageBuilder.withPayload(messageContent)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, "transactionId").build();
        RocketMQLocalTransactionState state = rocketMQTemplate.sendMessageInTransaction("transaction-topic", message,
                myTransactionListener, null);
        System.out.println(state);
    }
}

In the above example, RocketMQTransactionTemplate is used to send the transaction message, in which the RocketMQHeaders.TRANSACTION_ID attribute needs to be set to identify the transaction ID. At the same time, you also need to pass in MyTransactionListener as the transaction listener.

  1. Receive transaction messages:
    In the message subscriber, the same as different types of RocketMQ message transmission, use the @StreamListener annotation to listen to the input channel, and Process the received message.
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;

@EnableBinding(Sink.class)
public class MessageConsumer {
    
    

    @StreamListener(Sink.INPUT)
    public void handleMessage(String message) {
    
    
        System.out.println("Received message: " + message);
        // 处理消息逻辑
    }

}

Through the above steps, you can use Spring Cloud and RocketMQ to realize the transmission of transaction messages. Transaction messages are sent using RocketMQTransactionTemplate, transaction operations are executed in the TransactionListener implementation class, and the message receiving end listens to the input channel through the @StreamListener annotation. , and process the received message. When the transaction message needs to be rolled back, roll back the transaction operation by returning RocketMQLocalTransactionState.ROLLBACK to ensure the correctness of message transmission.

5. Set

1. Distributed transaction solutions

Spring Cloud Seata is an open source solution for solving distributed transaction problems. It is based on the Seata framework and integrated with Spring Cloud to provide distributed transaction management capabilities under a microservice architecture. The following is a simple code example that demonstrates how to implement distributed transactions using Seata in Spring Cloud:

  1. Add dependencies:
    Add the following dependencies in the pom.xml file, including Seata's client dependencies and Spring Cloud's related dependencies:
<dependencies>
    <!-- Seata 客户端依赖 -->
    <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-all</artifactId>
        <version>1.4.3</version>
    </dependency>

    <!-- Spring Cloud 相关依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>
    <!-- 其他依赖... -->
</dependencies>
  1. Configure Seata connection information:
    Configure Seata connection information in the application.properties file, for example:
spring.cloud.alibaba.seata.tx-service-group=my_tx_group
  1. Write business logic code:
    Create a business service and mark the methods that require global transaction management through @GlobalTransactional annotations.
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

@Service
public class BusinessService {
    
    

    @GlobalTransactional(rollbackFor = Exception.class)
    public void processBusiness() {
    
    
        // 执行业务逻辑
        // 调用其他微服务或数据库操作

        // 如果出现异常,Seata会自动回滚所有参与到事务的操作
    }
}

In the above example, the method is marked with the @GlobalTransactional annotation. When this method is executed, Seata will automatically create a global transaction and include all operations participating in the transaction into management. If an exception occurs during method execution, Seata automatically rolls back the transaction. processBusiness()

  1. Configure Seata proxy:
    In each microservice project that needs to participate in distributed transactions, you need to add Seata's configuration filesregistry.conf and a>file.conf, and configure accordingly. These configuration files are used to configure information such as Seata's proxy and transaction storage.

  2. Start Seata Server:
    In a distributed environment, you need to start an independent Seata Server instance to manage the coordination and recovery of global transactions.

  3. Start microservice applications:
    Start each microservice application and ensure that they can connect to Seata Server correctly.

Through the above steps, you can use Seata to implement distributed transaction management in Spring Cloud. By adding the @GlobalTransactional annotation on the method that needs to participate in the global transaction, Seata will automatically manage the submission and rollback of the transaction. At the same time, configure Seata's agent in each microservice project to ensure that each microservice participating in distributed transactions can correctly connect to Seata Server for transaction management.

2. Transaction Coordinator

Spring Cloud Seata provides a transaction coordinator (Transaction Coordinator), which is responsible for managing the creation, submission and rollback of global transactions. The following is a simple code example that demonstrates how to configure and use Seata's transaction coordinator in Spring Cloud:

  1. Add dependencies:
    Add the following dependencies in the pom.xml file, including Seata's client dependencies and Spring Cloud's related dependencies:
<dependencies>
    <!-- Seata 客户端依赖 -->
    <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-all</artifactId>
        <version>1.4.3</version>
    </dependency>

    <!-- Spring Cloud 相关依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>
    <!-- 其他依赖... -->
</dependencies>
  1. Configure Seata connection information:
    Configure Seata connection information in the application.properties file, for example:
spring.cloud.alibaba.seata.tx-service-group=my_tx_group
  1. Configure Seata's transaction coordinator:
    In the Spring Cloud configuration file, configure Seata's transaction coordinator.
seata:
  enabled: true
  application-id: my_application
  tx-service-group: my_tx_group
  service:
    vgroup-mapping.my_tx_group: default
    default.grouplist: "127.0.0.1:8091"

In the above example, Seata's transaction coordinator is configured. Among them, application-id is used to identify the application, tx-service-group is the identifier of the transaction group, and default.grouplist is the address of Seata Server.

  1. Start Seata Server:
    In a distributed environment, you need to start an independent Seata Server instance to manage the coordination and recovery of global transactions.

  2. Start microservice applications:
    Start each microservice application and ensure that they can connect to Seata Server correctly.

Through the above steps, you can configure and use Seata's transaction coordinator. The transaction coordinator is responsible for coordinating and managing distributed transactions, including the creation, submission, and rollback of global transactions. In Spring Cloud, you can interact with Seata's transaction coordinator by configuring Seata's connection information and enabling Seata in each microservice application.

3. Transaction participants

Spring Cloud Seata provides a transaction participant (Transaction Participant), which is responsible for controlling the submission and rollback of local transactions as a participant in a distributed transaction. The following is a simple code example that demonstrates how to configure and use Seata's transaction participants in Spring Cloud:

  1. Add dependencies:
    Add the following dependencies in the pom.xml file, including Seata's client dependencies and Spring Cloud's related dependencies:
<dependencies>
    <!-- Seata 客户端依赖 -->
    <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-all</artifactId>
        <version>1.4.3</version>
    </dependency>

    <!-- Spring Cloud 相关依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>
    <!-- 其他依赖... -->
</dependencies>
  1. Configure Seata connection information:
    Configure Seata connection information in the application.properties file, for example:
spring.cloud.alibaba.seata.tx-service-group=my_tx_group
  1. Write business logic code:
    Create a business service and implement theio.seata.rm.datasource.DataSourceProxy interface. This interface is used to manage local transactions of the database in distributed transactions.
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

@Service
public class UserService {
    
    

    @Autowired
    private DataSource dataSource;

    public void createUser(String username, String password) {
    
    
        Connection conn = null;
        PreparedStatement ps = null;
        try {
    
    
            // 获取Seata代理的数据库连接
            conn = dataSource.getConnection();
            conn.setAutoCommit(false); // 关闭自动提交

            // 执行SQL语句
            ps = conn.prepareStatement("INSERT INTO user(id, username, password) VALUES (?, ?, ?)");
            ps.setString(1, UUID.randomUUID().toString());
            ps.setString(2, username);
            ps.setString(3, password);
            ps.executeUpdate();

            conn.commit(); // 提交本地事务

        } catch (SQLException ex) {
    
    
            if (conn != null) {
    
    
                try {
    
    
                    conn.rollback(); // 回滚本地事务
                } catch (SQLException e) {
    
    
                    // 日志处理
                }
            }
        } finally {
    
    
            if (ps != null) {
    
    
                try {
    
    
                    ps.close();
                } catch (SQLException e) {
    
    
                    // 日志处理
                }
            }
            if (conn != null) {
    
    
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    // 日志处理
                }
            }
        }
    }

    // 实现 DataSourceProxy 接口
    public DataSource getDataSource() {
    
    
        return dataSource;
    }
}

In the above example, a UserService class is created and the getDataSource() method is implemented (this method is used to obtain the data source of the Seata agent). At the same time, the proxy method provided by Seata is used in the createUser() method to obtain the database connection under distributed transactions, thereby realizing the management of local transactions.

  1. Configure Seata proxy:
    In each microservice project that needs to participate in distributed transactions, you need to add Seata's configuration filesregistry.conf and a>file.conf, and configure accordingly. These configuration files are used to configure information such as Seata's proxy and transaction storage.

  2. Start Seata Server:
    In a distributed environment, you need to start an independent Seata Server instance to manage the coordination and recovery of global transactions.

  3. Start microservice applications:
    Start each microservice application and ensure that they can connect to Seata Server correctly.

Through the above steps, you can configure and use Seata's transaction participants in Spring Cloud. By implementing the DataSourceProxy interface, you can obtain Seata's proxy data source and manage local transactions through this data source. At the same time, configure Seata's agent in each microservice project to ensure that each microservice participating in distributed transactions can correctly connect to Seata Server for transaction management.

4. Transaction logging

In Spring Cloud Seata, transaction logging can be enabled through configuration. The following is a sample code that demonstrates how to configure and use Seata's transaction logging:

  1. Add dependencies:
    Add Seata's client dependencies and Spring Cloud's related dependencies in the pom.xml file, consistent with the steps mentioned above.

  2. Configure Seata connection information:
    Configure Seata connection information in the application.properties file, for example:

spring.cloud.alibaba.seata.tx-service-group=my_tx_group
  1. Configure Seata proxy:
    In each microservice project, you need to add Seata's configuration filesregistry.conf and file.conf and configure accordingly. Make sure that service.vgroup_mapping.my_tx_group=default is configured, where my_tx_group is the previously configured tx-service-group.

  2. Start Seata Server:
    Start an independent Seata Server instance to manage the coordination and recovery of global transactions.

  3. Transaction logging configuration:
    In thefile.conf configuration file, enable transaction logging, for example:

## Transaction Log Store
store {
  ## 日志存储模式: file, db (default file)
  mode = "file"

  ## File 模式配置
  file {
    ## 存储路径,默认为当前路径下的"logs"目录
    dir = "file_store/data"

    ## 存储文件个数,默认为100
    max-log-file-size = 5242880
    ## 日志文件大小,默认为1GB
    max-log-size = 104857600

    ## Buffer 缓冲区大小,默认为8MB
    log-buffer-size = 83886080

    ## 异步刷盘,默认为false
    flush-disk-mode = false
  }
}
  1. Start microservice applications:
    Start each microservice application and ensure that they can connect to Seata Server correctly.

Through the above steps, you can enable the transaction logging function in Spring Cloud Seata. By configuring the relevant parameters in thefile.conf file, you can control the storage method, storage path, size and other information of the transaction log. It should be noted that the transaction logging function has a certain impact on performance. You can choose whether to enable this function based on actual needs and system load conditions.

Guess you like

Origin blog.csdn.net/qq_49841284/article/details/133991880