Spring Boot 2关于http接口调用4

使用WebClient

WebClient是Spring 5的反应性Web框架Spring WebFlux的一部分。
在Spring Boot中引用
compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-webflux’, version: ‘2.0.4.RELEASE’

创建实例

// 创建默认实例
static WebClient create() {
	return new DefaultWebClientBuilder().build();
}
// 创建实例(提供基础链接例如http://a.b.c.com)
static WebClient create(String baseUrl) {
	return new DefaultWebClientBuilder().baseUrl(baseUrl).build();
}

单元测试

@Test
public void test1() {
        long begin = System.currentTimeMillis();

        // GET返回简单类型
        Mono<String> responseEntity = WebClient.create().get()
                .uri(URI.create("http://localhost:9999/demo/hello"))
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
                .retrieve().bodyToMono(String.class);
        System.out.println(responseEntity.block());

        // GET带参数返回简单类型
        //Map<String, Object> paraMap = new HashMap<String, Object>();
        //paraMap.put("msg", "这是一条测试数据");
        responseEntity = WebClient.create().get()
                //.uri("http://localhost:9999/demo/hello?msg={msg}", "这是一条测试数据")
                //.uri("http://localhost:9999/demo/hello?msg={msg}", paraMap)
                .uri((uriBuilder) -> uriBuilder
                        .scheme("http")
                        .host("localhost")
                        .port("9999")
                        .path("demo/hello")
                        .queryParam("msg", "这是一条测试数据")
                        .build())
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
                .retrieve().bodyToMono(String.class);
        System.out.println(responseEntity.block());

        long end = System.currentTimeMillis();
        System.out.println("*****消耗时间(秒):" + (end - begin) / 1000.0);
}

@Test
public void test3() {
        long begin = System.currentTimeMillis();

        ParameterizedTypeReference<HttpRspDTO<String>> parameterizedTypeReference = new ParameterizedTypeReference<HttpRspDTO<String>>() {
            @Override
            public Type getType() {
                return ParameterizedTypeImpl.make(HttpRspDTO.class, new Type[]{String.class}, null);
            }
        };

        Mono<HttpRspDTO<String>> responseEntity = WebClient.create().get()
                .uri(URI.create("http://localhost:9999/demo/hello"))
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
                .retrieve().bodyToMono(parameterizedTypeReference);

        System.out.println(responseEntity.block());

        long end = System.currentTimeMillis();
        System.out.println("*****消耗时间(秒):" + (end - begin) / 1000.0);
}

源码位置

https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch01

更多推荐