我是靠谱客的博主 单薄火龙果,最近开发中收集的这篇文章主要介绍2-3 RestTemplate 用法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

常用方法

通过RestTemplate访问Web资源

Spring Boot 中没有自动配置Rest Template

Spring Boot 提供了RestTemplateBuilder

    RestTemplateBuilder.build()

 

GET请求  

    getForObject() / getForEntity()

POST请求

    postForObject()/postForEntity()

PUT请求

    put()

DELETE请求

    delete()

例子:String result =restTemplate.getForObject(/URI类型:/"http://example.com/...{} ...{}",String.class,"41","42")

 

构造URI

    UriComponentsBuilder

构造相对于当前请求的URI

    ServletUriComponentsBuilder

构造指向Controller的URI

    MvcUriComponentsBuilder

URI uri = UriComponentBuilder
        .fromUriString("http://example.com/hotels/{hotel}")
        .queryParam("q","{q}")
        .encode()
        .buildAndExpand("westin","123")
        .toUri();

URI uri = UriComponentsBuilder
        .fromUriString("http://example.com/hotels/{hotel}?q={q}")
        .builder("westin","123");

UriComponents uriComponents = MvcUriComponentsBuilder
    .fromMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);

URI uri = uriComponents.encode().toUri();

 

RestTemplate的高阶用法

传递HTTP Header

    RestTemplate.exchange()

    RequestEntity<T> / ResponseEntity<T>

String uriTemplate = "http://example.com/hotels/{hotel}";
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).build(42);

RequestEntity<Void> requestEntity = RequestEntity.get(uri)
        .header("MyRequestHeader","Myvalue")
        .build();

ResponseEntity<String> response = template.exchange(requestEntity,String.class);

String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();

类型转换

JsonSerializer / JsonDeserializer 

@JsonComponent   // extends StdSerialize/StdDeserialize

解析泛型对象 

自己制定一个 ptr传入

    RestTemplate.exchange()

    ParameterizedTypeReference<T>

ParameterizedTypeReference<List<Coffee>> ptr = 
                new ParameterizedTypeReference<List<Coffee>>(){};
ResponseEntity<List<Coffee>> list = restTemplate
                .exchange(coffeeUri,HttpMethod.GET,null,ptr);
list.getBody.forEach(c->log.info("coffee:{}"),c);

 

定制RestTemplate

连接管理

    PoolingHttpClientConnectionManager

    KeepAlive策略

超时设置

    connectTimeout / readTimeoud

SSL校验

    证书检查策略

连接复用

public class CustomConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy{
    private final long DEFAULT_SECONDS = 30
    
    @Override
    public long getKeepAliveDuration(HttpResponse response,HttpContext context){
        return Arrays.asList(response.getHeader(HTTP.CONN_KEEP_ALIVE))
                .stream()
                .filter(h -> StringUntils.equalsIgnoreCase(h.getName(),"timeout")
                        && StringUntis.equalsIgnoreCase(h.getValue()))
                .findFirst()
                .map(h -> NumberUntils.toLong(h.getValue(),DEFAULT_SECONDS))
                .orElse(DEFAULT_SECONDS)*1000
    }
}

默认实现 org.apache.http.impl.client.DefualtConnectionKeepAliveStrategy

构造一个requestFactory()

@Bean
public HttpComponentsClientHttpRequestFatory requestFactory(){
    PoolingHttpClientConnectionManager connectionManager = 
            new PoolingHttpClientConnectionManage(30,TimeUnit.SECONDS);
    connectionManager.setMaxTotal(200);
    connectionManager.serDefultMaxPerRoute(20);
    
    CloseableHttpClient httpClient = HttpClients.sustom()
            .setConnectionManager(connectionManager)
            .evictIdConnections(30,TimeUnit.SECONDS) //连接30s
            .disableAutomaticRetries() //关闭重试
            // 有 keep-Alive 认里面的值,没有的话永久有效
            // .setKeppAliveStrategy(DefultConnectionKeepAliveStrategy.INSTANCE)
            // 换成自定义的
            .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy())
            .build();
    
    HttpConmponentsClientHttpRequestFactory requestFactory = 
            new HttpConmponentsClientHttpRequestFactory(httpClient);

    return requestFactory ;
}

@Bean
pulic RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder
                .setConnectTimeout(Duration.ofMillis(100))
                .setReadTimeout(Duration.ofMillis(500))
                .requestFactory(this::requestFactory)
                .build();
}

 

--摘自极客时间玩转Spring全家桶

最后

以上就是单薄火龙果为你收集整理的2-3 RestTemplate 用法的全部内容,希望文章能够帮你解决2-3 RestTemplate 用法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部