首页 > 解决方案 > 使用 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();
}

标签: spring-boothttprequestspring-webfluxwebclientdummy-data

解决方案


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(反应式编程)时,您应该始终处理MonoFlux充分利用反应式堆栈。


推荐阅读