自定义注解
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyLoadBalanced {
}
@Configuration
public class MyConfig {
@Autowired(required = false)
@MyLoadBalanced
private List<RestTemplate> tpls = Collections.emptyList();
@Bean
public SmartInitializingSingleton lbInitializing() {
return new SmartInitializingSingleton() {
public void afterSingletonsInstantiated() {
for(RestTemplate tpl : tpls) {
List<ClientHttpRequestInterceptor> interceptors = tpl.getInterceptors();
interceptors.add(new MyInterceptor());
tpl.setInterceptors(interceptors);
}
//System.out.println(tpls.size());
}
};
}
}
public class MyRequest implements HttpRequest {
HttpRequest sourceRequest;
public MyRequest(HttpRequest sourceRequest) {
this.sourceRequest = sourceRequest;
}
public HttpHeaders getHeaders() {
return sourceRequest.getHeaders();
}
public HttpMethod getMethod() {
return sourceRequest.getMethod();
}
public URI getURI() {
try {
URI newUri = new URI("http://localhost:8080/hello");
return newUri;
} catch (Exception e) {
e.printStackTrace();
}
return sourceRequest.getURI();
}
}
自定义拦截器:
public class MyInterceptor implements ClientHttpRequestInterceptor {
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
System.out.println("=============== 这是自定义拦截器");
System.out.println(" 旧的uri:" + request.getURI());
HttpRequest newRequest = new MyRequest(request);
System.out.println(" 新的uri:" + newRequest.getURI());
return execution.execute(newRequest, body);
}
}
@RestController
@Configuration
public class MyController {
@Bean
@MyLoadBalanced
public RestTemplate tplA() {
return new RestTemplate();
}
@RequestMapping(value = "/call", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String call() {
RestTemplate tpl = tplA();
String json = tpl.getForObject("http://hello-servie/call", String.class);
return json;
}
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "Hello World";
}
}
启动类:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.crazyit.cloud</groupId>
<artifactId>rest-tpl-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
</dependencies>