Spring Cloud 微服务二:API网关spring cloud zuul

前言:本章将继续上一章Spring Cloud微服务,本章主要内容是API 网关,相关代码将延续上一章,如需了解请参考:Spring Cloud 微服务一:Consul注册中心

  • Spring cloud zuul概览
  • zuul 是netflix开源的一个API Gateway 服务器, 本质上是一个web servlet应用。Zuul 在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。Spring对zuul进行了整合,使开发者能够很方便地使用zuul
  • 集成zuul
    • 延续上一个项目,新建module api-gateway-zuul pom中添加zuul的依赖
        <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-zuul</artifactId>
          </dependency>
    •  在启动类中添加@EnableZuulProxy注解,启用zuul
      @SpringBootApplication
      @EnableZuulProxy
      public class ApiGatewayApplication {
          public static void main(String[] args) {
              SpringApplication.run(ApiGatewayApplication.class, args);
          }
      }
    • 修改配置文件application.yml,设置相关路由,url为上一章中consul消费者的地址
      server:
        port: 8080
      spring:
        application:
          name: api-gateway-zuul
      zuul:
        routes:
          user:
            path: /user/**
            url: http://localhost:10080/
      debug: true
    • 分别启动user-service,user-consumer,api-gateway-zuul,访问 http://localhost:8080/user/users, 能够正常返回信息,说明路由已成功
    • 服务化,使用url配置路由在微服务场景下非常不方便,为此,zuul支持另外一种配置:使用serviceId
      server:
        port: 8080
      spring:
        application:
          name: api-gateway-zuul
        cloud:
          consul:
            host: localhost
            port: 8500
            discovery:
              register: false
      zuul:
        routes:
          user:
            path: /user/**
            serviceId: user-service
      debug: true

      使用serviceId替换url,值为服务提供者Id

    • 重启api-gateway-zuul,访问 http://localhost:8080/user/all, 能够正常返回信息,说明路由已成功

 

原文地址:https://www.cnblogs.com/csts/p/10276277.html