Spring Cloud 之 Zuul 服务网关Gateway



Netflix  Zull介绍

zuul 是netflix开源的一个API Gateway 服务器, 本质上是一个web servlet应用。

Zuul 在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门。

Gateway(网关)是微服务架构的不可获取的一个部分,Gateway为客户点提供了统一访问的入口,Netflix Zuul是

Spring Cloud默认使用的Gateway组件

Zuul是Netflix出品的一个路由和服务端的负载均衡组件

Netflix  Zull创建

1、打开idea新建springBoot项目

扫描二维码关注公众号,回复: 11518422 查看本文章

创建完成项目后,可以发现pom.xml文件中的这两个依赖

  • spring-cloud-starter-netflix-eureka-client     注册为客户端
  • spring-cloud-starter-netflix-zull                    服务网关组件
        <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>

2、在项目的主类上添加注解

@EnableDiscoveryClient //注册客户端

@EnableZuulProxy //启用路由

package vip.ablog.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableDiscoveryClient   //注册客户端
@EnableZuulProxy   //启用路由
//Zuul路由的访问规则是 :  http://xxxxx:xxx/server-id/...
//                       这里的server-id值得就是Server的application.name
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

3、编辑配置文件application.yml配置文件,进行编辑

这里的 zull-routes:代表客户端访问的路由地址;

在启用网关以后,客户端访问所有的接口都采用统一规则进行访问:

Zuul路由的访问规则是 : http://xxxxx:xxx/server-id/...    //这里的server-id 的值就是Server的application.name

spring:
  application:
    name: gateway
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9001/eureka/
server:
  port: 7000
zuul:
  routes:
    client: /c/**
    member: /m/**
    book: /b/**

4、现在我们启动application,访问注册中心registery,即可看到网关Gateway在此注册,现在我们就可以通过网关访问client  member了

5、上图可以看到客户端member的端口虽然是8000,但是我们可以访问网关的7000端口再加上我们网关配置文件中设置的路由地址即可访问客户端member

猜你喜欢

转载自blog.csdn.net/Allan_Bst/article/details/80958283