对Spring 的RestTemplate进行包装

Spring的RestTemplate及大地简化了REST Client的开发,但每次还要编写大量的模板代码,代码不够简洁。我对他进行了一次包装,采用接口来声明REST接口,使用Annotation对interface的方法进行标注。如下声明一个REST接口

//接口必须继承BaseRestClient,提供了一个setUrl的基本方法。
public interface ITestRest extends BaseRestClient
{
    //声明一个REST方法,method是GET,在路径里面有个参数id,如:  http://localhost:8080/get/{id}。返回一个UserInfo对象,由Json反射过来。
    @RestClient(method = HttpMethod.GET)
    UserInfo getUser(@PathParam(value = "id") String id);
    //声明一个REST方法,method用POST,除了路径里面的id,还有一个表单
    @RestClient(method = HttpMethod.POST)
    UserInfo postUser(@PathParam(value = "id") String id,@FormBody UserForm form);
    //表单中含有文件
    @RestClient(method = HttpMethod.POST,hasFile = true)
    UserInfo postUserWithFile(@PathParam(value = "id") String id,@FormBody UserFormWithFile form); 
}

声明Bean

@Bean
    public ITestRest testRest(RestTemplate restTemplate){
        ITestRest testRest= RestClientBuilder.newRestClient(ITestRest.class,restTemplate);
        return  testRest;
    }
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplateBuilder()
                .additionalMessageConverters(new MappingJackson2HttpMessageConverter())
                .additionalMessageConverters(new FormHttpMessageConverter()).build();
    }

调用方

    @Autowired
    ITestRest testRest;
    ......
    testRest.setUrl("http://localhost:8080/get/{id}");
    UserInfo user=testRest.getUser("123456");

由于访问路径可能会变化,比如采用了集群,所以在调用前需要set一下,url放到ThreadLocal里面,线程安全。 
如果不变,可以在@RestClient声明中加上path指定访问地址 
github地址:https://github.com/bobdeng/ssrf

posted @ 2018-04-20 12:30  ido  阅读(1297)  评论(0编辑  收藏  举报