Spring Cloud整合Gateway(网关)

一:Spring Cloud Gateway 相关概念

1:官网地址:https://spring.io/projects/spring-cloud-gateway

2:API网关是一个服务器,是系统的唯一入口。从面向对象设计的角度看,它与外观模式类似。API网关封装了系统内部架构,为每个客户端提供一个定制的API。它可能还具有其它职责,如身份验证、监控、负载均衡、缓存、请求分片与管理、静态响应处理。API网关方式的核心要点是,所有的客户端和消费端都通过统一的网关接入微服务,在网关层处理所有的非业务功能。通常,网关也是提供REST/HTTP的访问API。

3:Spring Cloud Gateway核心概念

(1)Route(路由)

Route(路由)是网关最基础的部分,由ID,目标URL,断言,Filter过滤器组成,当请求到达网关时,由 Gateway Handler Mapping 通过断言进行路由匹配(Mapping),当断言为真时,匹配到路由。

(2)Predicate(断言)

Predicates是Java8中的断言函数。Spring Cloud Gateway中的Predicates断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的Predicates断言函数允许开发者去定义匹配来自于http request中的任何信息,比如请求头和参数等。

(3)Filter过滤器。

Spring cloud gateway中的filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理

 二:正文:

1:创建网关工程:

2:工程pom.xml文件(版本由父工程管理)
 

<dependencies>

        <dependency>

            <groupId>com.gx</groupId>

            <artifactId>common_utils</artifactId>

            <version>0.0.1-SNAPSHOT</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

        </dependency>


        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-gateway</artifactId>

        </dependency>


        <!--gson-->

        <dependency>

            <groupId>com.google.code.gson</groupId>

            <artifactId>gson</artifactId>

        </dependency>


        <!--服务调用-->

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-openfeign</artifactId>

        </dependency>

    </dependencies>

 3、编写application.properties配置文件

# 服务端口

server.port=8808

# 服务名

spring.application.name=service-gateway


# nacos服务地址

spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848


#使用服务发现路由

spring.cloud.gateway.discovery.locator.enabled=true


#配置服务
#设置路由id

spring.cloud.gateway.routes[0].id=gateway-acl

#设置路由的uri   lb://nacos注册服务名称

spring.cloud.gateway.routes[0].uri=lb://gateway-acl

#设置路由断言,代理servicerId为auth-service的/auth/路径

spring.cloud.gateway.routes[0].predicates= Path=/*/acl/**

 

yml文件写法:

server:

  port: 8808

    nacos:

      discovery:

        server-addr: 127.0.0.1:8848

spring:

  application:

  cloud:

    gateway:

      discovery:

        locator:

          enabled: true

      routes:

      - id: gateway-acl

        uri: lb://gateway-acl

        predicates:

        - Path=/*/acl/** # 路径匹配


创建一个config类用来处理跨域问题
 

@Configuration

public class CorsConfig {

    @Bean

    public CorsWebFilter corsFilter() {

        CorsConfiguration config = new CorsConfiguration();

        config.addAllowedMethod("*");

        config.addAllowedOrigin("*");

        config.addAllowedHeader("*");


        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());

        source.registerCorsConfiguration("/**", config);


        return new CorsWebFilter(source);

    }

}

配置启动类在Nacos中注册网关服务

@EnableDiscoveryClient注解注册Nacos

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

 注意:使用网关时,前端连接的端口号需要修改为网关的端口号,

链接请求网关时会自动匹配网关中配置的相关服务进行路径的匹配,从而触发真正的请求返回数据

这里使用的前端模板为vue-admin

module.exports = merge(prodEnv, {

  NODE_ENV: '"development"',

  //网关开放的端口

  BASE_API: '"http://localhost:8808"',

})

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Spring Cloud GatewaySpring Cloud生态系统中的一个全新项目,它基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术,旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud,提供了一种简单而有效的方式来管理API请求的路由、过滤和转换。它可以与Eureka、Consul、Zookeeper等服务注册中心集成,支持动态路由、限流、熔断等功能,可以帮助我们快速构建高可用、高性能的微服务架构。 ### 回答2: Spring Cloud GatewaySpring Cloud 的一个全新项目,它基于 Spring 5.0,是一个独立的路由和过滤器,领域涵盖协议转换、流量整形、安全、监控/指标、日志等。它可以使用 Java 开发,也可以使用 Groovy 开发。它旨在为微服务架构提供一种简单而有效的方式,以实现路由、监控和安全等诸多目标功能。 Spring Cloud Gateway 的一个键特性是能够动态路由,它可以根据业务实现和运行情况以及使用者的需求,对请求进行处理和转发。同时,Spring Cloud Gateway 不仅支持各种协议的路由和服务转发,还提供了强大的过滤器机制,可以在请求和响应阶段进行访问控制、操作转换等操作。 使用Spring Cloud Gateway整合Gateway可以快速构建高性能的微服务应用,并实现各种路由和过滤器功能。 首先安装 Spring Cloud Gateway 依赖,同时在pom.xml文件中添加如下代码: ``` <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> </dependencies> ``` 接下来,需要添加路由规则。Spring Cloud Gateway 支持两种方式添加路由规则,一种是采用配置文件方式,另外一种是采用编程方式。对于较为简单的场景,采用配置文件方式会更为便捷和方便。配置文件需要写在 application.properties(或者 application.yml)或自定义的配置文件中,在其中配置路由规则。可以通过在配置文件 application.yml 中,指定 routes 来定义路由: ``` spring: cloud: gateway: routes: - id: demo uri: https://example.com/ predicates: - Path=/demo ``` 上述配置的作用是当访问 http://localhost:8080/demo 时,转发到 https://example.com/。 需要注意的是,Spring Cloud Gateway 的路由规则是可以动态修改的,只需要将新增、修改、删除的路由规则写入相应的配置文件,无需重启服务即可生效。 最后,需要添加过滤器,Spring Cloud Gateway 提供了两种过滤器,一种是全局过滤器,另外一种是基于路由的过滤器。全局过滤器能够匹配所有路由,而基于路由的过滤器仅匹配特定的路由。在使用过滤器时,需要注意过滤器的执行顺序和配置顺序有,过滤器的执行顺序范围为0-10000。 Spring Cloud Gateway 实现了的基本功能,可以轻松地实现反向代理、路由转发、日志监控等功能,为 Spring Cloud 应用带来了更高效的边缘服务体系。通过使用 Spring Cloud Gateway 整合 Gateway,可以更迅速地进行微服务架构的开发和部署。 ### 回答3: 随着微服务的广泛应用,微服务架构下的服务也逐渐变得重要起来。Spring Cloud Gateway作为一种轻量级、高效、易扩展的服务,已成为业界热门的选择。在使用Spring Cloud Gateway时,需要将其与Spring Cloud的其它组件进行整合,以达到更好的服务支持和扩展性。 一、整合方式 1.在pom.xml文件中加入以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ``` 2.配置路由规则,可以在application.yml或application.properties文件中进行配置,在以下例子中,我们定义了一个简单的路由规则: ``` spring: cloud: gateway: routes: - id: route1 uri: http://example.org predicates: - Path=/foo/** - id: route2 uri: http://localhost:8080 predicates: - Path=/bar/** ``` 这里我们定义了两个路由规则,route1和route2,分别匹配以/foo和/bar开头的请求。其中uri属性指定了路由的目标地址,predicates属性指定了路由规则。 3.自定义过滤器,Spring Cloud Gateway提供了Filter接口,可以实现基于请求和响应的过滤器。以下是一个自定义的LoggingFilter,用来记录请求和响应的日志: ``` @Component public class LoggingFilter implements GlobalFilter, Ordered { private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class); private static final String START_TIME = "startTime"; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { exchange.getAttributes().put(START_TIME, System.currentTimeMillis()); return chain.filter(exchange).then( Mono.fromRunnable(() -> { Long startTime = exchange.getAttribute(START_TIME); if (startTime != null) { log.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + " ms"); } }) ); } @Override public int getOrder() { return -1; } } ``` 二、总结 Spring Cloud Gateway整合Spring Cloud的组件和功能,提供了一种轻量级、高效、易扩展的服务。通过配置路由规则和自定义过滤器,可以实现的基本功能,并且可以方便地扩展和定制化。同时,Spring Cloud Gateway还提供了丰富的插件,支持更多的业务场景和功能需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值