hystrix由来:服务器宕机或者依赖关系失败。
hystrix:
server:
port: 6003
eureka:
client:
service-url:
defaultZone: http://localhost:9001/eureka
instance:
instance-id: consumer6003
prefer-ip-address: true
spring:
application:
name: consumer3
3:启动类(App):
@SpringBootApplication
@EnableEurekaClient
@Configuration
@EnableHystrix
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4:控制器(HelloController):
@SuppressWarnings("unchecked")
@RestController
public class HelloController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/hi")
@HystrixCommand(fallbackMethod="helloFallback")
public Map<String,Object> hello(){
return restTemplate.getForObject("http://provider-one/hello", Map.class);
}
public Map<String,String> helloFallback(){
Map<String,String> map = new HashMap<String, String>();
map.put("info", "失败");
return map;
}
}
比较ribbo:
在方法上添加注解@HystrixCommand(fallbackMethod="helloFallback")
属性fallbackMethod的值是你要调用的方法
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- 断路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
2:修改配置文件(application.yml):
server:
port: 6004
eureka:
client:
service-url:
defaultZone: http://localhost:9001/eureka
instance:
instance-id: consumer6004
prefer-ip-address: true
spring:
application:
name: consumer4
3:启动类(App):
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@Configuration
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4:接口
@FeignClient(value = "provider-one",fallback=HelloServiceFallBach.class)
public interface HelloService {
@GetMapping("hello")
public Map<String,Object> h();
}
5:控制器
@RestController
public class HelloController {
@Autowired
private HelloService service;
@RequestMapping("jj")
public Map<String,Object> hello(){
return service.h();
}
}
6:错误返回控制器:
@Component
public class HelloServiceFallBach implements HelloService{
@Override
public Map<String, Object> h() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("info", "错误");
return map;
}
}
@Component别忘了加