Brief introduction
Zuul is the API gateway and filtering component provided by spring Cloud, which provides the following features:
- Certification
- Filter
- Pressure test
- Canary test
- Dynamic routing
- Service Migration
- Load Balancing
- Safety
- Static request Processing
- Dynamic traffic Management
In this tutorial, we will use Zuul to forward the web-side request /product to the corresponding product service, and define a pre filter to verify that the Zuul is forwarded.
Basic Environment
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
Project Source
Gitee Code Cloud
Create a Zuul service
Create a MAVEN project in IntelliJ:
Then pom.xml add the following code in:
<?xmlVersion= "1.0" encoding= "UTF-8"?><projectxmlns="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>Cn.zxuqian</groupId> <artifactId>Apigateway</artifactId> <version>1.0-snapshot</version> <parent> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>Org.springframework.cloud</groupId> <!--name has changed, Before:spring-cloud-starter-zuul-- <artifactId>Spring-cloud-starter-netflix-zuul</artifactId> </dependency> <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-config</artifactId> </dependency> <dependency> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter-web</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>Org.springframework.cloud</groupId> <artifactId>Spring-cloud-dependencies</artifactId> <version>Finchley.m9</version> <type>Pom</type> <scope>Import</scope> </dependency> </dependencies> </dependencyManagement> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>Spring-milestones</id> <name>Spring Milestones</name> <url>Https://repo.spring.io/libs-milestone</url> <snapshots> <enabled>False</enabled> </snapshots> </repository> </repositories></project>
It should be noted that the spring website of the tutorial to the Zuul Artifactid for Spring-cloud-starter-zuul, this is the old version of Zuul name, in our Finchley.M9 version has been renamed spring-cloud-starter-netflix-zuul .
src/main/resources/bootstrap.ymlto add a file, specify spring.application.name :
spring: application: name: zuul-server
To create a cn.zxuqian.Application class:
Package Cn.zxuqian;import Cn.zxuqian.filters.PreFilter;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;import Org.springframework.context.annotation.Bean;@EnableZuulProxy@EnableDiscoveryClient@SpringBootApplication Public classApplication { Public Static void Main(string[] args) {springapplication.Run(Application.class, args); }@Bean PublicPrefilterPrefilter() {return New Prefilter(); }}
This is used @EnableZuulProxy to specify a reverse proxy that uses Zuul to forward our request to the corresponding server. Then, eureka the service discovery is enabled. Zuul also uses the Ribbon for load balancing by default, so you can discover registered services through Eureka. PreFilteris a pre-filter that is used to do something before the request is processed, with the following code:
Package cn.zxuqian.filters;import Com.netflix.zuul.ZuulFilter;import Com.netflix.zuul.context.RequestContext;import com.netflix.zuul.exception.ZuulException;import Org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest; Public classPrefilterextendsZuulfilter {Private StaticLogger log = Loggerfactory.GetLogger(Prefilter.class);@Override PublicStringFilterType() {return "Pre"; }@Override Public int Filterorder() {return 1; }@Override Public Boolean Shouldfilter() {return true; }@Override PublicObjectRun()throwszuulexception {RequestContext CTX = RequestContext.Getcurrentcontext(); HttpServletRequest request = CTX.getrequest(); Log.Info(String. Format("%sWay Request%s", request.GetMethod(), request.Getrequesturl().toString()));return NULL; }}
filterType-Zuul built-in filter type Four,,,, respectively, represents the request before processing, processing pre route , after post error processing and after an error.
filterOrder-Specifies the order in which the filter executes.
shouldFilter-whether this filter is turned on.
run-The business logic of the filter. Here is simply a log of the reqeust request and the path of the request.
Next, create the file in the Git repository in our configuration Center zuul-server.yml and add the following configuration:
server: port: 8083zuul: routes: products: path: /product/** serviceId: product-service
This configures the port for Zuul to 8083, and then maps all /product/ the requests to our product-service service. If not configured serviceId , then products this key will default as Serviceid, and in our case, Serviceid is included - , so Serviceid is specified in the bottom display. Commit to Git when the configuration is complete.
Update Productservice
Productservice's URI makes a little change to make it more restful:
@RequestMapping("/list")publicproductList() { log.info("Access to /products endpoint"); return"外套,夹克,毛衣,T恤";}
Here the @RequestMapping matching path changed /list to, before is /products .
Update Web Client
ProductServiceadd a new method to our web client:
publicproductListZuul() { returnthis.restTemplate.getForObject("http://zuul-server/product/list", String.class);}
This time we request the service directly and zuul-server then it reflects our request to the product-service service. Finally, ProductController add a request processing method in:
@RequestMapping("/product/list")publicproductListZuul() { return productService.productListZuul();}
Used to process /product/list the request and then invoke the ProductService method in the class.
Test
Use mvn spring-boot:run startup configServer ,,, registry zuulServer productService web These several works, and then start the second one productService , using SERVER_PORT=8082 spring-boot:run .
After several visits http://localhost:8080/product/list , and in addition to seeing the results returned in the browser, we will also zuulServer see the following in the command-line window:
GET Mode Request Http://xuqians-imac:8083/product/list
And then in the two productService command-line window, we'll also see a randomly occurring
Access to/products Endpoint
The instructions are zuulServer also automatically load balanced.
Welcome to visit my blog Zhang Xu blog
What do you have in mind to welcome the discussion.
Spring Cloud Getting Started Tutorial-Zuul implementing API gateways and request filtering