当前位置:网站首页>微服务之间的Token传递之一@Feign的token传递
微服务之间的Token传递之一@Feign的token传递
2022-06-26 04:51:00 【RabbitMq_mr wang】
方法一,@RequestHeader
在请求调用方的微服务方法头中添加@RequestHeader用来接收用户端请求时传入的token,关键代码片段
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ShareDTO findById(HttpServletRequest request,
@PathVariable Integer id,
@RequestParam(name = "foo") String foo,
@RequestHeader("X-Token") String token) {
System.out.println(foo);
return this.shareService.findById(id, token);
}
这里获取到header中的“X-Token”
在采用Feign调用其他微服务时将获取到的Token传入到下一个微服务的请求头中
@GetMapping("/users/{id}")
UserDTO findById(@PathVariable Integer id, @RequestHeader("X-Token") String token);
这里的@RequestHeader的意思是将参数token放入到下个请求的请求头header中。到此,使用这种方式进行token传递就可以实现了。
方法2 使用Feign的Interceptor
Step1 实现RequestInterceptor接口
apply->获取到X-Token
Step2 将token传递给下一次请求
实现一个RequestInterceptor
实现内容如下
//省略包名
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @author frend
* @version v0.0.1
* @apiNote feign传递token拦截统一处理
* @time 2020/10/26 12:48
* @parjectName rate-content-center
*/
public class TokenTelayRequestIntecepor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 从header获取X-token
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes srat = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = srat.getRequest();
String token = request.getHeader("X-Token");
if (StringUtils.isNotBlank(token)) {
//将token传递出去
requestTemplate.header("X-Token", token);
}
}
}
这里先获取到HTTPServletRequest
接着在从request中获取到header的“X-Token”
将这个token传递给requestTemplate
Interceptor实现之后还需要对这个Interceptor设置配置
Step3 配置Feign
给全局配置一个 requestInterceptors: 将上面的实现了RequestInterceptor的类全路径给这个配置
feign:
client:
config:
default:
loggerLevel: full
requestInterceptors:
- org.rate.contentcenter.feignclients.interceptor.TokenTelayRequestIntecepor
到此,全局的FeignToken传递就实现完成了。
最后做个总结:
1.使用@RequestHeader的方式比较直观,也较为容易理解,但是当对接口进行改造,或者服务接口过多时,任务量巨大
2.使用RequestInterceptor拦截器,在理解上有一些抽象,不过这种方式在实际操作和代码的耦合上是非常有优势的。
边栏推荐
- 问题随记 —— pip 换源
- Differences between TCP and UDP
- Tips for using idea
- Solution to back-off restarting failed container
- Genius makers: lone Rangers, technology giants and AI | ten years of the rise of in-depth learning
- 1.24 learning summary
- [H5 development] 02 take you to develop H5 list page ~ including query, reset and submission functions
- Sort query
- numpy 索引及切片
- YOLOV5训练结果的解释
猜你喜欢

为什么许多shopify独立站卖家都在用聊天机器人?一分钟读懂行业秘密!

How can the intelligent transformation path of manufacturing enterprises be broken due to talent shortage and high cost?

0622 horse palm fell 9%

一个从坟墓里爬出的公司

图像翻译/GAN:Unsupervised Image-to-Image Translation with Self-Attention Networks基于自我注意网络的无监督图像到图像的翻译

08_ Spingboot integrated redis

Text horizontal alignment attribute text align and element vertical alignment attribute vertical align

企业的产品服务怎么进行口碑营销?口碑营销可以找人代做吗?

Thinkphp6 implements a simple lottery system

Illustration of ONEFLOW's learning rate adjustment strategy
随机推荐
Image translation /gan:unsupervised image-to-image translation with self attention networks
1.21 learning summary
Hash problem
基础查询
Multipass Chinese document - remote use of multipass
问题随记 —— pip 换源
Some parameter settings and feature graph visualization of yolov5-6.0
UWB超高精度定位系统架构图
Physical design of database design (2)
2022 talent strategic transformation under the development trend of digital economy
Multipass中文文档-使用Packer打包Multipass镜像
PSIM software learning ---08 call of C program block
What is the best way to store chat messages in a database? [Close] - best way to store chat messages in a database? [closed]
ModuleNotFoundError: No module named ‘numpy‘
Sixtool- source code of multi-functional and all in one generation hanging assistant
Multipass Chinese documents - improve mount performance
图解OneFlow的学习率调整策略
Yapi cross domain request plug-in installation
[IDE(ImageBed)]Picgo+Typora+aliyunOSS部署博客图床(2022.6)
A ZABBIX self discovery script (shell Basics)