问题
For the sake of question, let's say i have 2 microservices.
- Identity management
- Accounting
I know that each microservice should not be tightly coupled and it should have it's own database.
Let's say that accounting has invoices and each invoice has issuing agent. Agent from accounting also exists as User in Identity microservice.
If i understood well, data from identity management (users), should be copied to accounting (agents), and should copy only data which are needed for that bounded context (first and last name), so the invoice can have proper issuingAgentId
.
Is this correct way to keep data consistent and shared between contexts? Each time when user is created in identity microservice, event "UserCreated" will be published and accounting or any other service interested in this event should listen and process it by adding corresponding agent? Same goes for updating user information.
回答1:
This is one way to handle it yes and usually the preferred method. You keep a cache locally in your service that holds copies of the data from another service. In an event-driven system, this would involve listening to events of interest and using them to update your local cache. The cache could be in-memory, or persisted. An example for your use case would be when raising an invoice, the Accounting context would look in it's local cache for a user/agentid before creating the Invoice.
Other options:
Shared database
I know it is frowned upon (for good reason) but you can always share a database schema. For example, the Identity context can write to a user table and the Accounting context can read from it when it needs an AgentId to put in an invoice. The trade-off is you are coupling at the database level, and introducing a single point of failure.
RPC
You can make a RPC call to another service when you need information. In your example, the Accounting context would call the Identity Management context for the AgentId/User information before raising an invoice. Trade-off with this approach is again a coupling to the other service. What do you do when it is not available? You cannot raise an Invoice.
Reporting domain
Another option is to have a completely separate service that listens for data from other services and maintains view models for UIs. This would keep your other services ignorant of other service's concerns. When using an event-driven system, you'd be listening for events form other services that allow you to build a view model for the UI. This is usually a good option if all you are doing is viewing the data
来源:https://stackoverflow.com/questions/38858550/microservices-and-bounded-contexts