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

2023-05-16 0 3,419

目录

本文简要介绍如何使用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
2, https://github.com/spring-cloud-samples/spring-cloud-gateway-sample

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 Spring Cloud Gateway替代zuul作为API网关的方法 http://www.20zxx.cn/705300/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务