参考链接:https://blog.csdn.net/chenhaotao/article/details/78716608?locationNum=10&fps=1
熔断器:当服务不可用的时候迅速返回一个错误而不是超时等待
1\引入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2\ 添加注解@EnableHystrix开启hystrix功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class CustomerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
// 这次我们使用了OkHttp客户端,只需要注入工厂即可
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class, args);
}
}
3\添加注解@HystrixCommand(fallbackMethod = “method”)指定熔断点并指定熔断方法
@RestController
public class CustomerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;// Eureka客户端,可以获取到服务实例信息
@RequestMapping("/customer")
@HystrixCommand(fallbackMethod = "testError")
public String queryUserById(){
List<String> users = new ArrayList<>();
// 地址直接写服务名称即可
String baseUrl = "http://userserver/user/7/";
System.out.println(baseUrl);
// 我们测试多次查询,
users.add(this.restTemplate.getForObject(baseUrl, String.class));
return users.toString();
}
public String testError(){
return "sorry, "+"访问 SERVICE-HELLO服务 出错";
}
}
Feign
Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。
feign已经自带断容器不需要再单独引用hystrix依赖,只不过在feign中熔断器功能默认是未打开的,需要在配置文件中开启。
在application.yml中开启熔断器
feign:
hystrix:
enabled: true
导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
还要再加一个,不然会报错:java.lang.IllegalStateException: Failed to introspect Class
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>compile</scope>
</dependency>
开启feign
@EnableFeignClients
@SpringCloudApplication
public class CustomerApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerApplication.class, args);
}
}
调用
@RestController
public class CustomerController {
@Autowired
private UserFeignClient userFeignClient;
@RequestMapping("/customer")
public String queryUserById(){
System.out.println("test feign");
return userFeignClient.testService();
}
}
FeignClient书写
@FeignClient(value ="userserver",fallback = FeignServiceFallback.class)
public interface UserFeignClient {
@GetMapping(value = "/user/7/")
String testService();
}
回滚函数书写
@Component
public class FeignServiceFallback implements UserFeignClient {
@Override
public String testService() {
return "ERRORS 111111111111111";
}
}
启动测试就,正常情况会调用userserver,如果userserver服务不可用们就会调用回滚函数FeignServiceFallback.