Created
June 7, 2024 19:36
-
-
Save geovannymcode/42daae52be866a617688357ee15ac145 to your computer and use it in GitHub Desktop.
Ejemplo Práctico: Microservicios de Pedidos y Productos con Spring Boot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SpringBootApplication | |
public class OrderServiceApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(OrderServiceApplication.class, args); | |
} | |
} | |
@RestController | |
@RequestMapping("/orders") | |
public class OrderController { | |
private final OrderService orderService; | |
private final RestTemplate restTemplate; | |
@Autowired | |
public OrderController(OrderService orderService, RestTemplate restTemplate) { | |
this.orderService = orderService; | |
this.restTemplate = restTemplate; | |
} | |
@PostMapping | |
public ResponseEntity<Order> createOrder(@RequestBody OrderRequest orderRequest) { | |
Arrays.asList(orderRequest.getProductIds()).forEach(productId -> { | |
ResponseEntity<Product> productResponse = | |
restTemplate.getForEntity("http://product-service/products/" + productId, Product.class); | |
if (!productResponse.getStatusCode().is2xxSuccessful()) { | |
throw new RuntimeException("Product validation failed"); | |
} | |
}); | |
Order order = orderService.createOrder(orderRequest); | |
return ResponseEntity.ok(order); | |
} | |
} | |
@Bean | |
public RestTemplate restTemplate() { | |
return new RestTemplate(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@SpringBootApplication | |
public class ProductServiceApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(ProductServiceApplication.class, args); | |
} | |
} | |
@RestController | |
@RequestMapping("/products") | |
public class ProductController { | |
private final ProductService productService; | |
@Autowired | |
public ProductController(ProductService productService) { | |
this.productService = productService; | |
} | |
@GetMapping("/{id}") | |
public ResponseEntity<Product> getProductById(@PathVariable Long id) { | |
Product product = productService.getProductById(id); | |
return ResponseEntity.ok(product); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment