How To Make Relations Between Two Entities From Different Microservices In Spring Boot?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 19:17:21

问题


I am trying to make a simple Spring Boot web app using Microservice Architecture.

I have two microservices with entities as defined below:

Microservice 1 :

@Entity
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private String Content;

}

and

Microservice 2 :

@Entity
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
}

Now I want to have a Many To Many relation between these two entities in my Gateway.

I had tried to use feign client as below:

Gateway :

@FeignClient(value = "article-service")
public interface ArticleClient {

    @RequestMapping(value = "/articles/", method = RequestMethod.GET)
    Set<Article> getArticleById(@RequestParam("id") Long id);

}

@FeignClient(value = "tag-service")
public interface TagClient {

    @RequestMapping(value = "/tags/", method = RequestMethod.GET)
    Tag getTagById(@RequestParam("id") Long id);

}

And defined Article and Tag entities in my Gateway like this:

Gateway :

@JsonIgnoreProperties(ignoreUnknown = true)
public class Entry {

    private Long id;

    private String title;

    private String Content;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "article_tag",
        joinColumns = @JoinColumn(name = "article_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id",
                referencedColumnName = "id"))
    private Set<Tag> tags;
}


@JsonIgnoreProperties(ignoreUnknown = true)
public class Tag {
    private Long id;

    private String title;

    @ManyToMany(mappedBy = "tags")
    private Set<Article> articles;
}

I have a table named article_tag in my database (Postgres).

Now how can I define my repositories in the Gateway? How to write getArticlesByTagId() or getTagsByArticleId() functions? I did whatever I could to make this relation work but I think they are not going to get along with each other :)


回答1:


It just impossible what you want, you have 2 differents applications, each entity has its own life in its context. Imagine the case where a service is down, how would you do?

If a microservice is closely linked to another one, you should revise your architecture.

To solve this kind of problem, add an identifier in each entity to identify which Tag belongs to an Entry and vice-versa, you can request your data using those identifiers.



来源:https://stackoverflow.com/questions/46193708/how-to-make-relations-between-two-entities-from-different-microservices-in-sprin

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