RestTemplate调用前统一申请Token传递到调用的服务中
如果项目中用的 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;
    }
}
所有教程
- C语言入门
- C语言编译器
- C语言项目案例
- 数据结构
- C++
- STL
- C++11
- socket
- GCC
- GDB
- Makefile
- OpenCV
- Qt教程
- Unity 3D
- UE4
- 游戏引擎
- Python
- Python并发编程
- TensorFlow
- Django
- NumPy
- Linux
- Shell
- Java教程
- 设计模式
- Java Swing
- Servlet
- JSP教程
- Struts2
- Maven
- Spring
- Spring MVC
- Spring Boot
- Spring Cloud
- Hibernate
- Mybatis
- MySQL教程
- MySQL函数
- NoSQL
- Redis
- MongoDB
- HBase
- Go语言
- C#
- MATLAB
- JavaScript
- Bootstrap
- HTML
- CSS教程
- PHP
- 汇编语言
- TCP/IP
- vi命令
- Android教程
- 区块链
- Docker
- 大数据
- 云计算
