gpt4 book ai didi

node.js - Graphql server + NodeJS,用 Redis 缓存数据

转载 作者:可可西里 更新时间:2023-11-01 10:53:18 24 4
gpt4 key购买 nike

我想知道如何改善从连接 graphql 到 api 的响应时间。我决定使用 Redis。我不知道我应该怎么做。

我已经构建了我的 graphql 服务器:

import express from 'express';
import {
graphqlExpress,
graphiqlExpress,
} from 'graphql-server-express';
import bodyParser from 'body-parser';

import { schema } from './src/schema';
import cors from 'cors';

import redis from 'redis';

const PORT = 4000;
const server = express();

const client = redis.createClient();

client.on('error', function (err) {
console.log('error' + err)
});

server.use('*', cors({ origin: 'http://localhost:3000' }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
schema, context: { client }
}));


server.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql'
}));



server.listen(PORT, () =>
console.log(`GraphQL Server is now running on http://localhost:${PORT}`)
);

我这里已经导入了redis。我的 graphql 服务器通过 cors 连接到首页,所以我可以从 api 渲染字符串。在解析器中,我通过 Node.js 连接到 api(如果需要,我会添加它。),并且我在这里有一些自定义解析器。 api 的响应时间(也影响页面上的渲染)太慢了——大约 10~15 秒。

最佳答案

我建议查看 Apollo Engine更好地了解 GraphQL 的工作原理,并使使用附加组件(如 Redis 缓存)变得更加容易。一旦你让 Apollo Engine 开始工作,你就可以使用 apollo-server-redis-cache创建缓存。

如果您的请求在没有缓存的情况下需要 10-15 秒,我也希望先优化它们,然后再将 Redis 放在它们前面。

关于node.js - Graphql server + NodeJS,用 Redis 缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50579276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com