Springcloud microservices Series--Service Gateway Components Zuul

Source: Internet
Author: User

Preface

https://img-blog.csdn.net/20180803175652889?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lleWF6aGlzaGFuZw==/ Font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70

可以看出,该系统架构图包含了服务注册中心eureka-server作为服务注册中心,config-server作为配置中心获取远程Git地址的配置文件信息,在服务的请求处还做了负载均衡,服务之间做了集群分布,实现了高可用,服务之间还可以实现相互调用,由此可见,一个简易的微服务系统就搭建成了。
Elicit Zuul

The above architecture already contains the basic functionality of the microservices system, but there are still shortcomings:
The first is the uncertainty of service routing, in the previous study, we realized the load balance through the way of Resttemplate+ribbon and feign client, can realize the consumption of the high available service, but the kind of load processing which is called directly based on the service name is not complete, We need to have a more powerful gateway control tool.
Second, there is a lack of calibration function, when we need to access the interface within the cluster, to achieve external service access, we have to add the verification logic on the original interface, so that there is a coupling between the service, not in line with the purpose of development.
For these shortcomings, Spring Cloud provides Zuul components to be perfected.
The main function of Zuul is routing forwarding and filtering. The routing feature is part of the microservices, such as/api/user forwarding to the User Service, and/api/shop forwarding to the shop service. Zuul default and Ribbon combine to achieve load balancing function, after joining the Zuul, the Micro Service architecture will become more perfect, the frame composition is as follows:
https://img-blog.csdn.net/20180803175708387?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lleWF6aGlzaGFuZw==/ Font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70
The following examples take us to appreciate the charm of Zuul.

Create a project

Before creating the Zuul project, we need to refer to the previous project, readers have questions can refer to 81392085

In the original project to create a new project Zuul-service, its pom file is as follows:

<?xml version= "1.0" encoding= "UTF-8"?
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "http://maven.apache.org/POM/4.0.0/HTTP// Maven.apache.org/xsd/maven-4.0.0.xsd ";
<modelversion>4.0.0</modelversion>

<groupid>com.yeya</groupid><artifactid>zuul</artifactid><version>0.0.1-snapshot </version><packaging>jar</packaging><name>zuul</name><description>demo Project for Spring boot</description><parent> <groupId>org.springframework.boot</groupId> & Lt;artifactid>spring-boot-starter-parent</artifactid> <version>2.0.4.RELEASE</version> < Relativepath/> <!--lookup parent from Repository--></parent><properties> < Project.build.sourceencoding>utf-8</project.build.sourceencoding> <project.reporting.outputencoding >UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> < Spring-cloud.version>finchley.sr1</spring-cloud.version></properties><dependencies> < Dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework .cloud</groupid> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </depe ndency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId> spring-cloud-starter-netflix-zuul</artifactid> </dependency> <dependency> <groupid>or G.springframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <sco Pe>test</scope> </dependency></dependencies><dependencyManagement> <dependencies > <dependency> <groupId>org.springframework.cloud</groupId> <artifact            Id>spring-cloud-dependencies</artifactid> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencymanage ment><build> <plugins> <plugin> <groupid>org.springframework.boot</grou pid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins&gt ;</build>

</project>
Add annotations @EnableDiscoveryClient and @EnableZuulProxy on the startup class of your program to turn on the functions of service registration and service Gateway, with the following code:

@SpringBootApplicationbr/> @EnableDiscoveryClient

public class Zuulapplication {

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

}

In the configuration file application.yml Configure the following information:

Eureka
Client
Serviceurl:
defaultzone:http://localhost:1111/eureka/
Server
port:1116
Spring
Application:
Name:zuul-service
Zuul:
Routes
API-A:
Path:/clientapi/
Serviceid:eureka-client
Api-b:
Path:/ribbonapi/

Serviceid:eureka-ribbon

其中,eureka.client.serviceUrl.defaultZone是服务注册中心的地址,服务的名称为zuul-service,以/clientapi/ 开头的请求都转发给eureka-client服务;以/ribbonapi/开头的请求都转发给eureka-ribbon服务;配置好信息后,依次启动这几个工程,记得eureka-client要改端口 (1112,1113) 启动两次,然后打开浏览器,多次访问 http://localhost:1116/clientapi/hello,会发现浏览器反复显示

hello:1112
hello:1113
Similarly, multiple accesses to Http://localhost:1116/ribbonapi/consumer, the browser will show the same results, indicating that Zuul does play the role of Route forwarding.

Service Filtering
zuul除了能做路由转发之外,还能实现过滤作用,做一些安全的验证功能,下面我们来改造一下zuul-service工程。在工程中创建一个过滤器继承ZuulFilter ,并实现类中的方法,具体实现如下功能;如果请求地址中有带token,那么过滤器就不做拦截,否则拦截并输出 token is empty,下面是具体代码:

@Component
public class Myfilter extends Zuulfilter {br/> @Override

return "Pre";
}

@Overridepublic int filterOrder() {    return 0;}@Overridepublic boolean shouldFilter() {    return true;}@Overridepublic Object run() throws ZuulException {    RequestContext ctx = RequestContext.getCurrentContext();    HttpServletRequest request = ctx.getRequest();    Object accessToken = request.getParameter("token");    if(accessToken == null) {        ctx.setSendZuulResponse(false);        try {            ctx.getResponse().getWriter().write("token is empty");        }catch (Exception e){}        return null;    }    return null;}

}
FilterType: Returns a String representing the type of filter, and defines the filter type for four different lifecycles in Zuul, as follows:

Pre: Before routing
Routing: The time of routing
Post: After routing
Error: Sending the wrong call
Filterorder: The Order of filtering
Shouldfilter: Here can write logical judgments, whether to filter, this article true, filter forever.
Run: The specific logic of the filter. Can be complicated, including checking sql,nosql to see if the request has access.
After writing the code, restart the service, access the Http://localhost:1116/ribbonapi/consumer, and find the browser back

Token is empty
Add parameter token, re-access http://localhost:1116/ribbonapi/consumer?token=11, find the normal output of the browser

hello:1112
hello:1113
At this point, Zuul's filtration project was successfully implemented.

Summary
zuul作为微服务系统的服务网关,起到了至关重要的作用,所以,一般来说,在生产上的微服务系统中,zuul服务需要做集群分布,避免服务挂了网关失效的情况。

Springcloud microservices Series--Service Gateway Components Zuul

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.