1.依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--hystrix仪表盘-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2.配置
server:
port: 6065
logging:
level:
com.d4c: debug
eureka:
instance:
prefer-ip-address: false
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://peer1:6001/eureka/,http://peer2:6002/eureka/
spring:
cloud:
loadbalancer:
retry:
enabled: true # 开启Spring Cloud的重试功能
application:
name: consumer-hystrix
ribbon:
restclient:
enabled: true #没有这个ribbon超时配置不会生效,是
ReadTimeout: 1000
ConnectTimeout: 300
MaxAutoRetries: 1 #同一台实例最大重试次数,不包括首次调用
MaxAutoRetriesNextServer: 1 #重试负载均衡其他的实例最大重试次数,不包括首次调用
#当OkToRetryOnAllOperations设置为false时,只会对get请求进行重试。
#如果设置为true,便会对所有的请求进行重试,如果是put或post等写操作,如果服务器接口没做幂等性,会产生不好的结果,所以OkToRetryOnAllOperations慎用。
OkToRetryOnAllOperations: false #是否所有操作都重试
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 # 设置hystrix的超时时间为6000ms
3.
启动类
@SpringBootApplication
@EnableDiscoveryClient//开启服务发现
@EnableCircuitBreaker//开启熔断器
@EnableHystrixDashboard//开启hystrix仪表盘
public class ConsumerHystrixpplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerHystrixpplication.class, args);
}
}
配置类
@Configuration
public class CommonConfig {
//方式二
@Bean
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
service
@Service
public class AccountConsumerService {
@Resource
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallback")
public String hystrixCommand(Long id) throws Exception {
String url = "http://account-demo/account/get/" + id;
String forObject = restTemplate.getForObject(url, String.class);
System.out.println("forObject = " + forObject);
return forObject;
}
public String fallback(Long id) {
return "I am fallback!";
}
}
controller
@RestController
@RequestMapping("consumer")
public class AccountConsumerController {
@Resource
private AccountConsumerService accountConsumerService;
@RequestMapping("fallback/{id}")
public String fallback(@PathVariable Long id) throws Exception{
String s = accountConsumerService.hystrixCommand(id);
return s;
}
}
参考 参考Spring Cloud官方文档第13、14、15章
网友评论