Springcloud教程——GateWay网关组件

概述

入门案例

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:配置路由映射的路径。

过滤器配置

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与Feign的区别

Feign:将微服务中的接口暴露,让其他微服务调用,主要用在微服务直接的调用。

经验分享 程序员 微信小程序 职场和发展