springcloud-zuul 路由网关(十)
概述
什么是zuul?
Zull包含了对请求的路由(用来跳转的)和过滤两个最主要功能:
其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础,而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验,服务聚合等功能的基础。Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他服务的消息,也即以后的访问微服务都是通过Zuul跳转后获得。
注意:Zuul 服务最终还是会注册进 Eureka
提供:代理 + 路由 + 过滤 三大功能!
Zuul 能干嘛?
- 路由
- 过滤
官方文档:https://github.com/Netflix/zuul/
示例
新建 springcloud-zuul-9527 模块
- pom.xml
org.springframework.cloud
spring-cloud-starter-zuul
1.4.6.RELEASE
org.springframework.cloud
spring-cloud-starter-hystrix
1.4.6.RELEASE
org.springframework.cloud
spring-cloud-starter-hystrix-dashboard
1.4.6.RELEASE
org.springframework.cloud
spring-cloud-starter-ribbon
1.4.6.RELEASE
org.springframework.cloud
spring-cloud-starter-eureka
1.4.6.RELEASE
com.dong
springcloud-common
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
- application
server:
port: 9527
spring:
application:
name: springcloud-zuul #微服务名称
# eureka 注册中心配置
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
instance: #实例的id
instance-id: zuul9527.com
prefer-ip-address: true # 显示ip
info:
app.name: haust.springcloud # 项目名称
company.name: 河南科技大学西苑校区 # 公司名称
# zull 路由网关配置
zuul:
# 路由相关配置
# 原来访问路由 eg:http://localhost:8001/dept/get/1
# zull路由配置后访问路由 eg:http://localhost:9527/dong/mydept/dept/get/1
routes:
mydept.serviceId: springcloud-provider-dept # eureka注册中心的服务提供方路由名称
mydept.path: /mydept/** # 将eureka注册中心的服务提供方路由名称 改为自定义路由名称
# 不能再使用这个路径访问了,*: 忽略,隐藏全部的服务名称~
# ignored-services: springcloud-provider-dept
ignored-services: "*"
# 设置公共的前缀
prefix: /dong
- 主启动类
package com.dong.zull;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy // 开启Zuul
@EnableEurekaClient
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class,args);
}
}
-
测试
启动 springcloud-provider-8001,springcloud-eureka-7001和springcloud-zuul-9527
访问http://localhost:7001/查看服务是否注册到eureka
从springcloud-provider-8001访问http://localhost:8001/dept/get/1
{"deptno":1,"dname":"开发部","dbSource":"springcloud"}
从网关访问 http://localhost:9527/dong/mydept/dept/get/2
{"deptno":2,"dname":"人事部","dbSource":"springcloud"}
? 去除ignored-services: "*" 配置,我们可以通过微服务名称进行访问http://localhost:9527/dong/springcloud-provider-dept/dept/get/3
{"deptno":3,"dname":"财务部","dbSource":"springcloud"}
zuul其它相关配置
zuul:
add-host-header: true
#不对敏感资源做拦截
sensitive-headers:
ignored-headers:
-'Access-Control-Allow-Credentials'
-'Access-Control-Allow-Origin'
host:
socket-timeout-millis: 200000 # 请求的处理时间
connect-timeout-millis: 200000 # 请求的链接时间
参考教程 https://www.kuangstudy.com/