spring-boot - 使用 Spring Boot WebClient 调用一个虚拟 api 给邮递员
问题描述
我在这里遗漏了一些东西。我正在尝试使用 Spring Boot WebClient 从作为 Http 请求的 Dummy Api 中提取信息。当我进入邮递员时,我没有得到任何信息。
感谢您能给我的任何见解。我对编码和自学仍然很陌生。
这是我的员工控制器:
@Autowired
WebClientApp webClientApp;
@GetMapping("/consume")
public String getEmployee(Model model) {
model.addAttribute("listEmployees", empServiceImpl.getAllEmployees());
model.addAttribute("listemps", webClientApp.webClientBuilder());
return "index";
}
网络客户端
private WebClient webClient;
public void SimpleWebClient(WebClient webClient) {
this.webClient = webClient;
}
public Flux<Employee> webClientBuilder() {
return this.webClient
//this.webClientBuilder = webClientBuilder.baseUrl(DummyEmployee)
.get()
.uri("api/v1/employees")
.retrieve()
.bodyToFlux(Employee.class);
}
员工
@Data
@ToString
//@AllArgsConstructor
//@NoArgsConstructor
@JsonRootName(value = "data")
public class Employee {
@JsonProperty("id")
public int employeeID;
@JsonProperty("employee_name")
public String employeeName;
@JsonProperty("employee_salary")
public String employeeSalary;
@JsonProperty("employee_age")
public int employeeAge;
@JsonProperty("employee_image")
public Blob employeeImage;
}
服务
@Repository
@ComponentScan(basePackages = {"com.example.app.repository"})
@Service
public class ServiceImpl implements EmpService{
@Autowired
private EmployeeRepository employeeRepo;
@SuppressWarnings("unchecked")
public List<Employee> getAllEmployees() {
return (List<Employee>) employeeRepo.findAll();
}
}
服务
@Service
public interface EmpService {
static List<Employee> getAllEmployees() {
// TODO Auto-generated method stub
return null;
}
}
主要的
public static void main(String[] args) {
SpringApplication.run(RestWebsiteDataProjectApplication.class, args);
}
@Bean
public WebClient webClientFromScratch() {
return WebClient.builder()
.baseUrl("https://dummy.restapiexample.com/")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
解决方案
Flux
仅在订阅时发出其内容。您没有订阅Flux
该方法返回的webClientBuilder()
内容。你不应该真的这样做,但尝试添加.block()
到你的控制器如下:
@Autowired
WebClientApp webClientApp;
@GetMapping("/consume")
public String getEmployee(Model model) {
model.addAttribute("listEmployees", empServiceImpl.getAllEmployees());
model.addAttribute("listemps", webClientApp.webClientBuilder().block());
return "index";
}
如果可行,请考虑重新编写代码,因为在使用 Spring WebFlux(反应式编程)时,您应该始终处理Mono
并Flux
充分利用反应式堆栈。
推荐阅读
- c# - 获取 OData 方法 - 单元测试
- c# - 使用 C# 以高效的方式在 MySQL 数据库表中插入数千行
- latex - 我可以在markdown中插入文件中的数字吗?
- python - 在 Pandas 中避免整数的科学记数法
- r - 如何在给定R中的向量维度的情况下创建多个方阵
- hadoop - 如何防止hadoop以安全模式启动?
- html - 如何确保长文本在圆形内水平和垂直居中
- reactjs - React Native 错误 - 未定义不是函数(评估“(0 _reactnavigation.switchnavigator)”)
- ios - 隐藏在表格视图中的自定义范围滑块
- javascript - 使用 Javascript 函数进行时间转换