使用Zuul构建API网关
1.创建一个普通的SpringBoot项目,然后添加相关依赖 zuul 和 eureka
<!-- netflix开发 整合进spring cloud zuul 网关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- eureka-client注册中心客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
2.在入口类添加 @EnableZuulProxy注解,开启Zuul的API网关服务功能
@SpringBootApplication
//开启Zuul的API网关服务功能
@EnableZuulProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.在yml文件中配置路由规则
# 内置Tomcat端口
server:
port: 8088
spring:
application:
name: 06-springcloud-api-gateway
#配置API网关到注册中心上。API网关也将作为一个服务注册到eureka-server上
eureka:
client:
service-url.defaultZone: http://eureka8083:8083/eureka/,http://eureka8084:8084/eureka/
# 配置路由规则 是我们自定义的api-wjm 在这个路径后匹配
# 可以随便定义 但是 1.一定是一样的 2.并且成对的
zuul:
#prefix: /api # 添加路由前缀
routes:
api-wjm: # 路由的 id
path: /api-wjm/** #映射路径
# 映射路径对应的实际的url地址
# 访问路径规则 添加 映射路径的规则
service-id: 05-SPRINGCLOUD-SERVICE-FEIGN # 指定服务端的名称
以上配置,我们的路由规则就是匹配所有符合/api-wjm/**的请求,只要路径中带有/api-wjm/都将被转发到05-springcloud-service-feign服务上,至于05-springcloud-service-feign服务的地址到底是什么则由eureka-server注册中心去分析,我们只需要写上服务名即可。
以我们目前搭建的项目为例,请求http://localhost:8088/api-wjm/web/hello接口则相当于请求http://localhost:8087/web/hello
(05-springcloud-service-feign 服务的地址为http://localhost:8087/web/hello),路由规则中配置的 api-wjm是路由的名字,可以任意定义,但是一组path和serviceld 映射关系的路由名要相同。
如果以上测试成功,则表示们的API网关服务已经构建成功了,我们发送的符合路由规则的请求将自动被转发到相应的服务上去处理。