SpringCloud Netflix Zuul

The concept of the gateway

Service A, B are exposed for external direct calls,

Sometimes the need to filter requests, verification, such as testing whether the user has logged in, you can write in each service exposed but to write the same code across multiple services, too cumbersome, can be put forward, on the gateway.
If A, B clustering, load balancing needed to determine the use of A | B which node to handle, you can use the gateway for routing forwarding (load balancing).
A gateway service level corresponding to the foregoing, a service entrance, a request can be unified by filtration, check, the routing can be achieved.

Ribbon achieve internal service load balancing (C, D), the gateway exposed achieve load balancing and services (A, B).

No direct access to external services A, B, but access gateway to access the A, B through the gateway.

If A, B do not cluster, each gateway are forwarded to the A | B fixed node (because the service only this one node), static, static, known as static routing.

If A, B cluster, this may be forwarded to the A | B is a node, the next may be forwarded to the A | B of another node, the forwarding node is not fixed, it will change the dynamic, called dynamic routing .

If the gateway cluster, the need Nginx load balancing to determine which gateway nodes.

Zuul is a technology gateway, a framework, but also the Netflix home, was SpringCloud integrated.

Zuul routing forwarding using
(1) a new sub-module api-gateway

(2) pom.xml

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

As the gateway to Eureka client because the Eureka server to obtain service from a list of nodes, using the built-in Ribbon Eureka client load balancing.

So the configuration Eureka client should have.

(3) bootstrap class

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy //也可以使用@EnableZuulServer
public class GatewayApplication {

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

}

Ribbon is used by default polling, exactly the same if you want to use other strategies to modify the way and the Ribbon.

(4)application.properties

gateway config###

# Use port
server.port = 11001

# Services provided, the service name
spring.application.name = api-gateway

# 2 configured as a set, multiple sets may be arranged
at the beginning # zuul.routes is fixed, the end is fixed path, service-id, the set id corresponding to an intermediate portion arranged, can easily take
# mapped address
zuul.routes .user-service.path = / user-server / **
service to map #
zuul.routes.user-service.service-id = user- server

# Registered to the Eureka server
eureka.client.serviceUrl.defaultZone = http: //127.0.0.1: 9001 / eureka /

# The local address, the line should be changed on the machine when the actual IP
eureka.client.ipAddress = 127.0.0.1
# instance name to ip: port register to the server in the form of
eureka.instance.instance-id = e in r e k a . c l i e n t . i p A d d r e s s : {eureka.client.ipAddress}: {server.port}

# When registering the node IP precedence, the default is false-- register the host name
eureka.instance.prefer-ip-address = true

# How often sends a heartbeat, default 30s, can be set shorter debugging
# eureka.instance.lease-renewal-interval-in -seconds = 30

Request address: http: // ip: port / user-server / user / order / {user_id}

Use Gateway (Zuul) of ip: port, followed by the service name mapped path (not the service name, service name and path but I set the same as above)

Will automatically find the corresponding service name (service_id) based on path, load balancing to determine which node to use the service. Different services (those services exposed) is mapped to a different path.

You can add a prefix:

zuul.prefix = / api
requested address: the request address: http: // ip: port / api / user-server / user / order / {user_id} front address mapping added

ajax's url, link href, the action request to write the above address.

After you call the consumer (exposed by the service), it does not call, but the use of the above url, to call through the gateway,

The equivalent of a Gateway Interface (API), to provide the address of the gateway, path services for external calls, the gateway (gateway) also known as API gateway.

Gateway did not cluster here, so the direct use of the gateway ip: port, a request to the gateway;

If the gateway to a cluster, you need to use Nginx to do load balancing gateway, requests to Nginx.

Zuul filtered using the request
to create a new packet filter, a new class MyFilter the package:

@Component // into the spring container can automatically use this interceptor
public class MyFilter extends ZuulFilter {// need to inherit ZuulFilter

//指定过滤时机
//String类型,"pre"——路由转发之前,"routing"——路由转发之时,"post"——路由转发之后,"error"——发生错误时
@Override
public String filterType() {
    return "pre";
}


//设置此拦截器的执行顺序
// 因为可能有多个拦截器,设置一个int型的值,数值越小,优先级越高、越先执行
@Override
public int filterOrder() {
    return 0;
}


//是否要进行过滤,即是否要使用此过滤器,这个需要改一下,因为默认为false
@Override
public boolean shouldFilter() {
    return true;
}


//核心方法,进行过滤
@Override
public Object run() {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();
    //获取传递的参数、验证权限
    String token = request.getParameter("token");
    //token要和数据库查到的进行比较,此处随便写一个代替
    if (token==null || !token.equals("123456")) {
        //直接就返回响应了,请求终止,不再转发给服务
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(400);
        //把提示信息显示到页面
        try {
            currentContext.getResponse().getWriter().write("token is invalid");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

}

Description
request gateway filter will filter all requests for exposed services, it is generally write generic filter, such as login status check, if not universal, write in the service.

If the service is not exposed cluster, you can not use a gateway, directly to request a service node.

SpringMVC use file upload file upload, but the size of the default gateway to upload files requested size is limited, we need to configure the look in application.properties gateway:

# Maximum size of uploaded files, the default 1MB
spring.servlet.multipart.max-File-size = 2000MB
# requested maximum size, default 10MB
spring.servlet.multipart.max-Request-size = 2500MB

Can be used on the boot class @ EnableZuulProxy, @ EnableZuulServer, these two notes almost all the same, the difference is small:

To inherit implementing filter ZuulFilter class, the opportunity to specify filter, this class has many subclasses These subclasses have been specified timing, we can inherit directly with, so do not specify the timing of the filter, use @EnableZuulServer, a small number of subclass impossible, little effect.

We do not recommend the use of a large number of filters, because it will increase the time overhead, down performance.

Published 78 original articles · won praise 9 · views 6190

Guess you like

Origin blog.csdn.net/WANXT1024/article/details/104401806