Hystrix项目使用
配置pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
配置RestTemplate对象
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate create() {
return new RestTemplate();
}
}
添加测试类
@RestController
public class HystrixController {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "failCallHello")
@GetMapping("/hello")
public String callHello() {
String result = restTemplate.getForObject("http://192.168.1.55:8081/hello", String.class);
return result;
}
public String failCallHello() {
return "Fail";
}
@HystrixCommand(fallbackMethod = "failCallHello", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") })
@GetMapping("/hello2")
public String callHello2() {
String result = "Ok";
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
}
- /hello测试程序异常
- /hello2测试超时异常
激活Hystrix,启动类添加注解@EnableHystrix
@EnableHystrix
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
准备
启动Eureka服务,并注册两个应用作为测试集群机器,如图所示;测试接口/hello
Feign项目使用
再添加配置pom.xml依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
封装Feign接口,eureka-provider-app
为注册到Eureka中的服务名称
@FeignClient(value = "eureka-provider-app", fallback = TestClientFailBack.class)
public interface TestClient {
@GetMapping("/hello")
String hello();
}
TestClientFailBack失败处理策略
@Component
public class TestClientFailBack implements TestClient{
@Override
public String hello() {
return "FAIL_fail";
}
}
添加测试类
@RestController
public class TestController {
@Autowired
private TestClient client;
@GetMapping("/test")
public String test() {
String result = client.hello();
return result;
}
}
激活Feign配置
@EnableFeignClients(basePackageClasses = {TestClient.class})
@EnableHystrix
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置文件application.properties添加Eureka注册配置,启动feign与hystrix整合
eureka.client.serviceUrl.defaultZone=http://192.168.1.55:8761/eureka/
feign.hystrix.enabled=true```
添加测试类
```java
@RestController
public class TestController {
@Autowired
private TestClient client;
@GetMapping("/test")
public String test() {
String result = client.hello();
return result;
}
}
测试,成功测试
停掉应用,测试