gateway

在这里插入图片描述

依赖

<!--网关-->
<dependency>
    <groupId>org.springframework.cloud</groupId>

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

</dependency>

<!--nacos服务发现依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>

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

</dependency>

配置

server:
  port: 88# 网关端口
spring:
  application:
    name: gateway # 服务名称
  cloud:
    nacos:
      server-addr: localhost:8848 # nacos地址
    gateway:
      routes: # 网关路由配置
        - id: user-service # 路由id,自定义,只要唯一即可
          # uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址
          uri: lb://userservice # 路由的目标地址 lb就是负载均衡,后面跟服务名称
          predicates: # 路由断言,也就是判断请求是否符合路由规则的条件
            - Path=/api/** # 这个是按照路径匹配,只要以/user/开头就符合要求
		  filter: # 过滤器
		  	- RewritePath=/api/(?<segment>.*), /newpath/$\{segment}  # 路径重写 
	  default-filters: # 全局过滤器
        - AddRequestHeader=Default-Header, DefaultValue

启动类注册nacos发现注解

断言

predicates:
  - Path=/api/**                     # 匹配路径
  - Method=GET,POST                  # 限制 HTTP 方法
  - Host=**.example.com               # 匹配域名
  - Header=X-Request-Id, \d+          # 请求头匹配
  - Query=token                       # 请求参数必须包含 token
  - Before=2025-12-31T23:59:59.999Z   # 在某个时间之前生效
  - After=2025-01-01T00:00:00.000Z    # 在某个时间之后生效
  - Between=2025-01-01T00:00:00.000Z, 2025-12-31T23:59:59.999Z # 时间范围
  - RemoteAddr=192.168.1.1/24         # 限制 IP 地址
  - Weight=group1, 5                 # 按指定权重负载均衡,group1 组内权重为 5
  - Cookie=SESSIONID, abc123          # 包含名为 SESSIONID 的 Cookie,且值必须匹配 abc123
  - XForwardedRemoteAddr=192.168.1.0/24  # 从 X-Forwarded-For 请求头解析 IP,限制来源于 
                                           192.168.1.0/24 网段

自定义断言工厂

过滤器

filters:
  - StripPrefix=1                  # 去掉第一级路径
  - AddRequestHeader=Token, abc123  # 给请求添加请求头
  - AddResponseHeader=X-Response, OK  # 给响应添加请求头
  - RewritePath=/api/(?<segment>.*), /newpath/$\{segment}  # 路径重写
  - SetStatus=404                   # 修改返回状态码
  - Retry=5                          # 失败重试 5 次
  - RequestRateLimiter=redis-rate-limiter  # 基于 Redis 令牌桶算法限流

自定义过滤器

CORS 跨域配置

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]': # 匹配所有路径
            allowedOrigins: "https://example.com"  # 允许的来源
            allowedMethods:  # 允许的请求方法
              - GET
              - POST
              - PUT
              - DELETE
            allowedHeaders: "*"  # 允许所有请求头
            allowCredentials: true  # 允许携带 Cookie

配置类处理跨域

@Configuration
public class CorsConfig {
    /**
     * 跨域配置
     * @return
     */
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 允许哪些头部请求跨域:全部
        corsConfiguration.addAllowedHeader("*");
        // 允许哪些请求方式跨域:所有
        corsConfiguration.addAllowedMethod("*");
        // 允许哪些请求来源跨域:任意
        corsConfiguration.addAllowedOrigin("*");
        // 是否允许携带cookie跨域:是
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值