1. 架构选型与决策矩阵

架构维度单体架构 (Monolith)微服务架构 (Microservices)决策依据与生产考量
部署与交付集中式单包发布,协同窗口强绑定服务级独立构建与蓝绿/金丝雀发布满足业务高频敏捷迭代诉求
数据边界共享单一数据库,跨表 ACID 强事务Database-per-Service 存储隔离,Saga 最终一致性杜绝底层物理数据模型耦合与连接数耗尽
伸缩弹性整体集群等比扩容,资源利用率低针对热点服务(如库存查询)定向水平扩展优化云资源投入产出比
容错隔离局部内存泄漏或慢查询拖垮全局服务舱壁隔离与 Resilience4j 熔断降级消除级联崩溃雪崩风险
技术异构性全局统一技术栈与依赖库版本按业务特征选择存储(PostgreSQL / MongoDB)匹配特定业务场景的最佳存储模型

2. 工业级四层分层生产代码范式

2.1 领域实体层 (Model)

java
package com.packt.bookstore.inventory.model;
 
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
 
@Entity
@Table(name = "books")
public class Book {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
    private String title;
    private String author;
    private BigDecimal price;
 
    public Book() {}
 
    public Book(Long id, String title, String author, BigDecimal price) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
    }
 
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
    public BigDecimal getPrice() { return price; }
    public void setPrice(BigDecimal price) { this.price = price; }
}

2.2 不可变传输对象 (Record DTO)

java
package com.packt.bookstore.inventory.dto;
 
import java.math.BigDecimal;
 
public record BookDTO(Long id, String title, String author, BigDecimal price) {
}

2.3 持久化仓储层 (Repository)

java
package com.packt.bookstore.inventory.repository;
 
import com.packt.bookstore.inventory.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}

2.4 业务服务层与事务控制 (Service)

java
package com.packt.bookstore.inventory.service;
 
import com.packt.bookstore.inventory.dto.BookDTO;
import com.packt.bookstore.inventory.repository.BookRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.List;
 
@Service
public class BookService {
 
    private final BookRepository bookRepository;
 
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
 
    @Transactional(readOnly = true)
    public List<BookDTO> getAllBooks() {
        return bookRepository.findAll().stream()
            .map(book -> new BookDTO(
                book.getId(),
                book.getTitle(),
                book.getAuthor(),
                book.getPrice()
            ))
            .toList();
    }
}

2.5 表现控制器层 (Controller)

java
package com.packt.bookstore.inventory.controller;
 
import com.packt.bookstore.inventory.dto.BookDTO;
import com.packt.bookstore.inventory.service.BookService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.List;
 
@RestController
@RequestMapping("/books")
public class BookController {
 
    private final BookService bookService;
 
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }
 
    @GetMapping
    public ResponseEntity<List<BookDTO>> getAllBooks() {
        return ResponseEntity.ok(bookService.getAllBooks());
    }
}

3. Bookstore 平台端到端微服务拓扑流图

text
[ 浏览器客户端:Angular 22 SPA (Signals + Standalone) ]
                          │
            HTTPS / REST  │  JWT Bearer Token
                          ▼
        [ API 网关:Spring Cloud Gateway ] ──> [ Keycloak 认证中心 ]
        (统一路由 / JWT 鉴权校验 / 路径重写)       (OAuth 2.0 / OIDC 验签)
                          │
      ┌───────────────────┴───────────────────┐
      │ /packt/inventory/api/**               │ /packt/user/api/**
      ▼                                       ▼
[ 库存微服务: inventory-ms ]            [ 用户微服务: user-ms ]
(Spring Boot 4.1 + JPA)                 (Spring Boot 4.1 + Mongo)
      │                                       │
      ▼                                       ▼
 [ PostgreSQL 17 ]                       [ MongoDB 8 ]
      │                                       │
      └───────────────────┬───────────────────┘
                          │ Micrometer Tracing (TraceId / SpanId)
                          ▼
            [ 分布式链路监控:Zipkin ]

4. 微服务架构避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
跨微服务提取共享包含业务实体的 Common Jar 依赖库。维护微服务边界自治,跨服务仅共享轻量 OpenAPI 契约或 DTO Spec。
将持久化 @Entity 直接作为 HTTP 控制器出参暴露。使用不可变 Java record 作为 DTO,在服务层完成隔离映射。
多个微服务直连读写同一个底层物理数据库。严格执行 Database-per-Service 规范,服务间数据交互一律经由 API 或领域事件。
沿技术维度切分服务(如 Controller 集中服务、Service 集中服务)。遵循 DDD 限界上下文,按业务能力(库存、用户、订单)进行纵向切分。
依赖重型企业服务总线(ESB)完成复杂业务逻辑转换。遵循“聪明端点,管道极简(Smart Endpoints, Dumb Pipes)”原则,业务收敛于微服务内部。