在Spring Boot中如何通过不同的微服务在两个实体之间建立关系? [英] How To Make Relations Between Two Entities From Different Microservices In Spring Boot?
问题描述
我正在尝试使用 Microservice Architecture 创建一个简单的 Spring Boot 网络应用.
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;
}
和
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);
}
并在我的网关中定义 Article 和 Tag 实体,如下所示:
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;
}
我的数据库( Postgres )中有一个名为 article_tag 的表.
I have a table named article_tag in my database (Postgres).
现在如何在网关中定义我的存储库? 如何编写getArticlesByTagId()或getTagsByArticleId()函数? 我尽我所能使这种关系正常运转,但我认为他们不会相处的:)
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 :)
推荐答案
您想要的东西根本就不可能,您有2个不同的应用程序,每个实体在其上下文中都有自己的生命.想象一下服务中断的情况,您将如何处理?
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.
这篇关于在Spring Boot中如何通过不同的微服务在两个实体之间建立关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!