Spring Cloud Gateway使用

简介

Spring Cloud Gateway是Spring Cloud官方推出的网关框架,网关做为流量入口,在微服务系统中有着十分重要的做用,经常使用功能包括:鉴权、路由转发、熔断、限流等。java

Spring Cloud Gateway是经过Spring WebFlux的HandlerMapping作为底层支持来匹配到转发路由,使用时不要引入SpringMVC,不然初始化时会出错;Spring Cloud Gateway内置了不少Predicates工厂,这些 Predicates 工厂经过不一样的 HTTP 请求参数来匹配,多个 Predicates 工厂能够组合使用。spring

使用

一、添加依赖api

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

二、配置(结合Eureka使用)app

server:
  port: 8066
spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true  #设置serviceId小写,默认大写
      routes:
      - id: user-server
        uri: lb://user-server   #lb表示从注册中心获取服务
        predicates:
        - Path=/userapi/**         # 若是请求地址知足/userapi/**,则转发到user-server服务
        filters:
        - StripPrefix=1           # 去除原请求地址中的userapi
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

三、集成Hystrix框架

依赖微服务

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

配置spa

filters:
- name: Hystrix
  args:
    name : default
    fallbackUri: 'forward:/dfallback'
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000   

java端code

@RestController
public class DHystrixController {
    @RequestMapping("/dfallback")
    public Map<String,String> dfallback(){
        System.out.println("降级了。。。");
        Map<String,String> map = new HashMap<String,String>();
        map.put("rCode","-1");
        map.put("rMsg","出错了");
        return map;
    }
}

ENDserver