SpringCloud-API服务网关Zuul

SpringCloud微服务就是把一个大的项目拆分成多个小的模块,然后模块之间通过远程调用、服务治理的技术互相配合工作,随着业务的增加,项目也将会越来越庞大,接口数量也随之增加,对外提供服务的接口也会增加,运维人员对于这些接口的管理也会变得越来越难。另一方面对于一个系统来说,权限管理也是一个不可少的模块,在微服务架构中,系统被拆分,不可能每个模块都去添加一个个权限管理,这样系统代码重复、工作量大、后期维护也难。为了解决这些常见的架构问题,API网关应运而生。SpringCloudZuul是基于Netflix Zuul实现的API网关组件,它实现了请求路由、负载均衡、校验过滤、与服务治理框架的结合、请求转发是的熔断机制和服务的聚合等功能。

简单使用

新建一个SpringBoot项目,命名为api-gateway。添加如下依赖。

        <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>

在主类上使用@EnableZuulProxy注解开启API网关服务功能

@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {

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

配置文件

server.port=8082
spring.application.name=api-gateway
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/

#这里的配置是指,访问/myZuul/**,请求会转发到名称为zuul-client这个微服务,也可以这样zuul.routes.zuul-client=/myZuul/**
zuul.routes.myZuul.path=/myZuul/**
zuul.routes.myZuul.service-id=zuul-client
#设置不过滤cookies
zuul.routes.myZuul.sensitive-headers=

#排除某些路由,这样就可以禁止某些接口通过网关访问。如果是.yml,- /myZuul/index2
zuul.ignored-patterns=/myZuul/index2

新建一个SpringBoot项目,命名为zuul-client。添加如下依赖

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

启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ZuulClientApplication {

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

配置文件

server.port=8081
spring.application.name=zuul-client
#指定服务注册中心的地址,这样才能将我们的应用注册到服务注册中心
eureka.client.serviceUrl.defaultZone: http://localhost:8080/eureka/

新建一个Controller,里面写两个接口

@RestController
public class Controller {

    @GetMapping("/index1")
    public String index1(HttpServletRequest request){
        return "zuul-client index1";
    }

    @GetMapping("/index2")
    public String index2(){
        return "zuul-client index2";
    }
}

启动api-gateway和zuul-client将这两个服务注册到eureka。

我们在zuul-client写了两个接口,以/index1为例:

有了服务网关之后,我们可以通过以下方式来访问/index

(1)通过自身地址来访问:http://localhost:8081/index1

(2)通过服务网关来访问:http://localhost:8082/zuul-client/index1

(3)由第二种方法可以知道,通过服务网关来访问其它服务的接口,需要在地址中加上服务名称。这里要介绍的就是我们可以可以自定义服务名称,方法看api-gateway中的配置文件:

zuul.routes.myZuul.path=/myZuul/**
zuul.routes.myZuul.service-id=zuul-client

因此我们可以这样来访问:http://localhost:8082/myZuul/index1

猜你喜欢

转载自blog.csdn.net/lizc_lizc/article/details/82724724