springCloud(16):使用Zuul构建微服务网关-容错回退与高可用
一、容错与回退
1.1、容错
在Spring Cloud中,Zuul默认已经整合了Hystrix。
测试:
a、依次启动eureka-server(4010)、provide-user(4011)、hystrix-consumer-movie(5012)、microservice-gateway-zuul(5016)、hystrix-dashboard(5013)
b、访问http://localhost:5016/hystrix-consumer-movie/user/1,可正常获取结果
c、访问http://localhost:5016/hystrix.stream,可获取监控数据
d、访问http://localhost:5013/hystrix,并在监控地址栏上填写http://localhost:5016/hystrix.stream
总结:Zuul的Hystrix监控的粒度是微服务,而不是某个API;同时也说明,所有经过Zuul的请求,都会被Hystrix保护起来
e、关闭hystrix-consumer-movie,再次访问http://localhost:5016/hystrix-consumer-movie/user/1,将会出现异常。那么如何为zuul实现回退呢?
1.2、为Zuul添加回退
要为Zuul添加回退,需要实现ZuulFallBackProvider接口。在实现类中指定为哪个微服务提供回退,并提供一个ClientHttpResponse作为回退响应。
a、新建一个maven工程、添加zuul依赖,此处端口为5018
b、新建回退类
package com.liuy.fallback;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
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;
/**
* 电影微服务添加回退
* @description 电影微服务添加回退
* @author luis
* @version 1.0
* @date:2017年8月24日上午11:11:23
*/
public class MovieFallBack implements ZuulFallbackProvider {
@Override
public String getRoute() {
// 表明是哪个微服务提供回退
return "hystrix-consumer-movie";
}
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpHeaders getHeaders() {
// headers设定
HttpHeaders headers = new HttpHeaders();
MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
headers.setContentType(mt);
return headers;
}
@Override
public InputStream getBody() throws IOException {
// 响应体
return new ByteArrayInputStream("电影微服务不可用,请稍后再试。".getBytes());
}
@Override
public String getStatusText() throws IOException {
// 状态文本,此处返的OK,详见HttpStatus
return this.getStatusCode().getReasonPhrase();
}
@Override
public HttpStatus getStatusCode() throws IOException {
// fallback时的状态码
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
// 数字类型的状态码,此处返的200,详见HttpStatus
return this.getStatusCode().value();
}
@Override
public void close() {
}
};
}
}c、关闭hystrix-consumer-movie,再次访问http://localhost:5018/hystrix-consumer-movie/user/1
未完,待续。。。
本文出自 “我爱大金子” 博客,请务必保留此出处http://1754966750.blog.51cto.com/7455444/1958962
