微服务中传递公共参数,在网关层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
相关推荐
头茬韭菜2 小时前
第 1 篇:「Glass-Box 的骨架」——全景架构与六层数据流水线
架构·agent·semantica
奔跑的架构师4 小时前
[A-50]ARMv9/v8-DVFS系统架构
linux·arm开发·架构·系统架构·arm
闲云自留地4 小时前
动手玩 Nova:Hypervisor、主机聚合、可用分区、虚拟机生命周期实操
运维·架构·openstack
一航jason5 小时前
Android平台推理框架及试用场景模型对比
android·人工智能·ai·架构·ai编程·llama
Leo.yuan5 小时前
2026年多数据库实时同步的四种架构方案及工具推荐
数据库·架构
yychen_java7 小时前
第二篇:从世界模型到 Physical AI——一套可落地的工业智能体架构
人工智能·架构
六面体混凝土移动师9 小时前
我把 Cloudflare 开源了
架构·云计算·agent
2601_9622184712 小时前
万象生鲜系统多账套隔离技术适配集团生鲜企业集团化数字化管控
大数据·运维·微服务·云原生·架构
Seoyoneh12 小时前
云客服系统与传统本地部署客服系统:底层架构差异与选型逻辑全解析
架构