我正在努力解决我的Node.js应用程序中的内存泄漏问题,而这段代码似乎确实泄漏了
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
const data = await client.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
return res.json(data);
} catch (err) {
return next('error');
}
});
};因此,ApolloClient客户端每次都会重新创建,因为它是全局的。在路线内定义它更好吗?那会不会导致性能问题呢?
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
let httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
let client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
const data = await client.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
httpLink = null
client = null
return res.json(data);
} catch (err) {
return next('error');
}
});
};发布于 2022-02-15 14:49:48
由于许多原因,创建一个ApolloClient实例并重用它更好。
考虑拥有20个或更多(N)端点/中间件,需要访问存储在数据库中的一些数据。为每个实例创建一个ApolloClient实例意味着有N个实例。这不是表演性的,违反并违反了“不要重复自己”的编码规则。
另一方面,创建一个实例并在整个应用程序中使用它是非常方便的。考虑一下这个例子:
const ApolloClient = require('apollo-client').ApolloClient;
const fetch = require('node-fetch');
const createHttpLink = require('apollo-link-http').createHttpLink;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const httpLink = createHttpLink({
uri: 'http://xxxxxx',
fetch: fetch
});
// instantiating
module.exports = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});A单元:
const dbClient = require('./db_client')
module.exports = (app) => {
app.post('/graphql', async (req, res, next) => {
try {
const data = await dbClient.query({
query: 'xxxxxxx',
variables: 'xxxxxxx'
});
return res.json(data);
} catch (err) {
return next('error');
}
});
};另一个模块:
const dbClient = require('./db_client')
...另一个模块:
const dbClient = require('./db_client')
...可以看到,只要有一个实例,我们就可以实现一个更健壮和性能更好的应用程序。
https://stackoverflow.com/questions/71067853
复制相似问题