Spring Cloud Gateway常用场景实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/it_lihongmin/article/details/90813558

目录

一、Spring Cloud Gateway搭建

二、常用应用场景搭建

1、与Spring Cloud支持的注册中心整合

1)、一些提前准备

2)、配置文件

3)、启动类中添加@EnableEurekaClient配置

4)、启动服务

2、与断路器Hystrix整合

3、请求频率限制

4、Predicate集成

5、filter集成

6、RouteDefinitionLocator编码方式实现


项目地址:https://github.com/kevin-lihongmin/spring-cloud-project-kevin/tree/master/gateway-demo

一、Spring Cloud Gateway搭建

    在start.spring.io中添加Actuator、Gateway模块,默认就会开启Spring Cloud Gateway服务(可以在配置中添加spring.cloud.gateway.enabled=false进行关闭)。 

    在application.properties中添加配置如下:

# 服务端口
server.port = 8900
# 应用名称
spring.application.name=gateway-server

二、常用应用场景搭建

1、与Spring Cloud支持的注册中心整合

    Spring Cloud Gateway可以与各种Spring Cloud 支持的注册中心(Eureka Server,Zookeeper、Consul)进行整理,当前以Eureka Server服务中心为例,其他的注册中心其实也是一样的。

1)、一些提前准备

    Eureka Server注册中心请参见:Spring Cloud Eureka Server集群和客户端调用

    服务提供端请参见之前写的ribbon-demo中的ribbon-provider模块(项目地址为:https://github.com/kevin-lihongmin/spring-cloud-project-kevin/tree/master/ribbon-demo),使用Spring profiles启动不同的配置。

2)、配置文件

    在gateway-demo的bootstrap.properties配置中添加:

# 配置Eureka Server注册中心地址
eureka.client.service-url.defaultZone = http://127.0.0.1:8761/eureka/,\
  http://127.0.0.1:8760/eureka/,http://127.0.0.1:8759/eureka/
# gateway开启服务注册和发现的功能
spring.cloud.gateway.discovery.locator.enabled = true
# 获取注册中心的服务名称的进行Lower Case操作
spring.cloud.gateway.discovery.locator.lower-case-service-id = true
# 开启后默认的路由规则与zuul中一致,则会将安装注册到注册中心的服务名称进行负载均衡调用,如下就是默认规则
spring.cloud.gateway.discovery.locator.url-expression='lb://'+serviceId

3)、启动类中添加@EnableEurekaClient配置

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;

/**
 *	Spring Cloud Gateway 服务网关
 *
 * @author kevin
 * @date 2019/6/4 10:33
 * @since 1.0
 */
@EnableEurekaClient
@SpringBootApplication
public class GatewayDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(GatewayDemoApplication.class, args);
	}

}

4)、启动服务

    在原来的服务ribbon-provider中,启动的三个节点端口分别为:8765、8766、8767。比如访问 http://localhost:8765/user/1

    现在访问http://localhost:8900/ribbon-user-provider/user/1, 默认使用注册到注册中心的名称进行访问并且进行负载均衡

2、与断路器Hystrix整合

待更新

3、请求频率限制

待更新

4、Predicate集成

待更新

5、filter集成

待更新

6、RouteDefinitionLocator编码方式实现

猜你喜欢

转载自blog.csdn.net/it_lihongmin/article/details/90813558