身臨其境:使用微服務架構開發Java功能的實際案例
@RestController public class UserController { @Autowired private UserService userService; @PostMapping("/register") public void registerUser(@RequestBody UserDto userDto) { userService.registerUser(userDto); } @PostMapping("/login") public void loginUser(@RequestBody UserDto userDto) { userService.loginUser(userDto); } @GetMapping("/users/{id}") public UserDto getUserById(@PathVariable String id) { return userService.getUserById(id); } }
@Service public class UserService { @Autowired private UserRepository userRepository; public void registerUser(UserDto userDto) { User user = new User(userDto); userRepository.save(user); } public void loginUser(UserDto userDto) { // 验证用户信息并生成登录令牌 } public UserDto getUserById(String id) { User user = userRepository.findById(id) .orElseThrow(() -> new NotFoundException("User not found")); return new UserDto(user); } }
@RestController public class ProductController { @Autowired private ProductService productService; @GetMapping("/products/{id}") public ProductDto getProductById(@PathVariable String id) { return productService.getProductById(id); } @GetMapping("/products") public List<ProductDto> getProducts() { return productService.getAllProducts(); } }
@Service public class ProductService { @Autowired private ProductRepository productRepository; public ProductDto getProductById(String id) { Product product = productRepository.findById(id) .orElseThrow(() -> new NotFoundException("Product not found")); return new ProductDto(product); } public List<ProductDto> getAllProducts() { List<Product> products = productRepository.findAll(); return products.stream() .map(ProductDto::new) .collect(Collectors.toList()); } }
@RestController public class OrderController { @Autowired private OrderService orderService; @PostMapping("/orders") public void placeOrder(@RequestBody OrderDto orderDto) { orderService.placeOrder(orderDto); } @GetMapping("/orders/{id}") public OrderDto getOrderById(@PathVariable String id) { return orderService.getOrderById(id); } }
以上是身臨其境:使用微服務架構開發Java功能的實際案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!