如何从微服务中调用另一个微服务?

时间:2020-01-09 17:33:55

标签: apollo apollo-client apollo-server

这听起来可能有点奇怪,但是我面临的情况是我拥有一个微服务,该微服务组合了一些定价逻辑,但为此,它需要另一微服务提供的大量信息。

我相信我有两个选择:(1)从数据库中获取我需要的所有数据,而忽略在另一个微服务中完成的GraphQL工作,或者(2)以某种方式从我的内部命中该另一个微服务当前服务并获取我需要的数据。

某人将如何完成(2)?

我不知道如何在不造成混乱的情况下完成任务。

我想把定价微服务变成一个小型客户是可行的,但是我不确定这是否是一个坏习惯。

1 个答案:

答案 0 :(得分:1)

经过深思熟虑并阅读了here的答案后,我决定通过使用apollo-client将微服务转变为微型客户端。

简而言之,我有这样的东西:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';

// Instantiate required constructor fields
const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'http://localhost:3000/graphql',
});

const client = new ApolloClient({
  // Provide required constructor fields
  cache: cache,
  link: link,
});

export default client;

该HttpLink是联合模式,因此我可以从我的解析器或其他任何地方调用它:

const query = gql`
        query {
          something(uid: "${uid}") {
            field1
            field2
            field3
            anotherThing {
              field1
              field2
            }
          }
        }
      `;
const response = await dataSources.client.query({query});