java
新建 Zuul 子模块
Zuul 服务网关体验
依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>springcloud</artifactId> <groupId>com.qn</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion>
<artifactId>zuul</artifactId>
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> </dependencies>
</project>
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| spring: application: name: zuul server: port: 8773
eureka: client: serviceUrl: defaultZone: http://localhost:9999/eureka/
provider-user: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
zuul: routes: hello: path: /producer/** serviceId: provider-user
|
启动类
1 2 3 4 5 6 7 8
| @SpringBootApplication
@EnableZuulProxy public class ZuulApp { public static void main(String[] args) { SpringApplication.run(ZuulApp.class,args); } }
|
熔断器 Filter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| @Component public class ApiFallbackProvider implements FallbackProvider { @Override public String getRoute() { return "provider-user"; }
@Override public ClientHttpResponse fallbackResponse(String route, Throwable cause) { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.OK; } @Override public int getRawStatusCode() throws IOException { return 200; } @Override public String getStatusText() throws IOException { return "{code:0,message:service error =_=}"; } @Override public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream(getStatusText().getBytes() ); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } };
} }
|
测试
- 启动 Eureka 客户端、三个提供者服务(不同端口)、Zuul 网关模块,访问地址:http://localhost:8773/producer/user/1
- 访问 15 次,发现请求是随机访问到三个提供者服务(说明自定义的负载均衡策略生效了,zuul 默认的负载均衡策略是轮询)。
- 关掉两个提供者服务,再次请求以上地址,发现可能返回服务降级内容(不超过两次)。
- 关掉最后一个提供者,再次请求会返回服务降级内容(说明熔断器生效)。
参考资料
[菜鸟 SpringCloud 实战入门]第九章:服务网关 Zuul 体验