Java 成长:从 SpringBoot 入门到微服务架构设计的 6 个核心步骤

步骤 1:SpringBoot 基础搭建

目标:创建最小可运行项目
关键代码

@SpringBootApplication
public class HelloApp {
    public static void main(String[] args) {
        SpringApplication.run(HelloApp.class, args);
    }
    
    @RestController
    public class HelloController {
        @GetMapping("/hello")
        public String hello() {
            return "服务已启动!";
        }
    }
}

说明:通过@SpringBootApplication实现自动配置,@RestController定义 REST 接口。


步骤 2:数据层集成

目标:连接数据库并实现 CRUD
关键代码

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // Getter/Setter
}

@Repository
public interface UserRepo extends JpaRepository<User, Long> {}

@Service
public class UserService {
    @Autowired
    private UserRepo userRepo;
    
    public User createUser(String name) {
        User user = new User();
        user.setName(name);
        return userRepo.save(user);
    }
}

说明:使用 Spring Data JPA 简化数据库操作,@Entity映射表结构。


步骤 3:RESTful API 设计

目标:构建标准化接口
关键代码

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        return ResponseEntity.ok(userService.createUser(user.getName()));
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}

说明:通过@PathVariable获取参数,@RequestBody处理 JSON 请求。


步骤 4:服务拆分

目标:模块化拆分单体应用
项目结构

├── user-service (独立模块)
│   ├── UserController.java
│   └── UserService.java
├── order-service (独立模块)
│   ├── OrderController.java
│   └── OrderService.java
└── gateway (API 网关)

关键配置

# application.yml (每个微服务)
spring:
  application:
    name: user-service  # 服务唯一标识
server:
  port: 8081           # 差异化端口


步骤 5:服务注册与发现

目标:实现动态服务定位
关键组件:Spring Cloud Netflix Eureka
注册中心代码

@EnableEurekaServer
@SpringBootApplication
public class RegistryCenter {
    public static void main(String[] args) {
        SpringApplication.run(RegistryCenter.class, args);
    }
}

服务注册(在微服务中添加):

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka


步骤 6:微服务通信

目标:服务间可靠调用
方案:OpenFeign + 熔断机制
示例代码

// 在 order-service 中调用 user-service
@FeignClient(name = "user-service", fallback = UserFallback.class)
public interface UserClient {
    @GetMapping("/api/users/{id}")
    ResponseEntity<User> getUser(@PathVariable Long id);
}

@Component
public class UserFallback implements UserClient {
    @Override
    public ResponseEntity<User> getUser(Long id) {
        return ResponseEntity.ok(new User(0L, "默认用户"));  // 熔断返回
    }
}

// 在 OrderService 中使用
public class OrderService {
    @Autowired
    private UserClient userClient;
    
    public Order createOrder(Long userId) {
        User user = userClient.getUser(userId).getBody();
        // 业务逻辑...
    }
}


架构演进示意图

graph LR
A[单体应用] --> B[模块拆分]
B --> C[服务注册中心]
C --> D[API网关]
D --> E[微服务集群]
E --> F[熔断/限流]

关键收获

  1. $单体 \rightarrow 微服务$的渐进式演进
  2. 服务治理核心公式:
    $$服务可用性 = \frac{成功请求数}{总请求数} \times 100%$$
  3. 通过 Feign 声明式调用降低耦合度
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐