【问题标题】:How To Make Relations Between Two Entities From Different Microservices In Spring Boot?如何在 Spring Boot 中建立来自不同微服务的两个实体之间的关系?
【发布时间】:2018-02-21 22:31:59
【问题描述】:

我正在尝试使用 微服务架构 制作一个简单的 Spring Boot Web 应用。

我有两个微服务,其实体定义如下:

Microservice 1 :

@Entity
public class Article {

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

    private String title;

    private String Content;

}

Microservice 2 :

@Entity
public class Tag {

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

    private String title;
}

现在我想在我的网关中的这两个实体之间建立一个多对多关系。

我曾尝试如下使用 feign 客户端:

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);

}

并在我的 Gateway 中定义了 ArticleTag 实体,如下所示:

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;
}

我的数据库 (Postgres) 中有一个名为 article_tag 的表。

现在如何在 网关 中定义我的存储库? 如何编写 getArticlesByTagId() 或 getTagsByArticleId() 函数? 我尽我所能使这种关系发挥作用,但我认为他们不会相处融洽:)

【问题讨论】:

  • 据我所知,您没有定义关系(因为您没有任何关系)。取而代之的是,您的网关将仅包含 article_tag 的实体,并且您必须自己映射 article_idtag_id 字段。如果要检索特定标签的文章,请查找 article_ids 并将它们传递给文章微服务(REST 调用?)以检索完整的文章。
  • 您的问题找到合适的解决方案了吗?

标签: spring-boot spring-data spring-data-jpa microservices


【解决方案1】:

你想要什么是不可能的,你有 2 个不同的应用程序,每个实体在其上下文中都有自己的生命。想象一下服务宕机的情况,你会怎么做?

如果一个微服务与另一个微服务紧密相连,您应该修改您的架构。

要解决此类问题,请在每个实体中添加一个标识符以识别哪个标签属于某个条目,反之亦然,您可以使用这些标识符请求您的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多