Zuul笔记
1.zuul的作用
zuul用于充当项目的网关,作为暴露给项目外部的接口,zuul负责按照开发人员设置好的规则将请求路由到特定的微服务上。
2.zuul的用法
-
创建zuul网关module
先通过maven建一个单独的zuul module,这里用的是父工程+子module的项目结构,建好之后,项目结构如下:
-
引入依赖
只有网关才需要zuul依赖,因此如果是父工程+子模块形式的项目项目结构,就不用把zuul依赖引入到父工程的pom文件里了,只在zuul module中引入依赖即可,zuul pom文件如下:
<?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"> <parent> <artifactId>ycb-bolg</artifactId> <groupId>com.yichengbo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>zuul-service</artifactId> <dependencies> <!--zuul网关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> <version>2.2.9.RELEASE</version> </dependency> </dependencies> </project>
-
创建zuul服务,并且注册到服务中心
zuul网关也属于一个微服务,需要被注册到eureka上,这样它才能把请求路由到各个微服务,所以zuul的properties文件配置如下:
server: port: 11000 spring: application: name: ZUUL-SERVICE-11000 # 注册到eureka eureka: client: service-url: defaultZone: http://localhost:10000/eureka #路由方式1:根据serviceId进行路由: 网关IP:网关端口/consumer1/** --> openFeign-consumer-10011/**。其中consumer1部分可以根据业务需要自定义 zuul: routes: route1: path: /consumer1/** serviceId: openFeign-consumer-10011 route2: path: /consumer2/** url: http://localhost:10011
-
设置路由规则
设置路由规则是最关键的一环,zuul的路由规则分为以下几种:
待补充