怎么在SpringCloud中利用Zuul实现一个网关功能

2023-10-27,

今天就跟大家聊聊有关怎么在SpringCloud中利用Zuul实现一个网关功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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

看完上述内容,你们对怎么在SpringCloud中利用Zuul实现一个网关功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注本站行业资讯频道,感谢大家的支持。

《怎么在SpringCloud中利用Zuul实现一个网关功能.doc》

下载本文的Word格式文档,以方便收藏与打印。