我正在尝试使用 Java + Spring + WebFlux 开始响应式编程。
我创建了一个微服务,它生成 Mono<Customer>
通过 Controller 。
@RestController
@RequestMapping("/customers")
public class CustomerController {
@GetMapping("/{id}")
public Mono<Customer> customerById(@PathVariable String id){
return customerService.findById(id);
}
}
public class Customer {
public Customer(String id, String fullName) {
this.id = id;
this.fullName = fullName;
}
@Id
private String id;
@NotNull(message = "The name must not be null")
private String fullName;
private String email;
private String document;
}
另一个微服务使用这个 Mono,它是上述类的副本,但 Spring Validation
除外。注释。
关于制作人:
//Service Class
public Mono<Customer> findById(String id){
return Mono.just(new Customer(id, "Joseph"));
}
//Method on Controller
@RestController
@RequestMapping("v1/customers")
public class CustomerController {
@GetMapping("/{id}")
public Mono<Customer> customerById(@PathVariable String id){
return customerService.findById(id);
}
}
当我在Customer Producer
上打开浏览器时端点,我得到以下信息:
{
id: "123",
fullName: "Joseph",
email: null,
document: null
}
当我调用GET
时关于Customer Consumer
端点,我得到 HTTPCode = 500
下面是 Customer Consumer
上的服务层
private String BASE_URL = "http://localhost:8060/";
public Mono<Customer> findById(String id){
WebClient.Builder builder = WebClient.builder();
return builder
.baseUrl(BASE_URL)
.build()
.get()
.uri("customers/{id}", id)
.retrieve()
.bodyToMono(Customer.class);
}
我还尝试删除 .baseUrl(BASE_URL)
并连接在 .uri()
,但没有成功。
我在消费者方面遇到的错误:
2019-12-01 22:21:45.910 ERROR 16788 --- [ctor-http-nio-2] a.w.r.e.AbstractErrorWebExceptionHandler : [1510eee8] 500 Server Error for HTTP GET "/v1/customers/123"
java.lang.NullPointerException: null at com.poc.controller.CustomerController.findById(CustomerController.java:19) ~[classes/:na]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? HTTP GET "/v1/customers/123" [ExceptionHandlingWebHandler]
Stack trace:
at com.poc.webportal.controller.CustomerController.findById(CustomerController.java:19) ~[classes/:na]
PS:我知道 WebClient 应该位于 bean
上,但举例来说,我只是想在重构代码之前使其工作。
最佳答案
这很尴尬,但我忘记在 Controller 上注入(inject)CustomerService
。
所以,Autowired
解决了这个问题..
关于java - WebClient 调用时出现 Webflux 微服务错误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59131264/