最近要在后台写一个异步POST请求,发现原来的AsyncResttemplate过时了,说明文档中提到了替代类WebClient。
于是查找文档,写了一个DEMO。下面是部分代码段。
首先在POM引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
POST请求
String url = configStorage.getApiUrl(WxCpApiPathConsts.Tp.GET_SUITE_TOKEN);
Map<String, String> params = new HashMap<String, String>();
params.put("suite_id", suiteId);
params.put("suite_secret", suiteSecret);
params.put("suite_ticket", suiteTicket);
WebClient client = WebClient.create();
@SuppressWarnings("rawtypes")
Flux<Map> mapFlux = client.post().uri(url).contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromObject(JSON.toJSONString(params))).retrieve().bodyToFlux(Map.class);
// 异步执行的方法,在里面可以执行http响应后需要执行的后续操作
// mapFlux.collectList().subscribe(list -> System.out.println(list.toString() + "list"));
mapFlux.subscribe(map -> System.out.println(map.toString() + "map"));