码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Spring-Cloud-Openfeign如何传递用户信息?


    用户信息传递

    微服务系统中,前端会携带登录生成的token访问后端接口,请求会首先到达网关,网关一般会做token解析,然后把解析出来的用户ID放到http的请求头中继续传递给后端的微服务,微服务中会有拦截器来做用户信息的拦截,把用户信息存放到ThreadLocal供接口使用。
    在这里插入图片描述

    feign远程调用的时候,有时候也需要把消费者端的用户信息传递到服务提供者端,否则可能因为没有用户信息而无法调用接口。feign调用并不会走网关,是由服务消费者直接去调用服务提供者,在消费者端已经有userId的前提下,只需要把userId放到Http的请求头中就可以继续复用微服务中HandlerInterceptor对userId的处理逻辑了。

    feign拦截器

    feign提供了一个拦截器的接口:

    public interface RequestInterceptor {
      /**
       * Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
       */
      void apply(RequestTemplate template);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这个接口中有一个RequestTemplate 对象,我们就可以使用这个对象来传递请求头。

    1)需要定义一个拦截器的实现类
    public class FeignRelayUserInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate template) {
            // 从TL中获取用户id
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return;
            }
            // 放入http的请求头中
            template.header("userId", userId.toString());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    2)在feign的配置类中注入这个拦截器
    public class FeignConfig {
        @Bean
        public FeignRelayUserInterceptor feignRelayUserInterceptor(){
            return new FeignRelayUserInterceptor();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    3)在feign接口中引用这个配置类
    @FeignClient(value = "user-service", 
    	url = "http://localhost:8081", 
    	configuration = FeignConfig.class)
    public interface UserClient {
        @GetMapping("/user/{id}")
        public User queryById(@PathVariable("id") Long id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    测试

    在服务提供者端从请求头中获取userId:

    @GetMapping("/{id}")
        public User queryById(@PathVariable("id") Long id,
         @RequestHeader("userId")Long userId) {
            log.info("============>userId:{}", userId);
            return userService.queryById(id);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    完整的源码下载:
    https://github.com/xjs1919/enumdemo/tree/master/feign-interceptor-demo

  • 相关阅读:
    给 K8s 中的 Operator 添加 Webhook 功能【保姆级】
    R语言贝叶斯非参数模型:密度估计、非参数化随机效应META分析心肌梗死数据...
    【Spring(二)】java对象属性的配置(Bean的配置)
    Vue ElementUI el-tooltip 全局样式修改
    使用二叉树的递归套路来解决的问题
    ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法
    【解决】刷了Magisk修改后的boot,magisk仍然没有ROOT
    java计算机毕业设计至臻阁古董拍卖网源码+数据库+系统+部署+lw文档
    【hisi】——hisi开发相关文档
    基于vue3+ts5+vue-router4+pinia2的PC端项目搭建教程
  • 原文地址:https://blog.csdn.net/goldenfish1919/article/details/132634446
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号