Spring Boot与微服务架构:快速开发指南
// 假设存在一个User实体类和对应的UserRepository
@Entity
public class User {
@Id
private Long id;
private String name;
// 省略其他字段、构造函数、getter和setter
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// 这里可以添加自定义查询方法
}
// 微服务控制器示例
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// 获取所有用户列表
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userRepository.findAll();
if (users.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(users, HttpStatus.OK);
}
// 根据ID获取单个用户
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> user = userRepository.findById(id);
return user.map(response -> new ResponseEntity<>(response, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
// 创建新用户
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
return new ResponseEntity<>(userRepository.save(user), HttpStatus.CREATED);
}
// 更新现有用户
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody User userRequest) {
return userRepository.findById(id)
.map(user -> {
user.setName(userRequest.getName()); // 更新字段
return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
})
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
// 删除用户
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Long id) {
return userRepository.findById(id)
.map(user -> {
userRepository.delete(user);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK);
})
.orElse(new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND));
}
}
这个代
评论已关闭