微服务——网关

网关:网络的关口,负责请求的路由、转发、身份校验

前端请求不能直接访问微服务,而是要请求网关:

  • 网关可以做安全控制,也就是登录身份校验,校验通过才放行

  • 通过认证后,网关再根据请求判断应该访问哪个微服务,将请求转发过去

网关路由

配置格式:

复制代码
spring:
  cloud:
    getway:
      routes:
        - id: hmall-gateway
          uri: lb://gateway
          predicates:
            - Path=/api/**
        - id: hmall-item
          uri: lb://item
          predicates:
              - Path=/api/items/**

路由属性:

网关路由对应的Java类型是routeDefinition,其中常见的属性有:

  • id:路由唯一标识
  • uri:路由目标地址
  • predicates:路由断言,判断请求是否符合当前路由
  • filters:路由过滤器,对请求或响应做特俗处理

网关登录校验

在网关内进行JWT校验,在转发之前进行校验

自定义过滤器

网关过滤器有两种

  • GatewayFillter:路由过滤器,作用于任意指定的路由;默认不生效,要配置到路由后生效
  • GlobalFilter:全局过滤器,作用范围是所有路由;声明后自动生效。

两种过滤器的过滤方法签名完全一致

java 复制代码
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
        // TODO 模拟登录校验逻辑
        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.过滤器业务处理
        HttpHeaders headers = request.getHeaders();//获取请求头
        System.out.println("headers = "+headers);
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //过滤器执行顺序,数值越小,优先级越高
        return 0;
    }
}

实现登录校验

自定义一个过滤器

java 复制代码
package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;

import org.springframework.http.HttpStatus;


import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要做登录拦截
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if(headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
        //4.校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        }catch(UnauthorizedException e){
            //拦截,设置响应状态码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.传递用户信息
        System.out.println("userId:=" + userId);
        //6.放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String path){
        for(String excludePath : authProperties.getExcludePaths()){
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

网关传递用户

1.在网关的登录校验过滤器中,把获取到的用户写入请求头

java 复制代码
        //传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

2.在common中编写SpringMVC拦截器,获取登录用户

OpenFeign传递用户

相关推荐
Xの哲學7 小时前
Linux NAT 深度剖析: 从设计哲学到实现细节
linux·服务器·网络·架构·边缘计算
Allen正心正念20257 小时前
AWS专家Greg Coquillo提出的8层Agentic AI架构分析
人工智能·架构·aws
神算大模型APi--天枢6468 小时前
全栈自主可控:国产算力平台重塑大模型后端开发与部署生态
大数据·前端·人工智能·架构·硬件架构
2501_924064118 小时前
2025年优测全链路压测平台:高并发卡顿环节精准定位实践
微服务·压测方案
赵榕8 小时前
RabbitMQ发布订阅模式同一消费者多个实例如何防止重复消费?
分布式·微服务·rabbitmq
Tadas-Gao8 小时前
存储技术革命:SSD、PCIe与NVMe的创新架构设计与性能优化
java·性能优化·架构·系统架构·存储
阿里云云原生8 小时前
AgentScope x RocketMQ:打造企业级高可靠 A2A 智能体通信基座
云原生·apache·rocketmq
想用offer打牌8 小时前
一站式了解跨域问题
网络协议·面试·架构
古城小栈8 小时前
雾计算架构:边缘-云端协同的分布式 AI 推理
人工智能·分布式·架构
新手小白*8 小时前
K8s 中的 CoreDNS 组件
云原生·容器·kubernetes