Gateway

发布于:2025-02-10 ⋅ 阅读:(93) ⋅ 点赞:(0)

用来做什么

  1. 身份认证和权限校验
  2. 服务路由、负载均衡
  3. 请求限流

用法

网关也是一个微服务,因此也需要注册到nacos中

导包

<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>
    <version>3.1.7</version>
</dependency>

配置

server:
  port: 10000
spring:
  application:
    name: gateway-service
  cloud:
    nacos:
      server-addr: localhost:8848
    gateway:
      # 路由
      routes:
        - id: user-service # 路由标识,必须唯一,名字自己起
          uri: lb://user-service # 从nacos中获取路由的目标服务
          predicates:
            - Path=/user/** # 什么请求路径路由到上面配的目标服务
      # 过滤器

自定义全局过滤器

跨域问题

定义

出于安全性考虑,浏览器在请求后端接口时如果出现跨域的情况,将会拒绝接收后端请求,具体表现为AJAX 请求的回调函数不会执行,导致JS也不能解析返回结果

简单来说,如果当前我所处的页面是https://www.baidu.com,我点击一个链接,链接url是https://www.taobao.com,由于域名不同,是不会允许这次跳转成功的,出现跨域问题

什么是相同域呢?
同协议同域名同端口,任意一个不同都是跨域,http和https也是不同协议

网关访问为什么会出现跨域问题

目前理解,如果请求都从网关走,响应也是由网关响应的,是不会出现跨域问题的
但如果有外部跳转链接,就会出现跨域问题,导致跳转失败

写了个小Demo模拟

<!DOCTYPE html>
<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>Title</title>
	</head>
	<script>
	    function fun() {
	        fetch('http://localhost:10086/user/getUser/5', {
	            method: 'GET',
	            headers: {
	                'Content-Type': 'application/json'
	            }
	        })
	    }
	</script>
	<body>
	<button onclick="fun()">跨域问题</button>
	</body>
</html>

在这里插入图片描述由于IDEA开前端端口是63342,我访问的是10086,出现了跨域,果然结果返回的也是CORS错误

如何解决

浏览器会查看响应头中是否含有CORS相关信息,如果含有就会进行页面解析
在application.yml中添加跨域配置即可

	gateway:
      globalcors: # 全局的跨域处理
        add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
        corsConfigurations:
          '[/**]': # 拦截哪些请求,这里是所有
            allowedOrigins: # 允许哪些网站的跨域请求,感觉*更常用?
              - "http://localhost:63342"
            allowedMethods: # 允许的跨域ajax的请求方式
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*" # 允许在请求中携带的头信息
            allowCredentials: true # 是否允许携带cookie
            maxAge: 360000 # 这次跨域检测的有效期

在这里插入图片描述

可能出现的问题

There was an unexpected error (type=Service Unavailable, status=503).

解决方法

  • 首先看看自己的routes下面各项是否正确
  • 在2020版本之后的springcloud中nacos去除了对Ribbon的依赖,因此在uri设置lb策略会导致无法进行负载均衡,这时在项目包中添加loadbalancer依赖即可
    <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-loadbalancer</artifactId>
         <version>3.1.7</version>
    </dependency>