简体   繁体   中英

Communication between microservices, share entity or other hell

read many books about microservices, and dont find answer on my question.

Situation: Has service A Service A, has entity Cat

Has service B Service B need get Cat from service A add some new fields in class and send to service C.

Question: 1) i need share entity Cat between services? (I known is bad idea, because we get tight-coupling) 2) Create some data class in Service B for deserialise response to object (so.. we get code duplication) 3) maybe has good pattern to communicate?

IMHO it's not longer a Cat after service B enriched the data from service A. Since a micro-service should encapsulate a domain there should only be a single service that produces Cat s which in your example is service A. Service B is producing something else, maybe it's a CatHistory or CatWithToys but not a Cat . There is no code duplication here as service A is not aware of the fields that are enriched by service B, they are outside service A domain.

Short answer: #2

Long answer:

I was involved in a large microservices project where we, initially, shared code (DTOs) between projects to make comms easier. We learnt it's a painful approach. First, an update to the "api" library meant updating all the clients of the service, even if most of them didn't need the changes. Second, there was no way to ensure backwards compatibility. Even though we could update all services to the same version of the library and everything would pass, deployments don't typically work atomically like that in an always-on environment, so changes were inherently unsafe. Lastly, almost no clients need all the fields that come out of the API, yet they had an object with all the fields being used in their code.

Eventually, we did away with API projects. Really, it's the JSON produced by a service that's the API, not the DTO used to generate the JSON. Clients would have their own DTO containing just the fields they needed. Contract testing using Pact ensured that APIs didn't change in backwards-incompatible ways.

There is probably not just one right answer for this, as it will always be a bit opinionated.

I would prefer the loose coupling and go for a contract approach. As I guess that you are not interested in making SOAP based web services, my best guess is that you would be making some kind of RESTful services.

I would take a look at Swagger (or some similar technology) for making a "contract first" approach. That way you should be able to generate the API classes in the server (producer) and client (consumer) from the contract.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM