SpringCloud GateWay网关的路由转发和跨域请求配置


一、实现方法

1.模块结构

在这里插入图片描述

2.pom文件引入网关依赖和注册中心依赖

在这里插入图片描述

<!--引入gateway依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--gateway也是需要注册到服务中心的-->
<!--注入eureka client 依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

3.创建启动类

在这里插入图片描述

package com.cxstar.gateway;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

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

4.创建application配置文件


server:
  port: 10086        # 网关端口

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:9999/eureka/

spring:
  application:
    name: gateway    # 服务名称
  cloud:
    gateway:

      globalcors:
        add-to-simple-url-handler-mapping: true   # 接收浏览器询问是否允许跨域的请求
        cors-configurations:
          # 仅在开发环境设置为*
          '[/**]':
            allowedOrigins:   # 允许哪些网站的ajax跨域请求
              - "http://192.168.0.46:8080"
            allowedHeaders:   # 允许的ajax跨域请求方式
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedMethods: "*"      # 允许在请求中携带的头信息
            allowCredentials: true   # 是否允许携带cookie
            maxAge: 36000            # 跨域请求有效期

      discovery:
        locator:
          enabled: true      # 开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:

        - id: order-service
          uri: lb://order-service # 匹配后提供服务的路由地址-------这里用的动态路由格式统一为 lb://注册进eureka服务中心的名字
          predicates:
            - Path=/order/** # 断言,路径相匹配的进行路由--------断言也就是匹配方式,当识别到/servero1/**时就会跳转上面的uri
#          filters:
#            - StripPrefix=1  # 例如,请求/name/bar/foo,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo-----这里写的是只去掉一个,多了自然会导致路径错误,不同的访问url配置也不同

# 配置Gateway日志等级,输出转发细节信息
logging:
  level:
    org.springframework.cloud.gateway: debug

二、测试结果

在这里插入图片描述
在这里插入图片描述

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什么都干的派森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值