当服务超时,如果你没有配置熔断器,它会报超时,但是服务继续执行。而且超时的时间也要配置好,一般是2秒就断了,所以要配置一哈。
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 仪表盘依赖2 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
第一个是熔断器引入,后面2个是监控器来着。
在启动类添加注解
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableHystrixDashboard
@EnableHystrix
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
zuul也是作为一个服务来注册的。
@EnableHystrixDashboard仪表器注解,通过访问/hystrix然后输入/hystrix.stream点击按钮运行
https://www.cnblogs.com/leeSmall/p/8847652.html
这一篇主要将超时配置!所以其他的不重点写
application.yml
zuul:
routes:
zuul:
path: /zuul/**
serviceId: zuul
fans:
path: /fans/**
serviceId: fans
fans:
ribbon:
ConnectTimeout: 8000
# 请按实际情况配置
ReadTimeout: 8000
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 8000
还有一个是熔断器的降级
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
@Component
public class ConsumerFallbackProvider implements ZuulFallbackProvider {
@Override
public String getRoute() {
// 表明是为哪个微服务提供回退
return "fans";
}
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
// fallback时的状态码
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
// 数字类型的状态码,本例返回的其实就是200,详见HttpStatus
return this.getStatusCode().value();
}
@Override
public String getStatusText() throws IOException {
// 状态文本,本例返回的其实就是OK,详见HttpStatus
return this.getStatusCode().getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
// 响应体
return new ByteArrayInputStream("微服务不可用,请稍后再试。".getBytes());
}
@Override
public HttpHeaders getHeaders() {
// headers设定
HttpHeaders headers = new HttpHeaders();
MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));
headers.setContentType(mt);
return headers;
}
};
}
}