快捷搜索: 王者荣耀 脱发

SpringCloud路由网关之Gateway

服务网关

Ⅰ、路由网关之Zuul(停更)

Ⅱ、路由网关之Gateway

1、Gateway简述

  1. Gateway 介绍 使用了webflux的reactor-netty响应式编程组件,底层使用了Netty通讯框架
  2. Gateway 功能介绍 反向代理 鉴权 流量控制 熔断 日志监控…
  3. Gateway 架构位置在服务器负载均衡之后
  4. Gateway 的优势 基于spring 5,spring boot 2.0,project Reactor构建 动态路由: 对路由指定断言和过滤 集成Hystrix断路器功能 继承了spring cloud 服务发现 限流和路径重写…
  5. Gateway 工作流程

2、Gateway入门

实现:Eureka + Gateway

  1. pom <!--注意:gateway中需要移除这个 --> <!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> <version>2.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.5.RELEASE</version> </dependency>
  2. yml server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名进行动态路由 routes: - id: payment_routh #payment_routh #路由的ID,没有固定规则,但要求唯一,建议配合服务名 uri: http://localhost:8081 #匹配后提供服务的路由地址 没有进行负载均衡 类似反向代理 predicates: - Path=/provider/** #断言,路径相匹配的进行路由 - id: payment_routh2 #payment_routh #路由的ID,没有固定规则,但要求唯一,建议配合服务名 uri: lb://eureka-client-provider #eureka-client-provider匹配后提供服务的路由地址 动态路由 predicates: - Path=/eurakeprovider/** #断言,路径相匹配的进行路由 eureka: instance: hostname: cloud-gateway-service client: fetch-registry: true # false表示自己就是注册中心。我的职责就是维护服务实例,并不需要去检索服务 register-with-eureka: true # false表示自己不需要向注册中心注册自己 service-url: # 设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址(单机版) defaultZone: http://localhost:7003/eureka/ #defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ # 集群版 扩展predicates: 扩展filters: 注意:predicates与filters 有优先级取舍
  3. main application @SpringBootApplication @EnableEurekaClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
  4. 服务提供方(yml 中 payment_routh2:需要成为Eureka的客户端) @RestController public class ProviderController { @Value("${server.port}") private String port; @Autowired DiscoveryClient discoveryClient; @RequestMapping("/provider/test") public String test() { return "获取服务端ProviderTest端口号:" + port; } /**方法体随便 主要是RequestMapping 要与路由配置一致*/ @RequestMapping("/eurakeprovider/discoveryClient") public Object discoveryClient() { List<String> list = discoveryClient.getServices(); list.stream().forEach(System.out::println); List<ServiceInstance> list1 = discoveryClient.getInstances("EUREKA-CLIENT-ORDER"); list1.stream().map(x -> x.getServiceId() + ":" + x.getHost() + ":" + x.getPort() + ":" + x.getUri()).forEach(System.out::println); return discoveryClient; } }
  5. 测试 http://localhost:9527/provider/test http://localhost:9527/eurakeprovider/discoveryClient
经验分享 程序员 微信小程序 职场和发展