【spring cloud】gateway 的配置

在 Spring Cloud Alibaba 中,配置 Gateway 的步骤和注意事项如下:

1. 添加依赖

首先,在 pom.xml 中添加必要的依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

2. 配置 Nacos

application.ymlapplication.properties 文件中配置 Nacos 服务发现:

spring:
  application:
    name: gateway-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      discovery:
        locator:
          enabled: true

3. 配置路由规则

application.yml 文件中配置 Gateway 路由规则。例如:

spring:
  cloud:
    gateway:
      routes:
        - id: service-route
          uri: lb://service-name
          predicates:
            - Path=/service/**
          filters:
            - StripPrefix=1
配置项解释:
  • id: 路由的唯一标识。
  • uri: 目标服务地址。lb:// 表示使用负载均衡。
  • predicates: 路由断言,用于匹配请求路径等。
  • filters: 路由过滤器,用于修改请求和响应。

4. 自定义过滤器

如果需要自定义过滤器,可以创建一个新的过滤器类。例如:

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class CustomFilter extends AbstractGatewayFilterFactory<CustomFilter.Config> {

    public CustomFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 自定义过滤逻辑
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // 响应逻辑
            }));
        };
    }

    public static class Config {
        // 配置属性
    }
}

application.yml 中使用自定义过滤器:

spring:
  cloud:
    gateway:
      routes:
        - id: service-route
          uri: lb://service-name
          predicates:
            - Path=/service/**
          filters:
            - name: CustomFilter

5. 其他配置项

除了上述基本配置,还可以根据需要配置其他选项,例如全局过滤器、请求限流、熔断等。

全局过滤器

application.yml 中配置全局过滤器:

spring:
  cloud:
    gateway:
      default-filters:
        - name: CustomGlobalFilter
请求限流

使用 Redis 作为限流存储:

spring:
  cloud:
    gateway:
      routes:
        - id: service-route
          uri: lb://service-name
          predicates:
            - Path=/service/**
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20

6. 启动应用

确保 Nacos 服务器已经启动,然后启动 Gateway 服务。访问配置的路由路径,验证 Gateway 的配置是否生效。

通过以上步骤,实现在 Spring Cloud Alibaba 使用 Gateway 实现服务路由和负载均衡等功能。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值