springcloud (ten): service gateway zuul

In the previous article, we introduced that Eureka is used for service registration and discovery, Feign supports service invocation and load balancing, Hystrix handles service fuses to prevent fault spread, and Spring Cloud Config service cluster configuration center seems to have completed a microservice framework. .

We still think about one less question, how do external applications access various internal microservices? In the microservice architecture, back-end services are often not directly open to the caller, but routed to the corresponding service through an API gateway according to the requested url. When the API gateway is added, a wall is created between the third-party caller and the service provider. This wall communicates directly with the caller for permission control, and then distributes requests to the background server in a balanced manner.


Why do you need API Gateway

1. Simplify the complexity of client calls

In the microservice architecture mode, the number of instances of the backend service is generally dynamic, and it is difficult for the client to find the access address information of the dynamically changed service instance. Therefore, in order to simplify the front-end calling logic in microservice-based projects, API Gateway is usually introduced as a lightweight gateway. At the same time, API Gateway will also implement related authentication logic to simplify the complexity of calling each other between internal services.

2. Data pruning and aggregation

Generally speaking, different clients have inconsistent data requirements for display, such as mobile phone or web, or in a low-latency network environment or a high-latency network environment.

Therefore, in order to optimize the user experience of the client, API Gateway can tailor the general response data to suit the needs of different clients. At the same time, multiple API call logics can be aggregated to reduce the number of client requests and optimize the client user experience.

3. Multi-channel support

Of course, we can also provide different API Gateways for different channels and clients. The use of this mode is called Backend for front-end by another well-known method. In the Backend for front-end mode, we can target different Clients create their BFFs separately. For more information on BFFs, please refer to this article: Pattern: Backends For Frontends

4. Microservice transformation of legacy systems

For system systems, microservice transformation is usually due to more or less problems with the original system, such as technical debt, code quality, maintainability, scalability, and so on. The API Gateway model is also applicable to the transformation of this type of legacy system. Through the transformation of microservices, the problems in the original system can be gradually repaired, thereby improving the responsiveness of the original business. Gradually replace old implementations with new implementations by introducing layers of abstraction.

In the Spring Cloud system, Spring Cloud Zuul is an API gateway that provides load balancing, reverse proxy, and authority authentication.

Spring Cloud Zuul

Spring Cloud Zuul routing is an integral part of the microservice architecture, providing edge services for dynamic routing, monitoring, resiliency, security, and more. Zuul is a JVM-based routing and server-side load balancer produced by Netflix.

Below we use the code to understand how Zuul works

Simple to use

1. Add dependencies

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

import spring-cloud-starter-zuulpackage

2. Configuration file

spring.application.name=gateway-service-zuul
server.port=8888

#这里的配置表示,访问/it/** 直接重定向到http://www.ityouknow.com/**
zuul.routes.baidu.path=/it/**
zuul.routes.baidu.url=http://www.ityouknow.com/

3. Startup class

@SpringBootApplication
@EnableZuulProxy
public class GatewayServiceZuulApplication {

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

Startup classes are added @EnableZuulProxyto support gateway routing.

The simplest zuul case in history is configured

4. Test

Start the gateway-service-zuul-simpleproject, visit: in the browser, http://localhost:8888/it/spring-cloudand see that the page returns: http://www.ityouknow.com/spring-cloud the information of the page is as follows:

Let's take the sample code of the previous article as an spring-cloud-producerexample to test the redirection of the request and add in the configuration file:

zuul.routes.hello.path=/hello/**
zuul.routes.hello.url=http://localhost:9000/

start spring-cloud-producer, restart gateway-service-zuul-simple, access: http://localhost:8888/hello/hello?name=%E5%B0%8F%E6%98%8E, return:hello 小明,this is first messge

Indicates that the request for access gateway-service-zuul-simpleis automatically forwarded to spring-cloud-producer, and the result is returned.


Servicing

通过url映射的方式来实现zull的转发有局限性,比如每增加一个服务就需要配置一条内容,另外后端的服务如果是动态来提供,就不能采用这种方案来配置了。实际上在实现微服务架构时,服务名与服务实例地址的关系在eureka server中已经存在了,所以只需要将Zuul注册到eureka server上去发现其他服务,就可以实现对serviceId的映射。

我们结合示例来说明,在上面示例项目gateway-service-zuul-simple的基础上来改造。

1、添加依赖

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

增加spring-cloud-starter-eureka包,添加对eureka的支持。

2、配置文件

配置修改为:

spring.application.name=gateway-service-zuul
server.port=8888

zuul.routes.api-a.path=/producer/**
zuul.routes.api-a.serviceId=spring-cloud-producer

eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/

3、测试

依次启动 spring-cloud-eureka、 spring-cloud-producergateway-service-zuul-eureka,访问:http://localhost:8888/producer/hello?name=%E5%B0%8F%E6%98%8E,返回:hello 小明,this is first messge

说明访问gateway-service-zuul-eureka的请求自动转发到了spring-cloud-producer,并且将结果返回。

为了更好的模拟服务集群,我们复制spring-cloud-producer项目改为spring-cloud-producer-2,修改spring-cloud-producer-2项目端口为9001,controller代码修改如下:

@RestController
public class HelloController {
    
    @RequestMapping("/hello")
    public String index(@RequestParam String name) {
        return "hello "+name+",this is two messge";
    }
}

修改完成后启动spring-cloud-producer-2,重启gateway-service-zuul-eureka。测试多次访问http://localhost:8888/producer/hello?name=%E5%B0%8F%E6%98%8E,依次返回:

hello 小明,this is first messge
hello 小明,this is two messge
hello 小明,this is first messge
hello 小明,this is two messge
...

说明通过zuul成功调用了producer服务并且做了均衡负载。

网关的默认路由规则

但是如果后端服务多达十几个的时候,每一个都这样配置也挺麻烦的,spring cloud zuul已经帮我们做了默认配置。默认情况下,Zuul会代理所有注册到Eureka Server的微服务,并且Zuul的路由规则如下:http://ZUUL_HOST:ZUUL_PORT/微服务在Eureka上的serviceId/**会被转发到serviceId对应的微服务。

我们注销掉gateway-service-zuul-eureka项目中关于路由的配置:

#zuul.routes.api-a.path=/producer/**
#zuul.routes.api-a.serviceId=spring-cloud-producer

重新启动后,访问http://localhost:8888/spring-cloud-producer/hello?name=%E5%B0%8F%E6%98%8E,测试返回结果和上述示例相同,说明spirng cloud zuul默认已经提供了转发功能。

到此zuul的基本使用我们就介绍完了。关于zuul更高级使用,我们下篇再来介绍。

参考:

API网关那些儿

示例代码


作者:纯洁的微笑
出处:http://www.ityouknow.com/
版权归作者所有,转载请注明出处

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393366&siteId=291194637