ITPub博客

首页 > 架构设计 > 软件结构 > (62)Spring Cloud企业快速开发架构之RestTemplate调用前统一申请Token传递到调用的

(62)Spring Cloud企业快速开发架构之RestTemplate调用前统一申请Token传递到调用的

原创 软件结构 作者:JIAN2 时间:2021-10-08 09:45:55 0 删除 编辑

 如果项目中用的 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;
    }
}




来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70006413/viewspace-2794826/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
华为资深架构师,曾参与华为数据中心迁移解决方案!有需要了解分布式微服务电商源码的朋友可以+我 v ❤: haiwabbc2 , 10余年互联网研发行业经验!博客里面是个人的一点技术总结,希望能够帮助到更多的IT朋友成长!

注册时间:2021-09-06

  • 博文量
    1404
  • 访问量
    622745