有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在微服务体系结构中,为什么他们说共享REST客户端库不好?

我们有15个使用JavaSpring构建的服务,它们使用REST相互通信

每次向池中添加新服务时,我们都从头开始创建所有代码,包括将与其他服务对话的rest客户端代码和用于映射所请求资源的POJO类

我们最终将其他服务的源代码复制并粘贴到新服务中

我认为最好将所有这些POJO和rest客户机代码放在一个库中,以便所有服务使用它,这将为我们节省大量的编码工作,但“他们”说我们不应该用微服务这样做

那为什么呢? 我们一次又一次地复制和粘贴完全相同的代码,我看不出有什么区别


共 (3) 个答案

  1. # 1 楼答案

    我会说“他们”错了,而你是对的。复制和粘贴客户端代码有几个问题:

    • 如果你的客户端代码中有一个bug,你必须在15个地方修复这个bug,而不是只修复一个
    • 这会减慢速度。现在,您必须测试和维护同一代码的多个副本
    • 创建客户端库并通过标准依赖关系管理器(如maven)分发它们是常见的做法。亚马逊和几乎所有其他公司都这样做

    总之,你是对的,亚马逊是支持你观点的最有力的例子。他们完全按照您对其web服务的建议行事,可以说他们是微服务领域最大、最强大的参与者

    另一个答案也是为了解决紧耦合的问题。好的api是向后兼容的,因此对api的更改不需要升级所有客户端,即使它们使用相同的客户端库

  2. # 2 楼答案

    我同意关于耦合的说法。我被迫在重用场景中使用一组特定的Maven依赖项,不允许任何人更新它们。结果是,创建新服务变得更加困难,因为框架和文档都过时了

    另一方面,代码重用可以节省大量的时间和金钱,尤其是在服务中使用的样板代码,如果它构造良好并且有适当的测试

    我认为这里有一个中间立场,涉及版本控制和一定量的日常维护

  3. # 3 楼答案

    主要问题是耦合Sam Newman, author of Building Microservices说得很好:

    In general, I dislike code reuse across services, as it can easily become a source of coupling. Having a shared library for serialisation and de-serialisation of domain objects is a classic example of where the driver to code reuse can be a problem. What happens when you add a field to a domain entity? Do you have to ask all your clients to upgrade the version of the shared library they have? If you do, you loose independent deployability, the most important principle of microservices (IMHO).

    Code duplication does have some obvious downsides. But I think those downsides are better than the downsides of using shared code that ends up coupling services. If using shared libraries, be careful to monitor their use, and if you are unsure on whether or not they are a good idea, I'd strongly suggest you lean towards code duplication between services instead.

    https://samnewman.io/blog/2015/06/22/answering-questions-from-devoxx-on-microservices/