import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List getAllUsers() {
// 查询数据库获取所有用户信息
List users = userService.getAllUsers();
return users;
}
// 其他接口方法省略...
} import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List getAllUsers() {
return userRepository.findAll();
}
// 其他业务逻辑方法省略...
} import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository{ }
public class User {
private Long id;
private String username;
private String email;
// 构造方法、getter和setter省略...
}spring:
application:
name: user-service
cloud:
config:
uri: http://config-service:8888eureka:
client:
serviceUrl:
defaultZone: http://eureka-server:8761/eureka/通过上述代码示例,我们可以快速搭建一个基于Spring Boot和Spring Cloud的微服务架构。服务注册与发现、配置中心、RESTful API等功能都可以得到支持,让开发者能够更加专注于业务逻辑的实现,提高开发效率和代码质量。