1、介绍
2、搭建zuul网关服务器
2.1 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
2.2 激活zuul
package com.yan.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
// 开启zuul网关
@EnableZuulProxy
public class ZuulServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServerApplication.class, args);
}
}
2.3 application配置
server.port=8080
spring.application.name=api-zuul-server
3、路由
路由:根据请求的url,将请求分配到对应的微服务进行处理。
3.1 基础配置
server.port=8080
spring.application.name=api-zuul-server
##路由配置
#映射路径 localhost:8080/product-service/dhajh
zuul.routes.product-service.path=/product-service/**
#映射路径对应的实际微服务地址
zuul.routes.product-service.url=http://localhost:9001
3.2 面向服务的路由
3.2.1 添加eureka配置
<!-- 引入EurekaClient -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3.2.2 开启eureka客户端的服务发现
package com.yan.application;
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;
@SpringBootApplication
// 开启zuul网关
@EnableZuulProxy
//激活EurekaClient
@EnableDiscoveryClient
public class ZuulServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServerApplication.class, args);
}
}
3.2.3 在zuul网关服务中配置eureka的注册中心和相关配置
server.port=8080
spring.application.name=api-zuul-server
##路由配置
#映射路径 localhost:8080/product-service/dhajh
zuul.routes.product-service.path=/product-service/**
#映射路径对应的实际微服务地址
zuul.routes.product-service.url=http://localhost:9001
#配置eurekaClient
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
#使用IP地址注册
eureka.instance.prefer-ip-address=true
3.2.4 修改路由中的映射配置
server.port=8080
spring.application.name=api-zuul-server
##路由配置
#映射路径 localhost:8080/product-service/dhajh
zuul.routes.product-service.path=/product-service/**
#映射路径对应的实际微服务地址
#zuul.routes.product-service.url=http://localhost:9001
zuul.routes.product-service.serviceId=product-service
#配置eurekaClient
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
#使用IP地址注册
eureka.instance.prefer-ip-address=true
3.3 简化路由配置
4、过滤器
4.1 自定义拦截器
4.2 自定义拦截器实现身份校验
5、内部源码
执行流程:
内部加载: