一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

SpringCloud Zuul网关功能如何实现 SpringCloud Zuul网关功能实现代码解析

时间:2020-03-17 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下SpringCloud Zuul网关功能实现代码解析,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

简介

API Gateway,时系统的唯一对外的入口,介于客户端和服务端之间的中间层,处理非业务功能,提供路由请求,鉴权,监控,缓存,限流等功能。

统一接入

智能路由

AB测试、灰度测试

负载均衡、容灾处理

日志埋点(类似 Nignx日志)

流量监控

限流处理

服务降级

安全防护

鉴权处理

监控

机器网终隔离

1.添加依赖

注意SpringBoot和SpringCloud版本兼容


  org.springframework.cloud
  spring-cloud-starter-netflix-eureka-client


  org.springframework.cloud
  spring-cloud-starter-netflix-zuul



  com.alibaba
  fastjson
  1.2.28

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

热门栏目