您的位置:首页 > 编程语言 > Java开发

SpringCloud Zuul网关功能实现解析

2020-03-19 12:07 821 查看

简介

API Gateway,时系统的唯一对外的入口,介于客户端和服务端之间的中间层,处理非业务功能,

提供路由请求,鉴权,监控,缓存,限流等功能

  • 统一接入   智能路由
  •   AB测试、灰度测试
  •   负载均衡、容灾处理
  •   日志埋点(类似 Nignx日志)
  • 流量监控
        限流处理
    •   服务降级
  • 安全防护
        鉴权处理
    •   监控
    •   机器网终隔离

    1.添加依赖

    注意SpringBoot和SpringCloud版本兼容

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <!-- fastjson -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
    </dependency>

    2.添加启动类注解@EnableZuulProxy

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
    
    @SpringBootApplication
    @EnableZuulProxy
    public class ZuulgatewayApplication {
    
    public static void main(String[] args) {
    SpringApplication.run(ZuulgatewayApplication.class, args);
    }
    
    }

    3.修改application.yml配置

    默认访问规则

    http://gateway:port/service-id/**

    server:
    port: 9000
    eureka:
    client:
    serviceUrl:
    defaultZone: http://localhost:8761/eureka/
    
    spring:
    application:
    name: zuul-gateway
    
    #自定义路由映射
    #order-service是订单服务的名称,访问路径为
    #旧:  http://localhost:9000/order-serice/api/v1/order/find
    #新:  http://localhost:9000/apigateway/order/api/v1/order/find
    zuul:
    routes:
    #方法一:
    #  product-service: /apigateway/product/**
    #  order-service: /apigateway/order/**
    #方法二:
    product-route:    #路由名称,可以任意取
    service-id: product-service
    path: /apigateway/product/**
    order-route:
    service-id: order-service
    path: /apigateway/order/**
    #忽略整个服务,不对外提供接口
    #多个服务用逗号隔开product-service,order-service
    #即不能用http://localhost:9000/order-serice/api/v1/order/find方式访问
    # ignored-services: product-service
    #正则表达式忽略多个服务
    ignored-patterns: /*-service/**
    sensitive-headers:
    
    #zuul使用Ribbon负载均衡,所以要配置ribbon超时时间,否则很短
    host:
    connect-timeout-millis: 15000 #HTTP连接超时要比Hystrix的大
    socket-timeout-millis: 60000  #socket超时
    ribbon:
    ReadTimeout: 10000
    ConnectTimeout: 10000

    4.Zuul网关注意事项

    默认情况,请求头header不会传递Cookie,Set-Cookie,Authorization信息,这些信息会显示为空

    如果需要传递,则修改application.yml配置

    zuul: sensitive-headers:

    5.访问路径

    http://127.0.0.1:9000/apigateway/product/api/v1/product/find?id=1

    http://127.0.0.1:9000/apigateway/order/api/v1/order/test?product_id=1

    图1

    以上就是本文的全部内容,希望对大家的学习有所帮助

    您可能感兴趣的文章:

  • 内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签:  Spring Cloud Zuul 网关