Spring Cloud Gateway替代zuul作为API网关的方法

作者:russle 时间:2023-05-03 07:19:58 

本文简要介绍如何使用Spring Cloud Gateway 作为API 网关(不是使用zuul作为网关),关于Spring Cloud Gateway和zuul的性能比较本文不再赘述,基本可以肯定Spring Cloud Finchley版本的gateway比zuul 1.x系列的性能和功能整体要好。

特别提醒:Spring Cloud Finchley版本中,即使你引入了spring-cloud-starter-netflix-zuul,也不是2.0版本的zuul

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

我们的介绍分为3个部分, 第一,pom文件,第二项目的基本架构,第三源码和截图。

第一,pom文件

因为使用Eureka作为服务注册和发现,因此在pom中引入了eureka,各位可根据自己的实际情况修改。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

<groupId>com.yq</groupId>
   <artifactId>GatewayDemo</artifactId>
   <version>1.0-SNAPSHOT</version>

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

<properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
   </properties>

<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>

<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>

<dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
       </dependency>

<dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <optional>true</optional>
       </dependency>

<dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>

<!-- fastjson-->
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.1.33</version>
       </dependency>

<dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-lang3</artifactId>
           <version>3.5</version>
       </dependency>

</dependencies>

<repositories>
       <repository>
           <id>spring-milestones</id>
           <name>Spring Milestones</name>
           <url>https://repo.spring.io/milestone</url>
           <snapshots>
               <enabled>false</enabled>
           </snapshots>
       </repository>
   </repositories>

<build>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
       </plugins>
   </build>

</project>

第二,项目结构

总共有3个项目,
第一个项目是eureka 注册中心,非常简单,基本就一个Application类。 端口7700
第二个项目是User service,也非常简单提供两个rest api,为了简略不连接数据库,直接在内存中生成一组数据。端口6601
第三个项目就是我们的网关。端口6604

目前项目中集成websocket服务配置,本文暂不介绍可直接忽略。

第三,项目代码和运行截图

网关的主代码

package com.yq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@SpringCloudApplication
public class APIGatewayApplication  {
   private static final Logger logger = LoggerFactory.getLogger(APIGatewayApplication.class);

@Bean
   public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
       return builder.routes()
               .route(r -> r.path("/baidu")
                       .uri("http://baidu.com:80/")
               )
              .route("websocket_route", r -> r.path("/apitopic1/**")
               .uri("ws://127.0.0.1:6605"))
               .route(r -> r.path("/userapi3/**")
                       .filters(f -> f.addResponseHeader("X-AnotherHeader", "testapi3"))

.uri("lb://user-service/")
               )
               .build();
   }

public static void main(String[] args) {
       SpringApplication.run(APIGatewayApplication.class, args);
       logger.info(" Start APIGatewayApplication Done");
   }

}

网关的配置文件application.yml

server:
 port: 6604

#服务名
spring:
 application:
   name: gateway-service
 cloud:
   gateway:
     filter:
       remove-non-proxy-headers:
         headers:
         - dummy
     routes:
       - id:  apiuser
       # 重点!/info必须使用http进行转发,lb代表从注册中心获取服务
         uri: lb://user-service
         predicates:
         # 重点!转发该路径!,/userapi/**,
         - Path=/userapi/**
         # http://localhost:6601/userapi/user/users/2, 必须加上StripPrefix=1,否则访问服务时会带上userapi
         #而不是我们期望的去掉userapi,只保留**部分
         filters:
         - StripPrefix=1
       - id:  api2user
         uri: lb://user-service
         predicates:
         - Path=/userapi2/**
         filters:
         - StripPrefix=1

eureka:
 client:
   serviceUrl:
     defaultZone: http://localhost:7700/eureka/

我们简要分析分析一下配置文件

  • id: apiuser

# 重点!/info必须使用http进行转发,lb代表从注册中心获取服务
uri: lb://user-service
predicates:
# 重点!转发该路径!,/userapi/,
- Path=/userapi/

# http://localhost:6601/userapi/user/users/2, 必须加上StripPrefix=1,否则访问服务时会带上userapi
#而不是我们期望的去掉userapi,只保留**部分
filters:
- StripPrefix=1

配置了一个路由apiuser, 当路径( - Path=/userapi/**),就转发到服务(lb://user-service),同时把路径中的userapi这部分去掉(- StripPrefix=1)。

运行效果图

直接访问User service
http://localhost:6601/user/users/2

通过网关访问user service
http://localhost:6604/userapi/user/users/2

Spring Cloud Gateway替代zuul作为API网关的方法

参考文档:

1, http://cloud.spring.io/spring-cloud-static/Finchley/single/spring-cloud.html#_spring_cloud_gateway
2, https://github.com/spring-cloud-samples/spring-cloud-gateway-sample

来源:https://blog.csdn.net/russle/article/details/80962066

标签:Spring,Cloud,Gateway,API网关
0
投稿

猜你喜欢

  • Android Toast实现全屏显示

    2023-12-22 09:16:05
  • Android实现歌词渐变色和进度的效果

    2023-09-24 02:33:17
  • Java C++题解leetcode 1684统计一致字符串的数目示例

    2023-04-23 09:06:31
  • 浅谈Spring Security LDAP简介

    2022-09-19 20:30:06
  • spring Bean创建的完整过程记录

    2022-04-14 03:57:51
  • MyBatis Log 插件无法显示SQL语句的原因解析

    2023-11-24 23:42:55
  • java接口自动化测试框架及断言详解

    2022-01-23 20:01:36
  • c# AcceptEx与完成端口(IOCP)结合的示例

    2023-07-29 01:46:24
  • Android应用中加入微信分享简单方法

    2022-06-05 00:17:27
  • Android 自定义返回按钮的实例详解

    2023-07-04 01:13:43
  • 使用adb命令向Android模拟器中导入通讯录联系人的方法

    2022-12-21 15:39:56
  • Java操作文件输出为字符串以及字符串输出为文件的方法

    2022-02-01 19:32:45
  • C#中的HttpWebRequest类用法详解

    2022-11-07 11:41:17
  • android动态壁纸调用的简单实例

    2023-11-17 05:43:28
  • 简单阐述一下Java集合的概要

    2023-08-23 19:49:45
  • Mybatis实现关联关系映射的方法示例

    2022-09-18 05:36:12
  • Android recyclerview实现纵向虚线时间轴的示例代码

    2023-08-23 07:03:39
  • Go Java算法之找不同示例详解

    2021-10-29 19:37:08
  • Mybatis中where标签与if标签结合使用详细说明

    2021-07-27 08:15:53
  • android轻量级无侵入式管理数据库自动升级组件

    2023-12-09 15:36:01
  • asp之家 软件编程 m.aspxhome.com