Spring Cloud学习笔记【七】服务网关 Zuul(路由)

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

准备工作

我们将用到之前实现的几个应用,包括:

  • eureka-server:服务注册中心
  • service-producer:服务提供者
  • service-consumer-ribbon:使用 Ribbon实现的服务消费者

首先创建一个基础的 Spring Boot 项目,命名为:service-api-gateway

POM 依赖

在pom.xml引入以下依赖

1 <dependency>
2     <groupId>org.springframework.cloud</groupId>
3     <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
4 </dependency>
5 <dependency>
6     <groupId>org.springframework.cloud</groupId>
7     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
8 </dependency>

配置文件

在配置文件 application.yml 中加入服务名、端口号、Eureka 注册中心的地址

server:
  port: 9100
spring:
  application:
    name: service-api-gateway
eureka:
  client:
    serviceUrl:
      defaultZone: http://admin:123456@localhost:8761/eureka/

启动类

使用@EnableZuulProxy注解开启 Zuul 的功能

 1 package com.carry.springcloud;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
 6 
 7 @EnableZuulProxy
 8 @SpringBootApplication
 9 public class ServiceApiGatewayApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(ServiceApiGatewayApplication.class, args);
13     }
14 }

测试

依次启动

  • eureka-server
  • service-producer
  • service-consumer-ribbon
  • service-api-gateway

由于 Spring Cloud Zuul 在整合了 Eureka 之后,具备默认的服务路由功能,即:当我们这里构建的service-api-gateway应用启动并注册到 Eureka 之后,服务网关会发现上面我们启动的两个服务service-producer和service-consumer-ribbon,这时候 Zuul 就会创建两个路由规则。每个路由规则都包含两部分,一部分是外部请求的匹配规则,另一部分是路由的服务 ID。针对当前示例的情况,Zuul 会创建下面的两个路由规则:

  • 转发到service-producer服务的请求规则为:/service-producer/**
  • 转发到service-consumer-ribbon服务的请求规则为:/service-consumer-ribbon/**

最后,我们可以通过访问9100端口的服务网关来验证上述路由的正确性:

浏览器中访问http://localhost:9100/service-consumer-ribbon/getPoducerInfo

 

posted @ 2018-08-28 10:13  CarryChan  阅读(535)  评论(0编辑  收藏  举报