Spring Boot 2關於http介面呼叫(4)
阿新 • • 發佈:2019-01-06
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); }