spring cloud中代理服务器zuul的使用

spring cloud中代理服务器zuul的使用

主流网关:

    zuul

    kong 基于nginx的API Gateway

    nginx+lua

1、新建项目,选择eureka discovery 和zuul

 

2、启动类中增加 @EnableZuulProxy

 

3、修改配置文件后缀名为yml,并在配置中增加端口号、应用名称和注册中心地址,如下:

    server:

     port: 9000

    spring:

     application:

        name: api-gateway

 

    eureka:

     client:

        service-url:

         defaultZone: http://localhost:7880/eureka #注册中心地址

        

4、访问

http://192.168.136.128:8651/api/v1/orderfeignhystrix/save?userId=2&productId=2

修改为

http://192.168.136.128:9000/orderfeignhystrix-service/api/v1/orderfeignhystrix/save?userId=2&productId=2

 

 

http://192.168.136.128:8765/api/v1/product/list

修改为

http://192.168.136.128:9000/product-service/api/v1/product/list

 

5、自定义路由转发

zuul:

routes:

product-service: /apigateway/**

    

访问    

http://192.168.136.128:9000/apigateway/api/v1/product/list

 

6、环境隔离:

            需求 :不想让默认的服务对外暴露接口

                product-service/api/v1/product/list

 

            配置:

            zuul:

                ignored-patterns:

                    - /*-service/api/v1/product/list

可以访问

http://192.168.136.128:9000/apigateway/api/v1/product/list

不可以访问

http://192.168.136.128:9000/product-service/api/v1/product/list        

原生地址仍旧可以访问

http://192.168.136.128:8765/api/v1/product/list

 

7、三个注意事项:

    1)、路由名称定义问题

        路由映射重复覆盖问题

        zuul:

         routes:

            product-service: /apigateway/**

            orderfeignhystrix-service-service: /apigateway/**

        这样会覆盖,product-service会无法访问

        可以增加子目录来区分

        zuul:

         routes:

            product-service: /apigateway/product/**

            orderfeignhystrix-service-service: /apigateway/order/**

    2)、Http请求头过滤问题(在 routers类中可以看到这个定义sensitiveHeaders)

        默认session等请求是关闭的

        "Cookie", "Set-Cookie", "Authorization"

        在yml文件中增加zuul的routes属性sensitiveHeaders:

        修改后为

        zuul:

         routes:

            product-service: /apigateway/product/**

            orderfeignhystrix-service: /apigateway/order/**

         ignored-patterns:

            - /*-service/api/v1/product/list

         sensitiveHeaders:

        测试方法:在order服务的controller的save中增加代码,并使用postman测试,增加如下代码

         String token = httpServletRequest.getHeader("token");

String session=httpServletRequest.getHeader("session");

System.out.println("token is:"+token);

System.out.println("session is:"+session);

        使用postman进行测试

            http://192.168.136.128:9000/orderfeignhystrix-service/api/v1/orderfeignhystrix/save?userId=2&productId=2

            增加header中的session和token属性

            

    3)、过滤器执行顺序问题 ,过滤器的order值越小,越先执行

        

原文地址:https://www.cnblogs.com/programer-xinmu78/p/10546496.html