> For the complete documentation index, see [llms.txt](https://ldbmcs.gitbook.io/java/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ldbmcs.gitbook.io/java/wei-fu-wu/shi-da-wei-fu-wu-she-ji-mo-shi-he-yuan-ze.md).

# 十大微服务设计模式和原则

> 原文链接：[Top 10 Microservices Design Patterns and Principles - Examples](https://javarevisited.blogspot.com/2021/09/microservices-design-patterns-principles.html)

大家好，如果您正在使用微服务架构，并且想要了解不同的微服务设计模式和原则以更好地构建您的应用程序，那么您来对地方了。早些时候，我已经为Java开发人员分享了[最好的Java微服务课程](https://javarevisited.blogspot.com/2018/02/top-5-spring-microservices-courses-with-spring-boot-and-spring-cloud.html)和[书籍](https://javarevisited.blogspot.com/2018/07/top-5-books-to-learn-spring-boot-and-spring-cloud-java.html)。在本文中，我将继续分享基本的微服务设计原则和设计模式，包括事件源(Event Sourcing)、断路器(Circuit Breaker)、SAGA、CQRS、STRANGE和API Gateway等模式，以及Scailibity、灵活性、Resiliency等原则。

在你在开发企业应用程序时，最好使用微服务，而不是使用单一的体系结构。

虽然在某些情况下，您希望使用单一架构，如低延迟应用程序。但在大多数情况下，如果您希望在云中运行您的Java应用程序，微服务架构可能提供了更好的解决方案。

所以，让我们快速了解一下什么是微服务，以及微服务的示例和设计模式。

## 什么是微服务架构？

微服务架构构建在业务领域(business domain)上，它是小型独立服务的集合。在微服务架构中，所有组件都是自主性的，并围绕着单个业务功能（专用性）。

为什么我们需要考虑微服务架构替换单体架构？下面提到的四个主要概念描述了微服务架构相对于整体架构的重要性。

1.可见性高：MSA为您的服务提供更好的可见性。 2.灵活扩展：独立扩展各项服务以满足其支持的应用程序功能的需求。 3.轻松部署：支持持续集成和持续交付，缩短新功能的发布时间。 4.降低成本：降低设计、实施和维护IT服务的总体成本。

如果您是一个完全的初学者，并且想要了解更多地微服务架构，那么我强烈建议您先学习这些微服务架构的[课程](https://javarevisited.blogspot.com/2019/09/top-5-courses-to-learn-soa-service-oriented-architecture-microservices.html)。

## 微服务设计模式和原则

现在，您已经了解了什么是微服务架构，以及为什么需要考虑微服务架构来构建经得起时间考验并具有足够的可伸缩性来处理实际流量的应用程序，现在让我们来了解微服务的基本原理和设计模式，您可以使用它们来解决与微服务架构相关的常见问题。

让我们看看构建微服务架构所遵循的原则。

1. 可扩展性：Scalability
2. 灵活性：Flexibility
3. 独立自主：Independent and autonomous
4. 分权治理：Decentralized governance
5. 适应力：Resiliency（没太明白）
6. 故障隔离：Failure isolation
7. 通过DevOps持续交付：Continuous delivery through the DevOps

在遵循上述原则的同时，开发人员可能会遇到一些其他陷阱，为了避免这种情况，我们可以在微服务架构中使用设计模式。

在本文中，我们将讨论下面提到的10种主要的设计模式。

1. Database per Microservice
2. Event Sourcing
3. CQRS
4. Saga
5. BFF
6. API Gateway
7. Strangler
8. Circuit Breaker
9. Externalized Configuration
10. Consumer-Driven Contract Tracing\*\*

因此，首先从每个微服务的数据库设计模式开始。

![dWmZhZ](https://image.ldbmcs.com/dWmZhZ.jpg)

### 1. 微服务数据库

### 2. 事件源模式：Event Sourcing Pattern

### 3. CQRS

### 4. SAGA

### 5. BFF

### 6. API Gateway

### 7. Strangler

<https://iambowen.gitbooks.io/cloud-design-pattern/content/patterns/strangler.html>

### 8. Circuit Breaker Pattern

### 9. Externalized Configuration

### 10. Consumer-Driven Contract Tracing
