2025年3月25日 星期二 甲辰(龙)年 月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Spring Cloud

RestTemplate调用前统一申请Token传递到调用的服务中

时间:03-13来源:作者:点击数:99

如果项目中用的 RestTemplate 来调用服务提供的接口,可以利用 RestTemplate 的拦截器来传递 Token,代码如下所示。

  • @Component
  • public class TokenInterceptor implements ClientHttpRequestInterceptor {
  • @Override
  • public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
  • throws IOException {
  • System.err.println("进入RestTemplate拦截器");
  • HttpHeaders headers = request.getHeaders();
  • headers.add("Authorization", System.getProperty("fangjia.auth.token"));
  • return execution.execute(request, body);
  • }
  • }

将拦截器注入 RestTemplate,代码如下所示。

  • @Configuration
  • public class BeanConfiguration {
  • @Autowired
  • private TokenInterceptor tokenInterceptor;
  • @Bean
  • @LoadBalanced
  • public RestTemplate getRestTemplate() {
  • RestTemplate restTemplate = new RestTemplate();
  • restTemplate.setInterceptors(Collections.singletonList(tokenInterceptor));
  • return restTemplate;
  • }
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门