在Spring WebFlux中,我们可以使用bodyToMono
和bodyToFlux
方法从响应中获取数据。这两种方法的区别在于它们返回的类型不同。
bodyToMono
方法返回一个Mono
对象,表示0或1个元素的序列。这对应于响应体中的单个对象。
bodyToFlux
方法返回一个Flux
对象,表示0或多个元素的序列。这对应于响应体中的多个对象。
下面是一些代码示例,展示了如何使用这两种方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class MyService {
private final WebClient webClient;
@Autowired
public MyService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.build();
}
public Mono getUserById(String id) {
return webClient.get()
.uri("/users/{id}", id)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(User.class);
}
public Flux getAllUsers() {
return webClient.get()
.uri("/users")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(User.class);
}
public Flux getUsersByIds(List ids) {
return webClient.get()
.uri("/users")
.accept(MediaType.APPLICATION_JSON)
.bodyValue(ids)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference() {});
}
}
在上面的示例中,getUserById
方法使用bodyToMono
返回一个Mono
对象,表示单个用户对象。
getAllUsers
方法使用bodyToFlux
返回一个Flux
对象,表示多个用户对象。
getUsersByIds
方法展示了如何使用ParameterizedTypeReference
来获取一个列表的用户对象。这里使用了bodyToFlux
方法,并使用ParameterizedTypeReference
来指定序列中的元素类型。
希望以上解决方法对你有帮助!