Spring Cloud 微服务三: API网关Spring cloud gateway

2022-10-22,,,,

前言:前面介绍了一款API网关组件zuul,不过发现spring cloud自己开发了一个新网关gateway,貌似要取代zuul,spring官网上也已经没有zuul的组件了(虽然在仓库中可以更新到,但主页上已经没有了),而且zuul1.x的性能据说也一般,所以本章将引入spring cloud原生网关产品。本章继续前面的内容,前情回顾请参考:

Spring Cloud 微服务一:Consul注册中心

Spring Cloud 微服务二:API网关spring cloud zuul

Spring cloud gateway概览

Spring cloud gateway,Spring Cloud Gateway是由spring官方基于Spring5.0,Spring Boot2.0,Project Reactor等技术开发的网关.该项目提供了一个构建在Spring Ecosystem之上的API网关,旨在提供一种简单而有效的途径来发送API,并向他们提供交叉关注点,例如:安全性,监控/指标和弹性.

集成gateway
在上一个项目的基础上新建一个module,名称api-gateway,pom中添加如下依赖,其中gateway是spring cloud网关组件,consul用于集成注册中心功能

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

启动类保持默认即可

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

主要在于配置文件,配置文件中定义了路由规则以及注册中心的相关配置,以下的配置,会将http://localhost:8088下的所有请求重定向到http://localhost:10086

server:
port: 8088
debug: true spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: user_route
uri: http://localhost:10086
predicates:
- Path=/*
consul:
host: localhost
port: 8500
discovery:
register: false

启动user-service,api-gateway,在浏览器访问:http://localhost:8088/all,显示服务的内容,调用成功!

Spring Cloud 微服务三: API网关Spring cloud gateway的相关教程结束。

《Spring Cloud 微服务三: API网关Spring cloud gateway.doc》

下载本文的Word格式文档,以方便收藏与打印。