---
title: "服务网关Spring Cloud Gateway"
author: "raymond.chen"
date: "2019-01-18T22:27:57Z"
tags: []
categories: ["互联网"]
slug: "spring-cloud-gateway"
draft: false
lastmod: "2019-02-24T16:19:14Z"
id: 2436795
url: "https://chenjumin.iteye.com/blog/2436795"
---

Spring Cloud Gateway是由Spring官方基于Spring5.0，Spring Boot2.0，Project Reactor等技术开发的网关，目的是代替原先版本中的Spring Cloud Netfilx Zuul。Spring Cloud Gateway基于Webflux，比较完美地支持异步非阻塞编程，很多功能实现起来比较方便。

 

Spring Cloud Gateway的特征：

        基于 Java 8 编码

        基于 Spring Framework 5，Project Reactor 和 Spring Boot 2.0 动态路由

        Predicates 和 Filters 作用于特定路由

        集成 Hystrix 断路器

        支持 Spring Cloud DiscoveryClient 配置路由，与服务发现与注册配合使用

        易于编写的 Predicates(断言) 和 Filters

        限流

       支持 WebSockets

        路径重写

 

**创建service-gateway工程说明Spring Cloud Gateway的使用**：

     pom.xml文件的关键配置：

```
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.7.RELEASE</version>
	<relativePath/>
</parent>

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-gateway</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-actuator</artifactId>
	</dependency>
</dependencies>

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>Finchley.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
```

 

     启动类：

```
@SpringBootApplication
@EnableEurekaClient
public class Main {
	public static void main(String[] args) {
		SpringApplication.run(Main.class, args);
	}	
}
```

 

     application.yml文件的配置：

```
server:
  port: 2001

eureka:
  instance: 
    hostname: ${spring.cloud.client.ip-address}
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://root:123456@${eureka.instance.hostname}:7001/eureka/
  
spring:
  application:
    name: service-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: false  #关闭通过服务名路由到具体服务实例的功能
      routes:
        - id: service-id
#          uri: http://localhost:9001   #目标服务地址
          uri: lb://service-consumer-1  #以负载均衡方式路由到目标服务，格式为 lb://服务名
          predicates:
            - Path=/api/**     #基于路径的路由策略
          filters:
            - StripPrefix=1    #去掉路径前缀
```

     访问网关地址 http://localhost:2001/api/addUser  会路由到微服务地址 http://localhost:9001/addUser

 

 开启以服务名开头的请求路径转发到对应的服务：

```
server:
  port: 2001

eureka:
  instance: 
    hostname: ${spring.cloud.client.ip-address}
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://root:123456@${eureka.instance.hostname}:7001/eureka/
  
spring:
  application:
    name: service-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true               #启用通过服务名路由到具体的服务实例
          lowerCaseServiceId: true    #启用服务名称小写支持，即将请求路径上的服务名配置为小写
```

      访问网关地址 http://localhost:2001/service-consumer-1/addUser  会路由到微服务地址 http://localhost:9001/addUser

 

设置spring.cloud.gateway.discovery.locator.enabled=true，表明gateway开启服务注册和发现的功能，并且gateway自动根据服务发现为每一个服务创建一个router，这个router将以服务名开头的请求路径转发到对应的服务。此时，gateway的路由规则是：

       http://Gateway\_HOST:Gateway\_PORT/大写的serviceId/\**

             其中微服务名默认大写访问

 

设置spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true，可以将请求路径上的服务名配置为小写。

 

 **更改Spring Cloud Gateway的默认负载均衡策略**

      当同一服务名下有多个服务实例时，默认是采用轮询的负载均衡策略，通过在启动类配置负载均衡Bean类可以更改默认策略。

```
/**
 * 更改gateway服务路由的负载均衡策略
 */
@Bean
public IRule feignRule(){
	return new RandomRule();
}
```

 

**配置Gateway的路由熔断功能**

      熔断器控制类：

```
@RestController
public class HystrixController {
	@GetMapping("/hystrixCommandFallback")
	public Response hystrixCommandFallback(){
		Response response = new Response("100", "服务暂时不可用");
		return response;
	}
}
```

 

      全局路由熔断的配置：

```
spring:
  cloud:
    gateway:
      default-filters:
        - name: Hystrix
          args:
            name: hystrixCommand
            fallbackUri: forward:/hystrixCommandFallback
```

 

     特定路由的熔断配置： 

```
spring:
  cloud:
    gateway:
      routes:
        - id: a
          uri: lb://service-consumer-1
          predicates:
            - Path=/cjm/**
          filters:
            - StripPrefix=1
            - name: Hystrix  #熔断器过滤器
              args:
                name: hystrixCommand  #熔断器名称，自行定义
                fallbackUri: forward:/hystrixCommandFallback  #回退方法
```

 

[服务网关Spring Cloud Gateway -- Predicate介绍](/blog/2438036)

 

[服务网关Spring Cloud Gateway -- 全局过滤器](/blog/2438037)

 

[服务网关Spring Cloud Gateway -- 网关过滤器工厂](/blog/2438038)