目录
概述
GateWay是一个网关应用,网关的作用就是过滤请求,将请求转发到对应的微服务上,这么做的好处是让请求不直接访问微服务而是通过网关,这样就可以对请求进行管理,隐藏微服务的ip和端口增强微服务的隐蔽性。最要的两个作用就是过滤和请求。
入门案例
1.由于GateWay本身一个微服务需要注册到Eureka当中,因此第一步需要创建一份maven工程,引入GateWay依赖和eureka客户端依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
2.gateway工程也是微服务工程因此启动项的依赖与其他微服务工程一样,需要添加eureka发现注解和springboot启动注解
@EnableDiscoveryClient
@SpringBootApplication
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class,args);
}
}
路由配置
predicates:配置路由映射的路径。
spring:
application:
#eureka中网关服务的名称
name: gateway-server
cloud:
gateway:
routes:
#路由的id
- id: user-server-route
#使用服务名称替代地址,eureka中不止一个服务
uri: lb://springcloud-server
#配置请求转发的
#uri: http://127.0.0.1:8082
#路由断言,配置访问的路径
predicates:
- Path=/testserver/**
过滤器配置
Filter:prefixpath配置访问的前缀,访问的路径predicates的路径可以设置成./**,来表示需要映射的路径,如果predicates设置的路径名称比较全如/server/user/**,那么可以设置去除前缀stripprefix,设置数值,1代表去除一个前缀,原来的/server/user/**访问路径可以改为/user/**
filters:
#配置访问的路劲的前缀
#- PrefixPath=/testserver
#去除前缀1个前缀
- StripPrefix=1
自定义过滤器
全局过滤器
不需要再yml中配置,实现GlobalFilter去设置
局部过滤器
作用:针对某个路由进行设置过滤器,编写过滤类继承MyParamGatewayFilterFactory类
GateWay中hystrix设置
gateway默认集成了Hystrix,配置值是默认的,可在yml中修改配置
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000
GateWay中设置Ribbon
GateWay中集成了ribbon实现负载均衡,可在yml修改配置
ribbon:
ConnectTimeout: 1000
ReadTimeout: 2000
MaxAutoRetries: 0
MaxAutoRetriesNextServer: 0
GateWay中跨域问题
跨域:前端访问的地址与当前服务器的地址不一致则会出现请求不到的跨域问题。在GateWay中可以设置其他服务器可通过访问的地址。
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins:
- "http://127.1.1:9909"
allowedMethods:
- GET
'[/**]':所有当问网关服务器的地址
allowedOrigins:允许跨域访问的地址由那些,可填写多个。
allowedMethods:允许跨域访问的请求类型有那些,可填写多个。
GateWay的高可用
GateWay既然也是为微服务,那就可以启动多个GateWay作为集群,内部网络访问gateway没用问题,要实现外部请求的负载均衡可以使用nginx作为负载均衡代理服务器,从nginx中转发请求到GateWay当中,GateWay收到请求查找Eureka中的服务进行调用。
GateWay与Feign的区别
GateWay:接收外部请求转发给其他微服务。
Feign:将微服务中的接口暴露,让其他微服务调用,主要用在微服务直接的调用。