亲宝软件园·资讯

展开

SpringCloud Zuul网关 SpringCloud Zuul网关功能实现解析

玉天恒 人气:0

简介

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

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

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

加载全部内容

相关教程
猜你喜欢
用户评论