Spring cloud中使用 Hystrix
前言
Hystrix 在Spring Cloud中使用了Netflix開發的Hystrix來實現熔斷器。可以稍微通過幾個簡單的代碼示例,學習Hystrix
導入依賴
<!-- 整合hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
代碼示例
開啓熔斷器
//開啓熔斷器
@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaclientApplication {
/**
* 實例化RestTemplate,通過@LoadBalanced註解開啓均衡負載能力.
* @return restTemplate
*/
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class, args);
}
}
業務實例代碼
這裏請求服務代碼就不寫了 可以查看 傳送門
容錯代碼
@Service
public class UserService {
@Autowired
RestTemplate restTemplate;
//服務發現對象
@Autowired
DiscoveryClient discoveryClient;
@HystrixCommand(fallbackMethod = "fallback")
public User getUser(int id){
//user微服務的名字 用來想此服務發送請求
String servceId = "user-server";
String url = "http://" + servceId + "/getUser?id=" + id;
System.out.println(url + " = " + url);
User forObject = restTemplate.getForObject(url, User.class);
return forObject;
}
/**
* 使用@HystrixCommand註解指定當該方法發生異常時調用的方法
* @param id id
* @return 通過id查詢到的用戶
*/
public User fallback(int id) {
return new User(1,"test 用戶 ","查詢用戶異常!","1");
}
}
controller 調用
@RestController
public class GetUserController {
@Autowired
private UserService userService;
@RequestMapping("get")
public User getUser(int id){
return userService.getUser(id);
}
}
實體類User
public class User {
private int id;
private String name;
private String sex;
private String count;
public User() {
}
public User(int id, String name, String sex, String count) {
this.id = id;
this.name = name;
this.sex = sex;
this.count = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
可以看到異常容錯