我想用 Springboot 构建微服务。我想在订单服务和库存服务之间进行通信。但是当我尝试使用 webclient get 方法从订单服务连接库存服务时,IDE 总是返回
路径 [] 上下文中 servlet [dispatcherServlet] 的 Servlet.service() 抛出异常 [请求处理失败:org.springframework.web.reactive.function.client.WebClientRequestException:连接被拒绝:没有更多信息:localhost/192.168.1.1:8080] 其根本原因
无论我尝试什么,都无法解决这个问题。
订单管理器=
@Service
@AllArgsConstructor
@Transactional
public class OrderManager implements OrderService {
private OrderRepository orderRepository;
private ModelMapperService modelMapperService;
private WebClient webClient;
@Override
public void placeOrder(OrderRequest orderRequest) {
Order order = new Order();
order.setOrderNumber(UUID.randomUUID().toString());
List<OrderLineItems> orderLineItemsList= orderRequest.getOrderLineItemsResponseList().stream()
.map(orders -> this.modelMapperService.forResponse().map(orders, OrderLineItems.class)).collect(Collectors.toList());
order.setOrderLineItemsList(orderLineItemsList);
List<String> skuCodes = order.getOrderLineItemsList().stream()
.map(OrderLineItems::getSkuCode)
.toList();
InventoryResponse[] inventoryResponsesArray = this.webClient.get()
.uri("http://localhost:8080/api/v1/inventory", uriBuilder -> uriBuilder.queryParam("skuCode",skuCodes).build())
.retrieve()
.bodyToMono(InventoryResponse[].class)
.block();
boolean allProductIsInStock = Arrays.stream(inventoryResponsesArray)
.allMatch(InventoryResponse::isInStock);
if ( allProductIsInStock){
this.orderRepository.save(order);
}
else {
throw new IllegalArgumentException("Product is not in stock");
}
}
}
库存管理器=
@Service
@AllArgsConstructor
public class InventoryManager implements InventoryService {
private final InventoryRepository inventoryRepository;
@Override
@Transactional(readOnly = true)
public List<InventoryResponse> isInStock(List<String> skuCode) {
return inventoryRepository.findBySkuCodeIn(skuCode).stream()
.map(inventory ->
InventoryResponse.builder()
.skuCode(inventory.getSkuCode())
.isInStock(inventory.getQuantity()> 0)
.build()
).toList();
}
订单控制器=
@RestController
@RequestMapping("/api/v1/order")
@AllArgsConstructor
public class OrderController {
private OrderService orderService;
@PostMapping()
@ResponseStatus(HttpStatus.CREATED)
public String placeOrder(@RequestBody OrderRequest orderRequest){
this.orderService.placeOrder(orderRequest);
return "Order Placed Successfully";
}
}
库存控制器=
@RestController
@RequestMapping("/api/v1/inventory")
@AllArgsConstructor
public class InventoryController {
private final InventoryService inventoryService;
@GetMapping()
@ResponseStatus(HttpStatus.OK)
public List<InventoryResponse> isInStock(@RequestParam() List<String> skuCode){
return this.inventoryService.isInStock(skuCode);
}
@GetMapping("/gets")
public List<Inventory> gets(){
return this.inventoryService.find();
}
}
我禁用了防火墙,并在防火墙的设置中让 TCP 响应数据。毕竟,他们并没有帮助解决我的解决方案。
本地主机系统的端口 URL 不同。当我从 cmd 检查时:
netstat -a
我的端口
8080
正在从 0.0.0.0
监听。当我写下 0.0.0.0
而不是 localhost
后,我的代码就按照我的预期运行了。