欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringCloud Zuul网关功能实现解析

时间:2022-04-10 10:32:44|栏目:JAVA代码|点击:

简介

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

上一篇:SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码

栏    目:JAVA代码

下一篇:深入理解Java设计模式之迭代器模式

本文标题:SpringCloud Zuul网关功能实现解析

本文地址:http://www.codeinn.net/misctech/198759.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有