0Pricing
Clean Architecture & Design Patterns in Practice · 课时

微服务中的整洁架构

探索如何在各个微服务内部应用整洁架构原则,以保持内部一致性和自主性。

微服务中的整洁架构 是 CoddyKit 上的免费 Clean Architecture & Design Patterns in Practice 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clean Architecture & Design Patterns in Practice 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Microservices Meet Clean Arch

Welcome! In this lesson, we'll explore how the powerful principles of Clean Architecture can be applied within individual microservices.

Microservices are small, independent services that communicate with each other. Combining them with Clean Architecture helps each service stay robust, maintainable, and truly autonomous.

Bounded Contexts & Microservices

A key concept in microservices is the Bounded Context. This means each service defines its own domain model and terminology, separate from others.

  • A microservice naturally forms a bounded context.
  • Clean Architecture provides a structured way to manage the internal complexity of this context.
  • It keeps the core business rules of the microservice isolated.

CA Inside a Microservice

Think of each microservice as having its own miniature Clean Architecture structure. The concentric circles apply internally:

  • Entities: Core business objects (e.g., User, Product).
  • Use Cases: Application-specific rules (e.g., CreateUser, PlaceOrder).
  • Interface Adapters: How the microservice interacts with the outside world (e.g., REST controllers, message queues) and its own data store (e.g., repositories).
  • Frameworks & Drivers: External tools and technologies used (e.g., Spring Boot, database drivers).

Microservice Communication Layers

For other services or clients to interact with a microservice, they typically do so through its Interface Adapters layer.

This means a microservice exposes its functionality via:

  • REST API endpoints (e.g., a UserController).
  • Message queue consumers (e.g., processing an event).
  • GraphQL endpoints.

These adapters translate external requests into calls to the microservice's internal Use Cases.

Data Ownership in Microservices

A fundamental principle of microservices is that each service owns its data. This means:

  • No shared databases between services.
  • The data persistence mechanism is an internal detail of the microservice.

Clean Architecture's Repository Pattern fits perfectly here, abstracting the actual database implementation from the core Use Cases.

Dependency Rule: Microservice Edition

The Dependency Rule is crucial: inner circles must not depend on outer circles. This holds true within a microservice.

  • Your core Entities and Use Cases should know nothing about your web framework or database.
  • This keeps your business logic truly independent and testable.
  • It allows you to swap out frameworks or databases without affecting the core.

Defining Core Contracts

Let's look at a simple example for a 'User' microservice. Here, we define the core User entity and the interfaces for our UserRepository and CreateUserUseCase.

class User {
  private String id;
  private String name;
  private String email;

  public User(String id, String name, String email) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  public String getId() { return id; }
  public String getName() { return name; }
  public String getEmail() { return email; }
}

interface UserRepository {
  User save(User user);
  User findById(String id);
}

interface CreateUserUseCase {
  User createUser(String name, String email);
}

Implementing Core Logic

Now, we implement the CreateUserUseCase, called an Interactor. It takes a UserRepository (an outer layer interface) as a dependency, adhering to the Dependency Rule.

Run this code to see how the core logic can be tested independently!

import java.util.UUID;
import java.util.HashMap;
import java.util.Map;

class User {
  private String id;
  private String name;
  private String email;

  public User(String id, String name, String email) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  public String getId() { return id; }
  public String getName() { return name; }
  public String getEmail() { return email; }
}

interface UserRepository {
  User save(User user);
  User findById(String id);
}

interface CreateUserUseCase {
  User createUser(String name, String email);
}

class InMemoryUserRepository implements UserRepository {
  private final Map<String, User> users = new HashMap<>();

  @Override
  public User save(User user) {
    users.put(user.getId(), user);
    return user;
  }

  @Override
  public User findById(String id) {
    return users.get(id);
  }
}

class CreateUserInteractor implements CreateUserUseCase {
  private final UserRepository userRepository;

  public CreateUserInteractor(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  @Override
  public User createUser(String name, String email) {
    String id = UUID.randomUUID().toString();
    User newUser = new User(id, name, email);
    return userRepository.save(newUser);
  }
}

public class Main {
  public static void main(String[] args) {
    // This simulates the wiring and interaction in a microservice
    UserRepository repo = new InMemoryUserRepository();
    CreateUserUseCase useCase = new CreateUserInteractor(repo);

    User user1 = useCase.createUser("Alice", "alice@example.com");
    System.out.println("Created User: " + user1.getName());

    User foundUser = repo.findById(user1.getId());
    System.out.println("Found User Email: " + foundUser.getEmail());
  }
}

The API Adapter Role

In a real microservice, a UserController (part of the Interface Adapters layer) would receive an HTTP request, map it to a DTO, call the CreateUserUseCase, and then return an HTTP response.

This controller depends on the Use Case, but the Use Case doesn't depend on the controller.

Why This Approach Works

Applying Clean Architecture to microservices offers significant benefits:

  • High Cohesion: Each microservice's core logic is tightly focused.
  • Loose Coupling: Core logic is decoupled from frameworks, databases, and even other services.
  • Independent Deployment: Changes to the UI or database don't affect core business rules.
  • Enhanced Testability: Business logic can be unit-tested without needing a database or web server.
  • Maintainability: Easier to understand, modify, and extend over time.

Check Your Understanding

Why is applying Clean Architecture principles within individual microservices particularly beneficial?

Microservices & CA: Summary

In this lesson, we've seen how Clean Architecture provides a robust internal structure for individual microservices. By adhering to the Dependency Rule and separating concerns into layers, each microservice becomes:

  • Highly autonomous
  • Easily testable
  • Flexible and maintainable

This combination ensures that your microservice ecosystem remains agile and resilient.

常见问题解答

「微服务中的整洁架构」课时是免费的吗?

是的 — 「微服务中的整洁架构」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clean Architecture & Design Patterns in Practice 课程的其余内容,请升级到 CoddyKit PRO。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。

「微服务中的整洁架构」这节课中我会学到什么?

探索如何在各个微服务内部应用整洁架构原则,以保持内部一致性和自主性。 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Clean Architecture & Design Patterns in Practice 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Clean Architecture & Design Patterns in Practice 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「微服务中的整洁架构」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Clean Architecture & Design Patterns in Practice 课中编写并运行代码吗?

能。每节 Clean Architecture & Design Patterns in Practice 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理横切关注点
  2. 事件驱动的整洁架构
  3. 微服务中的整洁架构
  4. 整洁架构中的 CQRS
← 返回 Clean Architecture & Design Patterns in Practice