GraphQL 入门: Apollo Client 查询(Batching)合并
Query batching 就是在单个请求中包含多个查询的技术,它有几个极其显著的优点:
使用假设一个场景,多个UI组件都是用了GraphQL查询从服务器获取数据. 下面两个查询可能是由两个不同的UI组件生产的,会产生两次客户端和服务器之间的数据往返. client.query({ query: query1 }) client.query({ query: query2 }) 在Apollo Client中,查询批处理默认是关闭的. 要打开查询批处理,需要在初始化 Apollo Client的时候打开 const client = new ApolloClient({ // ... 其他选项 shouldBatch: true }); 时间间隔时间间隔标识在一个特定的时间段内(比如100ms),如果客户端产生了多个查询,那么Apollo Client会自动把多个查询合并为一个.
查询合并查询合并是由 query firstQuery { author { firstName lastName } } query secondQuery { fortuneCookie } 我们想象一下合并的问题,假设上面的两个查询会合并成如下的样子: query ___composed { author { firstName lastName } fortuneCookie } 但是,上述合并后的查询有几个问题
网络层的查询合并网络层的查询合并,只需要用 import ApolloClient,{ createBatchingNetworkInterface } from 'apollo-client'; const batchingNetworkInterface = createBatchingNetworkInterface({ uri: 'localhost:3000',batchInterval: 100,opts: { // Options to pass along to `fetch` } }); const apolloClient = new ApolloClient({ networkInterface: batchingNetworkInterface,}); // These two queries happen in quick succession,possibly in totally different // places within your UI. apolloClient.query({ query: firstQuery }); apolloClient.query({ query: secondQuery }); 结语上述Batching查询是正对HTTP这种无状态协议的,目的是为了减少重复建立新的TCP连接消耗的时间,如果采用Websocket这种有状态协议,就没有必要在使用 参考资料
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |