SpringCloud网关zuul

2018-11-02  本文已影响0人  晓阳emmm

Zuul 简介

“Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application. As an edge service application, Zuul is built to enable dynamic routing, monitoring, resiliency and security. It also has the ability to route requests to multiple Amazon Auto Scaling Groups as appropriate.”

大致是说zuul是设备和网站到Netflix后台应用程序的所有的请求的前门,是一个边缘化应用程序,它的创建是为了实现动态路由,监控,弹性,和安全性, 它还能够根据需要将请求路由到多个Amazon Auto Scaling组。

来源'https://github.com/Netflix/zuul/wiki'

zuul主要实现的功能就是API Gateway(api网关)的功能

为什么使用api gateway:

在springcloud使用zuul:

​ 1、除了添加eureka依赖外,添加zuul依赖包:

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-eureka</artifactId>

</dependency>

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-zuul</artifactId>

</dependency>

​ 2、在启动类上使用@EnableZuulProxy 启用zuul

@SpringBootApplication

@EnableZuulProxy

public class ZuulApplication {

    public static void main(String[] args) {

        SpringApplication.run(ZuulApplication.class, args);

    }

}

​ 3、配置文件application.yml

spring:
    application:
        name: micoserice-gateway-zuul

server:
    port: 8090
eureka:
    client:
        serviceUrl:
            defaultZone: <http://localhost:8761/eureka/>

    instance:
        prefer-ip-address: true
        instance-id: ${spring.application.name}:${server.port}

启动运行:

img

如图我这里启动了三个服务,zuul注册到Eureka-service为服务后默认情况下是构建PAI-GATEWAY,访问时只要zuul-host/appname/api

如我这里访问:http://localhost:8090/micoserice-user/user/getuser,当调用服务有多个时,zuul是实现了负载均衡的。

zuul中使用hystrix的回退

代码如下

/**

* @author wxy

* zuul中使用hystrix的回退

*/

@Component

public class MyFallbackProvider implements ZuulFallbackProvider {

    @Override

    public String getRoute() {
        //路由配置micoserice-user,如果全部用"*"代替
        return "micoserice-user";

    }

    @Override

    public ClientHttpResponse fallbackResponse() {

        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 "ok";

            }

            @Override
            public void close() { }

            @Override
            public InputStream getBody() throws IOException {
                //回退响应体
                return new ByteArrayInputStream("服务不可用稍后再试".getBytes());

            }

            @Override
            public HttpHeaders getHeaders() {
                //header设置
                HttpHeaders headers = new HttpHeaders();
                MediaType mediaType = new MediaType("application","json", Charset.forName("UTF-8"));
                headers.setContentType(mediaType);
                return headers;

            }

        };

    }

}

添加回退后当访问micoserice-user 微服务失败后将会返回“服务不可用稍后再试”。

zuul过滤器

/**
* @author wxy
* zuul过滤器
* zuul中定义了四种标准过滤类型,这些过滤类型对应请求的生命周期
*
* PRE:这种过滤类型在请求被路由之前调用。可利用这种过滤器实现身份验证,在集群中选择请求的微服务,记录调试信息等。
*
* ROUTING:这种过滤器将请求路由到微服务。这种过滤用于构建发送给微服务的请求,
* 并可以使用Apache HttpClient,Fegin,Ribbon请求微服务。
*
* POST:这种过滤器在路由到微服务以后执行。这种过滤器可用来微响应添加标准的http header,
* 搜集统计信息和指标,将响应发送给客户端。
*
* ERROR:在其他阶段发生错误时执行该过滤器。
*
*/

public class RequestLogFilter extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(RequestLogFilter.class);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

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

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

    @Override
    public Object run() {
        RequestContext requestContext =RequestContext.getCurrentContext();
         HttpServletRequest request = requestContext.getRequest();
        logger.info(String.format("send %s request to %s",request.getMethod(),request.getRequestURL().toString()));
        return null;
    }

}

//在启动类下添加Bean

@Bean
public RequestLogFilter getRequestLogFilter(){
return new RequestLogFilter();

}

示例代码:microservice-gateway-zuul
本文参考
http://cloud.spring.io/spring-cloud-static/Finchley.M2/#_router_and_filter_zuulhttp://www.ityouknow.com/springcloud/2017/06/01/gateway-service-zuul.html
http://microservices.io/patterns/apigateway.html

上一篇 下一篇

猜你喜欢

热点阅读