Sử dụng Spring Cloud Hystrix để bảo vệ dịch vụ khỏi lỗi lan truyền

Trong hệ thống phân tán, sự chậm trễ hoặc lỗi từ một dịch vụ có thể kéo theo sự sụp đổ dây chuyền của toàn bộ hệ thống. Spring Cloud Hystrix — một thư viện được xây dựng dựa trên giải pháp Hystrix của Netflix — cung cấp cơ chế cách ly lỗi và phương án dự phòng nhằm nâng cao độ ổn định và khả năng phục hồi của hệ thống.

Triển khai dịch vụ hỗ trợ Hystrix

Để tích hợp Hystrix vào ứng dụng Spring Boot, cần thêm các phụ thuộc sau:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Cấu hình file application.yml:

server:
  port: 8401
spring:
  application:
    name: hystrix-service
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
service-url:
  user-service: http://user-service

Kích hoạt chức năng ngắt mạch bằng cách thêm chú thích @EnableCircuitBreaker vào lớp khởi động chính:

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

Tạo controller gọi đến dịch vụ user-service:

@RestController
public class UserFallbackController {

    @Autowired
    private RemoteUserService remoteUserService;

    @GetMapping("/testFallback/{id}")
    public CommonResult getUserWithFallback(@PathVariable Long id) {
        return remoteUserService.fetchUser(id);
    }
}

Trong lớp dịch vụ, sử dụng @HystrixCommand để định nghĩa phương thức xử lý khi xảy ra lỗi:

@Service
public class RemoteUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @HystrixCommand(fallbackMethod = "provideDefaultUser")
    public CommonResult fetchUser(Long id) {
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult provideDefaultUser(Long id) {
        User fallbackUser = new User(-1L, "fallbackUser", "defaultPass");
        return new CommonResult<>(fallbackUser);
    }
}

Chú thích @HystrixCommand

Chú thích này cho phép Hystrix bao bọc việc thực thi phương thức, từ đó kích hoạt các tính năng như ngắt mạch, cách ly luồng và xử lý dự phòng. Một số tham số quan trọng:

  • fallbackMethod: tên phương thức dự phòng khi lỗi xảy ra.
  • ignoreExceptions: danh sách các ngoại lệ không kích hoạt fallback.
  • commandKey: định danh duy nhất cho lệnh Hystrix.
  • groupKey: nhóm lệnh dùng để thống kê và giám sát.
  • threadPoolKey: tên nhóm luồng riêng biệt để cách ly tài nguyên.

Giám sát đơn thể với Hystrix Dashboard

Hystrix Dashboard cung cấp giao diện trực quan để theo dõi trạng thái thực thi lệnh Hystrix, tỷ lệ thành công/thất bại và trạng thái ngắt mạch.

Tạo module hystrix-dashboard với các phụ thuộc:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Cấu hình application.yml:

server:
  port: 8501
spring:
  application:
    name: hystrix-dashboard
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/

Kích hoạt dashboard bằng chú thích @EnableHystrixDashboard:

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

Giám sát cụm dịch vụ với Turbine

Để tổng hợp dữ liệu Hystrix từ nhiều instance, Netflix Turbine được sử dụng để thu thập và xuất luồng dữ liệu tập trung.

Tạo module turbine-service với phụ thuộc:

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

Cấu hình Turbine trong application.yml:

server:
  port: 8601
spring:
  application:
    name: turbine-service
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
turbine:
  app-config: hystrix-service
  cluster-name-expression: "'default'"
  combine-host-port: true

Kích hoạt Turbine bằng chú thích @EnableTurbine:

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

Thẻ: Spring Cloud Hystrix Turbine resilience Service Mesh

Đăng vào ngày 4 tháng 8 lúc 05:21