微服务中传递公共参数,在网关层header添加参数,各子微服务,openfeign,线程池等地方拿到网关传递过来的参数

需求:

网关层在header中添加参数,header-user_id=1001,header-user_name=小明

各个子微服务,可以通过openfeign,线程池等方式拿到上面的参数

1 网关层 gateway添加需要传递的参数信息

复制代码
import cn.hutool.core.net.URLEncodeUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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;

/**
 * 认证过滤器组件
 * 该组件用于检查请求中的认证令牌,以确保只有合法的请求才能继续传递到下游服务
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器的主要逻辑
     * 检查请求中的令牌,如果不是预期的令牌,则返回未授权的状态
     * 如果令牌有效,则在请求头中添加公共请求参数,并将请求传递给下游服务
     *
     * @param exchange 当前的服务器Web交换对象,包含请求和响应信息
     * @param chain    网关过滤器链,用于将请求传递给下一个过滤器或最终的目标服务
     * @return Mono<Void> 表示异步处理的空结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = getToken(request);
        // 根据自己的逻辑来判断处理
        if (!"xxx".equals(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
            DataBuffer dataBuffer = response.bufferFactory().wrap("Invalid token".getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }

        // 放入公共请求参数到请求头中,向下层服务中传递
        ServerHttpRequest.Builder mutate = request.mutate();
        mutate.header("header-user_id", "1001");
        mutate.header("header-user_name", URLEncodeUtil.encode("小明"));
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    /**
     * 获取请求中的令牌
     * 当前实现简单地从请求头中获取名为"token"的值
     *
     * @param request 当前的HTTP请求对象
     * @return String 表示请求中的令牌
     */
    private String getToken(ServerHttpRequest request) {
        return request.getHeaders().getFirst("token");
    }

    /**
     * 获取过滤器的顺序
     * 返回Ordered.LOWEST_PRECEDENCE表示该过滤器具有最低的优先级
     *
     * @return int 表示过滤器的顺序值
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}

2 新建一个中间处理层微服务,处理openfeign,普通请求,线程池中拿到header参数传递的逻辑

3 在各个子微服务中拿参数,@FeignClient要加上configuration 属性

复制代码
@FeignClient(name = "chao-chi-service", path = "/chi_controller",configuration = SystemContextRequestInterceptor.class)

@GetMapping("/getheadparam")
public String test1() {
        
        Map<String, String> contextMap = SystemContextHolder.getSystemContext().getContextMap();
        log.info("contextMap:{}", JSONUtil.toJsonPrettyStr(contextMap));
        
        this.threadPoolExecutor.execute(() -> {
            log.info("通过线程池 execute 执行任务,{}", SystemContextHolder.getSystemContext().getContextMap());
        });
        
        //5、使用线程池执行任务,调用的是 submit 方法
        this.threadPoolExecutor.submit(() -> {
            log.info("通过线程池 submit 执行任务,{}", SystemContextHolder.getSystemContext().getContextMap());
        });
        
        return "我是child-service-getHeadParam--------------"+JSONUtil.toJsonStr(contextMap);
    }

代码链接

复制代码
通过网盘分享的文件:微服务网关层发送参数-各子微服务通过openfeign-线程池等方式拿到参数.rar
链接: https://pan.baidu.com/s/1_NrJ-wz7-zmGlIskdPApwA?pwd=88cx 提取码: 88cx
相关推荐
黄俊懿3 小时前
【架构师从入门到进阶】第七章:缓存和存储的优化思路——第五节:缓存更新机制说明
缓存·性能优化·架构·系统架构
喵个咪4 小时前
GoWind Trade(风帆):从询盘到收款的外贸全流程一体化平台
后端·架构·go
喵个咪4 小时前
GoWind IM 私有化快速部署:研发型企业自己的协同底座
后端·架构·go
Dawson Zhu10 小时前
【模型量化⑨】量化选型决策树:如何为你的模型选择最优量化方案
人工智能·语言模型·架构·aigc·agi
Dawson Zhu10 小时前
【模型量化⑪】FP8量化:E4M3/E5M2格式、细粒度Scaling与训练推理全解析
人工智能·语言模型·架构·aigc·agi
数字孪生视频孪生12 小时前
场景自生长:无需人工建模的空间数字化路径
大数据·人工智能·重构·架构·空间计算
艾莉丝努力练剑14 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
aimartec14 小时前
企业小程序与APP定制源码买断工程实践:三层解耦架构、状态机防呆与平滑迁移清单
小程序·架构
Wellijohn14 小时前
让 AI 能改数据库,但不能背着你改:我给 MCP Server 装了一道审批闸
python·架构·mcp
飞奔的瓜牛14 小时前
呼叫中心部署架构与技术全景:从集中式到云原生智能客服
云原生·架构