SpringCloud integration Hystrix
Since the service may call the caller to hang up the service provider, the caller to the service integration Hystrix
The introduction of dependence
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
Start to open the main breaker
@SpringBootApplication
@EnableEurekaClient
//开启断路器
@EnableCircuitBreaker
public class SaleApp {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(SaleApp.class).web(true).run(args);
}
}
Services modified call service
@Service
//对这个类采用全局默认的回退机制,回退方法不能带参数,例如:“getMemberFallback”没有参数
//@DefaultProperties(defaultFallback = "getMemberFallback")
public class MemberService {
@Autowired
private RestTemplate restTpl;
//1、@HystrixCommand、@HystrixProperty这些注解不是SpringCloud注解,而是Hystrix框架提供的
//2、fallbackMethod当修饰具体方法时,fallbackMethod方法的参数和修饰方法保持一致
@HystrixCommand(fallbackMethod = "getMemberFallback", groupKey = "MemberGroup", commandKey = "MemberCommandKey",
commandProperties = {
//超时熔断
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
}, threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2")
})
public Member getMember(Integer id) {
try {
Thread.sleep(500);
} catch (Exception e) {
}
Member member = restTpl.getForObject(
"http://spring-hy-member/member/{id}", Member.class, id);
return member;
}
public Member getMemberFallback(Integer id) {
Member m = new Member();
m.setId(1);
m.setName("error member");
return m;
}
}
Note:
@DefaultProperties: You can configure global fallback mechanism, the fallback method does not take parameters, such as: "getMemberFallback" no parameters
@ HystrixCommand, @ HystrixProperty these annotations are not SpringCloud comment, but Hystrix framework provided
fallbackMethod when modifying specific method, fallbackMethod method of modifying parameters and methods consistent