简体   繁体   中英

Graphql server + NodeJS, store data in cache with Redis

I'd like to know how I can improve the response time from connecting graphql to api. I have decided to use Redis. I don't know how exactly should I do it.

I have built my graphql server:

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}`)
);

I have already imported redis here. My graphql server is connected to front page by cors, so I can render strings from api. In resolver I'm connecting to api by Node.js (if necessary I'll add it.), and I have some custom resolvers here. The response time from api (also affect rendering on page) is too slow- around 10~15s.

I recommend checking out Apollo Engine to get a better insight into how GraphQL is working, and make it easier to use add-ons such as a Redis cache. Once you get Apollo Engine working, you can use apollo-server-redis-cache to create a cache.

If your requests are taking 10-15s without a cache, I would also look to optimise them first before throwing Redis in front of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM