Bắt đầu với mã nguồn:
Phía máy chủ:
Trong phương thức của máy chủ, đoạn code 10/0 chắc chắn sẽ gây ra lỗi.
@Autowired
private PaymentService paymentService;
@GetMapping("/payment/hystrix/errorInfo")
public CommonResult handleError() {
String result = paymentService.generateError();
log.info("*******result:" + result);
if (result.equals("Lỗi dịch vụ")) {
return new CommonResult(302, "Dịch vụ gặp sự cố", null);
}
return new CommonResult(200, "Thành công", null);
}
package com.example.microservices.service;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class PaymentService {
public String generateError() {
try {
int number = 10 / 0;
} catch (Exception e) {
e.printStackTrace();
return "Lỗi dịch vụ";
}
return "Thành công";
}
}
Mã phía khách hàng:
PAYMENT_URL là tên dịch vụ của máy chủ
@GetMapping("/consumer/payment/errorInfo")
public CommonResult handleClientError() {
try {
ResponseEntity<CommonResult> response = restTemplate.getForEntity(PAYMENT_URL + "/payment/hystrix/errorInfo", CommonResult.class);
if (response.getStatusCode().is2xxSuccessful()) {
log.info("Mã trạng thái phản hồi: " + response.getStatusCode() + ", headers:" + response.getHeaders());
return new CommonResult<>(200, "Kết quả:" + response.getBody());
} else {
return new CommonResult<>(445, "Thất bại");
}
} catch (Exception e) {
e.printStackTrace();
return new CommonResult<>(556, "Có lỗi xảy ra khi gọi dịch vụ");
}
}
private static ExecutorService execService = Executors.newSingleThreadExecutor();
@GetMapping("/consumer/payment/timeoutCheck")
public CommonResult checkTimeout() {
try {
FutureTask<ResponseEntity<CommonResult>> futureTask = new FutureTask<>(new Callable<ResponseEntity<CommonResult>>() {
@Override
public ResponseEntity<CommonResult> call() throws Exception {
return restTemplate.getForEntity(PAYMENT_URL + "/payment/hystrix/errorInfo", CommonResult.class);
}
});
execService.execute(futureTask);
try {
ResponseEntity<CommonResult> result = futureTask.get(1, TimeUnit.MILLISECONDS);
return new CommonResult<>(200, "Kết quả:" + result.getBody());
} catch (InterruptedException | ExecutionException | TimeoutException e) {
futureTask.cancel(true);
return new CommonResult<>(667, "Gọi dịch vụ quá thời gian");
}
} catch (Exception e) {
e.printStackTrace();
return new CommonResult<>(556, "Có lỗi xảy ra khi gọi dịch vụ");
}
}
Cấu hình ứng dụng:
@Configuration
public class AppConfig {
@Bean
@LoadBalanced
public RestTemplate createRestTemplate() {
return new RestTemplate();
}
}
Kết quả từ phía máy chủ khi kích hoạt xử lý ngoại lệ:
Kết quả từ phía máy chủ khi không kích hoạt cài đặt thời gian chờ: