Join table between Different Microservices

佐手、 提交于 2020-01-01 08:42:20

问题


I am still trying to make sense of micro service architecture.

The idea to separate different application (include the database) excites me. But I am still confused if there are two micro-services e.g. Product and User. both product and user own table product and user respectively in their database. According to best practice in micro service, we only can access the database from the service.

The problem is, let us suppose we have product table that has user_id column. We want to do search product which also return the name of the user who create the product. This requires join between product table in product micro-service and user table in user micro-service. How do you handle this?


回答1:


You'll have to make a call to each microservice and do the join manually or pass in the relevant user ids to each service.

UserMicroservice:

SELECT * FROM Users WHERE some condition is true

Get list of Users back including their ids.

ProductMicroserivce:

SELECT * FROM Products WHERE some condition is true AND userId IN (.........)

So users and products can still be in two different databases, the products will just need to have the concept of a userId.

The reverse can also be done, ProductMicroserivce:

SELECT * FROM Products WHERE some condition is true

Extract all the UserIds then call the UserMicroservice:

SELECT * FROM Users WHERE some condition is true AND id IN (.........)



回答2:


While I think there's nothing wrong with doing it the way Jan suggested I would like to add that the difference microservices should add to your system is of a different nature.

The above segregation of services is what we've seen a lot in the SOA world and it turned out to become too complex very quickly without offering much value.

If you, and I understand it's just an example, have the need to query user connected to products - why split the service up? You end up designing a service per db-entity instead of looking at what the requirements are for a given, what seems to me bounded context.

-Lars




回答3:


Best answer to such scenarios is CQRS. Maintain the materialized views of User and product relationship. Meterialized views could be anything which provides low latency in reading like NoSql DBs. Whenever Command updates User or Product by their microservices,the corresponding events should get generated and gets captured by other service managing this materializedView. This service will be used to fetch the query you are interested in. Always keep in mind,Microservices architecture believes in Eventual Consistency which definitely is not a bad thing :) .Hope this answers your question.



来源:https://stackoverflow.com/questions/44085454/join-table-between-different-microservices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!