current position:Home>Chapter 5 business logic design in micro service architecture

Chapter 5 business logic design in micro service architecture

2022-01-27 04:02:26 Polychlorinated cyclohexane


This is a book about microservice architecture design , Here are my study notes . First, some symbols are explained :

() To supplement , Usually the content in books ;
[] The symbol is the author's note ;

1. Business logic organization model

There are two main patterns of organizational business logic : Process oriented transaction script pattern and object-oriented domain modeling pattern .

1.1 A typical service architecture

The business logic is surrounded by inbound and outbound adapters .

  • Inbound adapter : Process requests from clients and invoke business logic ;
  • Outbound adapter : Called by business logic , Then they call other services and external applications ;

Order Service With hexagonal architecture

Order Service With hexagonal architecture
This service consists of business logic and the following adapters :

  • REST API adapter: Inbound adapter , Realization REST API, these API Will call the business logic ;
  • OrderCommandHandlers: Inbound adapter , It accepts outbound adapters from the message broker , And call the business logic ;
  • Database Adapter: Outbound adapter called by business logic to access the database ;
  • Domain Event Publishing Adapter: Publish events to the outbound adapter of the message broker ;

1.2 Design business logic using transaction script pattern

Transaction script : Organize business logic into a collection of process oriented transaction scripts , Each type of request has a script .

 Design business logic using transaction script pattern

  • Classes that implement behavior are separate from classes that store state ;
  • Scripts are usually in service classes ;
  • Each service has a method for request or system operation ; This method implements the requested business logic ;

1.3 Design business logic using domain model pattern

Domain model : Organize business logic into an object model composed of classes with state and behavior .

 Design business logic using domain model pattern

  • The service method is usually simple ( Because service methods almost always call persistent domain objects , These objects contain a lot of business logic );
    • Such as :Order Classes have states and methods , The state is private , It can only be accessed indirectly through its methods ;
  • Easy to understand 、 maintain 、 Testing and extension ;

1.4 About Domain Driven Design

Domain-driven design (DDD) It's an improvement on object-oriented design , Is a way to develop complex business logic . The basic elements are as follows :

  • Entity (entity): With persistence ID The object of . Two entities with the same attribute value are still different objects ;
  • The value object (value object): An object that is a collection of values . Two value objects with the same attribute value can be used interchangeably ;
  • factory (factory): An object or method responsible for implementing object creation logic , The logic is too complex , Cannot be done directly by the constructor of a class . It can also hide instantiated concrete classes . Factory methods can generally be implemented as static methods of classes ;
  • The repository (repository): Objects used to access persistent entities , The repository also encapsulates the underlying mechanism for accessing the database ;
  • service (service): Implement business logic objects that do not belong to entity or value objects ;

2. Design domain model using aggregation pattern

The traditional domain model lacks a clear boundary for each business object ,DDD Aggregation aims to solve this problem .

2.1 Aggregation has clear boundaries

Aggregation mode : Organize domain models into aggregated collections , Each aggregation is a graph of a set of objects that can be processed as a unit .

Order Aggregation and its boundaries

Order  Aggregation and its boundaries

  • Aggregation represents a consistent boundary ;
    • Updating the entire aggregation can solve the consistency problem ;
  • Identifying aggregation is the key ;
    • In the field of drive design , The key part of the design domain model is to identify aggregations , And their boundaries and roots ;

2.2 Aggregation rules

Aggregation rules ensure that aggregation is a self-contained unit that can enforce various invariant constraints .

  • Rule one : Reference only aggregate roots ;
    • The aggregate root is the only part of the aggregate that can be referenced by an external class ; Clients can only update aggregations by calling methods on the aggregate root ;
    • Such as : The service uses the repository to load the aggregation from the database and get the reference of the aggregation root ;
  • Rule 2 : References between aggregations must use primary keys ;
    • Such as :Order Use consumerId Quote it Consumer Instead of quoting Consumer object ;
  • Rule three : In a transaction , Only one aggregate can be created or updated ;
    • This constraint ensures that the scope of a single transaction does not exceed the boundaries of the service ; It also meets most NoSQL Restricted transaction model of database ;
    • This rule complicates the operation of creating or updating multiple aggregations , But it can go through Saga solve ;

 A transaction can only create or update a single aggregate

2.3 Particle size of polymerization

  • Since each aggregate update is serialized , Therefore, finer grained aggregation increases the number of requests that applications can process at the same time , To improve scalability ;
  • On the other hand , Because aggregation is the scope of a transaction , Therefore, it may be necessary to define larger aggregations so that specific aggregate update operations meet the atomicity of transactions ;
  • therefore , When developing domain models , The key decision that must be made is to determine the size of each aggregation ;

2.4 Use aggregation to design business

  • In a typical microservice , Most business logic consists of aggregations ; The rest of the business logic exists with domain services and Saga in ;
  • Saga Sequence local transactions , To ensure data consistency ;
  • Service is the entrance of business logic , Called by the inbound adapter ;
  • The service uses the repository to retrieve aggregations from the database or save aggregations to the database ;
  • Each repository is implemented by an outbound adapter that accesses the database ;

2.5 Order Service Business logic based on aggregation design

Order Service Business logic based on aggregation design

  • The business logic consists of Order polymerization 、OrderService Service 、OrderRepository And one or more Saga form ;
  • OrderService call OrderRepository To save and load Order;
  • For simple requests that can be processed within the service , Service update directly Order polymerization ;
  • If the update request spans multiple services ,OrderService Will create a Saga;

3. Publish domain events

Field events : Aggregation is created when , Or release domain events when other major changes occur .

3.1 Application scenarios of domain events

  • Use orchestration based Saga Maintain data consistency between services 【 Chapter four 】;
  • Notify the service that maintains copies of the data , The source data has changed ; This method is called command query responsibility isolation (CQRS)【 Chapter vii. 】;
  • adopt Webhook Or message broker notifies different applications , To trigger the next business process ;
  • Notify different components of the same application in order ;
  • Send SMS or email notification to users , Tell them to ship the order 、 Flight delays and other news ;
  • Monitor domain events to verify that the application is running properly ;
  • Analyze domain events , Modeling user behavior ;

3.2 Characteristics of domain events

  • When naming domain events , Often choose the past participle of the verb ;
  • Each attribute of a domain event is an original value or value object ;
    • Such as :OrderCreated The event class has orderId attribute ;
  • Domain events usually have metadata , Such as events ID And time stamp ;
  • Metadata can be part of an event object , May be defined in a superclass ;

OrderCreated Events are an example of domain events

  • DomainEvent An interface is an identification interface , Used to identify a class as a domain event ;
  • OrderDomainEvent yes Order The identification interface of the aggregated published event ( Such as OrderCreated);
  • DomainEventEnvelope Is a class that contains event metadata and event objects ;

3.3 Event enhancement

When OrderCreated When the receiver of the event needs the details of the order , One way is from Order Service Retrieve this information from , Let the event receiver query the aggregation service , The disadvantage is the overhead of service requests ;

Another solution is event enhancement :

  • The event contains the information needed by the receiver ;
  • shortcoming : It may reduce the stability of domain events ; Whenever the needs of the recipient change , Event classes may need to be changed ; May reduce maintainability ;

 Insert picture description here

3.4 Identify domain events

You can use the event storm method , The result is an event centric domain model , It consists of aggregation and events ; It includes the following three steps :

  1. Brainstorming : Ask domain experts to brainstorm on domain events ;
  2. Identify event triggers : Ask domain experts to determine the trigger for each event ( Such as : The user action 、 An external system 、 Another domain event 、 The passage of time, etc );
  3. Identify aggregations : Ask domain experts to identify those aggregations that use commands and issue corresponding events ;

3.5 Generate domain events

In aggregating and invoking its services ( Or class ) Assign responsibilities between .

  • A service can use dependency injection to get the information about messaging API References to , So it's easy to post events ;
  • As long as the state changes , Aggregation generates events and returns them to the service ;
  • Aggregation can return events to services by :

Include a list of events in the return value of the aggregation method

The service calls the aggregation root method , And then release the event ;

The aggregation root accumulates and saves events in an internal field : The service then retrieves these events and publishes them ;

3.6 Publish domain events

The service must use transactional messages to publish events , To ensure that domain events are published as part of the aggregated transactions in the update database ;

Eventuate Tram Framework provide DomainEventPublisher Interface

DomainEventPublisher Interface
Let the service realize AbstractAggregateDomainEventPublisher Subclasses of : It provides a type safe interface for publishing domain events ;

AbstractAggregateDomainEventPublishe Interface

 Realization AbstractAggregateDomainEventPublisher Subclass

3.7 Consumer Events

Domain events are higher-level events used by the receiver API, Such as :Eventuate Tram Framework of the DomainEventDispatcher etc. . It can schedule domain events to appropriate handler methods .

  • Whenever the restaurant menu is updated ,KitchenServiceEventConsumer Will subscribe Restaurant Service Release events ;
  • It is responsible for making Kitchen Service Keep copies of your data up to date ;

4. Kichen Service Business logic of

The main function of the service is to realize the order management function of the restaurant . The two main aggregations are Restaurant and Ticket;

4.1 Kichen Service The design of the

Kitchen Service The design of the

  • Two aggregate :
    • Restaurant: Know the menu and business events of the restaurant , And can verify the order ;
    • Ticket: After the work order is cooked, the meal deliverer is responsible for delivering ;
  • The core business :
    • KitchenService: Business entrance , Defines how to create and update Restaurant And Ticket The way of aggregation ;
    • TicketRepository: Defines persistence Tickets Methods ;
    • RestaurantRepository: Defines persistence Restaurants Methods ;
  • Three inbound adapters :
    • REST API: Restaurant staff invoke these through their user interface REST API;
    • KitchenServiceCommandHandler: from Saga The call is based on asynchronous requests / Responsive API; It calls KitchenService To create and update Ticket;
    • KitchenServiceEventConsumer: subscribe Restaurant Service Published Events ; It calls KitchenService To create and update Restaurant polymerization ;
  • Two outbound adapters :
    • DB Adapter: Realization TicketRepository and RestaurantRepository Interface and access the database ;
    • DomainEventPublishingAdapter: Realization DomainEventPublisher Interface and publish Ticket Field events ;

4.2 Ticket Class structure

This kind of use JPA persist , And map to TICKETS surface .

Ticket Class structure

4.3 Ticket The act of aggregation

Ticket Some of the ways

  • create(): establish Ticket The factory method of ;
  • accept(): The restaurant has received an order ;
  • preparing(): The restaurant has begun to prepare orders , It means that the order can no longer be changed or cancelled ;
  • readyForPickup(): Orders can be dispatched ;

4.4 KitchenService Service areas

KitchenService Invoked by the service inbound adapter ; Defines various methods for changing order status ( Such as accept()、reject()、preparing() etc. ); Each method loads the specified aggregate , Call the corresponding method on the aggregation root , And publish domain events ; as follows accept() Method :

accept() Method update Ticket
accept() Two parameters of method

  • orderId: To accept an order ID;
  • readyBy: The estimated time when the order can be dispatched ;

4.5 KitchenServiceCommandHandler class

KitchenServiceCommandHandler Class is an adapter , Responsible for handling Order Service The realization of all kinds of Saga Send a command message ;

KitchenServiceCommandHandler class

5. Order Service Business logic of

5.1 Order Service The design of the

Order Service The design of the

  • Several inbound adapters :
    • REST API: For consumers to invoke using the user interface REST API; It calls OrderService To create and update Order;
    • OrderEventConsumer: subscribe Restaurant Service Published activities ; It calls OrderService To create and update its Restaurant copy ;
    • OrderCommandHandlers: from Saga The call is based on asynchronous requests / Corresponding API; It calls OrderService To update Order;
    • SagaReplyAdapter: subscribe Saga Reply to the channel and call Saga;
  • Some outbound adapters :
    • DB Adapter: Realization OrderRepository Interface and access Order Service The database of ;
    • DomainEventPublishingAdapter: Realization DomainEventPublisher Interface and publish Order Field events ;
    • OutboundCommandMessageAdapter: Realization CommandPublisher Interface and report to Saga Participants send imperative messages ;

5.2 Order Aggregate structure

Order Class is Order The roots of aggregation ;Order Aggregation also includes value objects , Such as :OrderLineItem、DeliveryInfo and PaymentInfo.

Order Design of aggregation
Order Class and its fields

Such use JPA Persistence , And map to ORDERS surface .

Order Class and its fields

5.3 Order Aggregate state machine

In order to create or update orders ,Order Service You have to use Saga Collaborate with other services .

Order Aggregate state machine
establish Order Invoked in procedure Order Method

 establish Order Method of calling in process

to update Order Method to call

 to update Order Method to call

5.4 OrderService class

This class defines the for creating and updating Orders Methods .

OrderService class

6. Similarities and differences of business logic between microservices and single applications

  • The same thing
    • By services such as 、JPA Supported entity classes and repositories are composed of such classes ;
  • Difference
    • Domain models are organized into a set of DDD polymerization , Various constraints can be imposed on it ;
    • Different from the traditional object model , References between classes in different aggregations are based on primary keys rather than object references ;
    • A transaction can only create or update a single aggregate ; Aggregation publishes domain events when the state changes ;
    • Services usually use Saga To maintain data consistency between multiple services ;

7. Summary of this chapter

  • Transaction script pattern is usually a good way to implement simple business . But when implementing complex business logic , You should consider using an object-oriented domain model pattern ;
  • A good way to design the business logic of a service is to use DDD polymerization .DDD Aggregation is useful , Because they modularize the domain model , Eliminates direct references to objects between services , And make sure that each ACID All transactions are within the service ;
  • Domain events should be published when aggregations are created or updated . Domain events have a wide range of uses . The first 4 Chapter discusses how to implement collaborative Saga. The first 7 This chapter discusses how to use domain events to update data copied from other services . Subscribers to domain events can also notify users and other applications , And will WebSocket Publish the message to the user's browser .


New people make , If there is a mistake , Welcome to point out , Be deeply grateful !
Welcome to the official account , Will share something more everyday !
If you want to reprint , Please mark the source !

copyright notice
author[Polychlorinated cyclohexane],Please bring the original link to reprint, thank you.

Random recommended