本篇介绍并集成ZUUL

API getaway:
API Gateway是一个服务器,也可以说是进入系统的唯一节点。这跟面向对象设计模式中的Facade模式很像。API Gateway封装内部系统的架构,并且提供API给各个客户端。它还可能有其他功能,如授权、监控、负载均衡、缓存、请求分片和管理、静态响应处理等。下图展示了一个适应当前架构的API Gateway。

clipboard.png
API Gateway负责请求转发、合成和协议转换。所有来自客户端的请求都要先经过API Gateway,然后路由这些请求到对应的微服务。API Gateway将经常通过调用多个微服务来处理一个请求以及聚合多个服务的结果。它可以在web协议与内部使用的非Web友好型协议间进行转换,如HTTP协议、WebSocket协议。

    Spring Cloud Zuul路由是微服务架构的不可或缺的一部分,提供动态路由,监控,弹性,安全等的边缘服务。Zuul是Netflix出品的一个基于JVM路由和服务端的负载均衡器。

新建Springboot项目,pom添加依赖

   <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>

application:

/**
    使用@EnableZuulProxy注解激活zuul。
 * 跟进该注解可以看到该注解整合了@EnableCircuitBreaker、@EnableDiscoveryClient,是个组合注解,目的是简化配置。
 
 */
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class,args);
    }
}

yml:

spring:
  application:
    name: microservice-api-gateway
server:
  port: 8000
eureka:
  instance:
    hostname: gateway
  client:
    serviceUrl:
      defaultZone: http://discovery:8761/eureka/
# 下面整个树都非必须,如果不配置,将默认使用 http://GATEWAY:GATEWAY_PORT/想要访问的Eureka服务id的小写/** 路由到:http://想要访问的Eureka服务id的小写:该服务端口/**
zuul:
  routes:
    user:                                               # 可以随便写,在zuul上面唯一即可;当这里的值 = service-id时,service-id可以不写。
      path: /user/**                                    # 想要映射到的路径
      service-id: userprovider         # Eureka中的serviceId

启动后这样就可以 用`http://GATEWAY:GATEWAY_PORT/想要访问的Eureka服务id的小写/**
访问微服务了

若想忽略某个微服务则可以配置
`zuul:
ignored-services: microservice-provider-user # 需要忽视的服务(配置后将不会被路由)`


陈小鹏
26 声望9 粉丝

physical