spring-cloud(7)、服务网关 — Zuul

  前面讲了注册中心、配置中心、客户端Ribbon调用、客户端Feign调用以及熔断器,下面来讲Spring-Cloud的另一个组件——服务网关,可以这么理解,原来客户端都是直接调用的服务端,现在在客户端调用服务端的过程中,插入一个过滤器,那就是服务网关。所以,现在的结构是客户端调用服务网关,服务网关做过滤后,再调用服务端,服务网关的职责更多像是一个过滤器,比如,安全、认证等功能,下面便详细说明。

  • 服务网关

  首先,服务网关需要单独的一个项目,新建一个服务网关的模块(gateway Module),服务网关调用服务端有两种方式,不同的方式依赖的jar也就不相同,比如,如果服务网关采用直接URL的话,则不需要依赖服务发现的Eureka的jar。本实例不采用直接URL的方式来说明,但是会提及直接URL,所以,POM如下。

<?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>cloud-demo</artifactId>
        <groupId>com.fzhsh.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>
</project>

  接着,编写主启动类,并采用@EnableZuulProxy

package com.fzhsh.cloud.gateway;

@SpringCloudApplication
@EnableZuulProxy
public class GatewayApp {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApp.class, args);
    }
}

  然后,配置配置文件application.yml,如果使用的是直接URL,则不需要eureka.client.serviceUrl.defaultZone,并且将zuul.routes.test.serviceId改为zuul.routes.test.uri,并填写上服务端的网址(http://localhost:8000/),其中test可以为任意名字,但尽量有意义。

spring:
  application:
    name: gateway

server:
  port: 8008

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8888/eureka/

zuul:
  routes:
    test:
      path: /**
      serviceId: server

  接着,前面说服务网关类似于过滤器,而且为了方便测试请求是否通过服务网关转发,故继承ZuulFilter,除了打印什么都不做,代码如下

package com.fzhsh.cloud.gateway.filter;

public class AccessFilter extends ZuulFilter{

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        System.out.println("access filter");
        return null;
    }
}

  最后,编写好过滤器代码后,实例化过滤器,使其生效

package com.fzhsh.cloud.gateway;

@SpringCloudApplication
@EnableZuulProxy
public class GatewayApp {

    @Bean
    public AccessFilter accessFilter(){
        return new AccessFilter();
    }

    public static void main(String[] args) {
        SpringApplication.run(GatewayApp.class, args);
    }
}
  • 改写客户端调用

  前面说过,客户端需要调用服务端,所以只需要将调用的地方修改,即可。

  Ribbon调用修改,将原来URL中的domain由原来的server改为gateway

package com.fzhsh.cloud.clent.service;

@Service
public class RibbonService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "timeout")
    public String get() {
        return restTemplate.getForObject("http://gateway/home", String.class);
    }

    public String timeout(){
        return "time out call";
    }
}

  Feign调用修改,只需要将@FeignClient的value,从server修改成为gateway

package com.fzhsh.cloud.clent.service;

@FeignClient(value = "gateway", fallback = CallClientHystrix.class)
public interface CallClient {

    @PostMapping("/concat")
    String concat(@RequestParam("str") String str);

}
test - home

    服务网关控制台显示

access filter
……
2017-06-14 00:34:04.293  INFO 8786 --- [nio-8008-exec-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client server initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=server,current list of Servers=[localhost:8000],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;    Instance count:1;    Active connections count: 0;    Circuit breaker tripped count: 0;    Active connections per server: 0.0;]
},Server stats: [[Server:localhost:8000;    Zone:defaultZone;    Total Requests:0;    Successive connection failure:0;    Total blackout seconds:0;    Last connection made:Thu Jan 01 08:00:00 CST 1970;    First connection made: Thu Jan 01 08:00:00 CST 1970;    Active Connections:0;    total failure count in last (1000) msecs:0;    average resp time:0.0;    90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;    max resp time:0.0;    stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@810ddc6

  服务端控制台显示

call home
  • 参考资料

http://cloud.spring.io/spring-cloud-static/Dalston.SR1/#_router_and_filter_zuul 

posted @ 2017-06-14 00:39  風之殤  阅读(113)  评论(0)    收藏  举报