(八十八)java版多租户社交电子商务平台-SpringClou
2019-06-19 本文已影响0人
IT达人Q
电子商务平台源码请加企鹅求求:三伍三六二四柒二五玖。SpringCloud整合Hystrix
由于服务调用者有可能调用服务挂掉的提供者,服务调用方整合Hystrix
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
主启动开启断路器
@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);
}
}
服务调用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;
}
}
注意:
@DefaultProperties:可以配置全局回退机制,回退方法不能带参数,例如:“getMemberFallback”没有参数
@HystrixCommand、@HystrixProperty这些注解不是SpringCloud注解,而是Hystrix框架提供的
fallbackMethod当修饰具体方法时,fallbackMethod方法的参数和修饰方法保持一致