【问题标题】:Frequent requests with React and Express GraphQL使用 React 和 Express GraphQL 的频繁请求
【发布时间】:2019-07-17 22:25:25
【问题描述】:

我正在使用 React 和 Express GraphQL 以及 MariaDB 数据库创建一个网站。但是,我遇到了频繁请求/订阅 GraphQL API 的问题。

在有问题的页面在 React 中加载后,我称之为:

componentDidMount() {
    this.setState({
        waitingTimer: setInterval(this.queryWaiting.bind(this), 1000)
    });
}

其中queryWaiting 是一个函数,它在localhost:3000/graphql 向我的GraphQL 服务器执行fetch 请求。该 URL 本身是在我的 setupProxy.js 文件中定义的代理,它代理来自 localhost:4000/graphql 的 URL,因此我不需要使用 CORS。

值得注意的是,我在componentWillUnmount中也有clearInterval这个waitingTimer

在我只是用node 运行的 GraphQL 服务器文件中,我这样设置我的服务器:

var app = express();

app.use("/graphql", graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
}));
app.listen(4000);

schema 是有效架构,root 是我的根解析器。

我重复调用的 API 查询称为 getWaitingCount,它的行为如下:

getWaitingCount: () => {
    return new Promise((resolve, reject) => {
        var currentTime = Date.now() / 1000;

        if (cachedWaitingTime + cachedWaitingInterval > currentTime) {
            return cachedWaiting;
        }

        connection.query("SELECT COUNT(*) FROM profiles WHERE isWaiting=1;", function (error, results, fields) {
            if (error)
                reject(error);
            else {
                // Update cache values
                cachedWaiting = results[0]["COUNT(*)"];
                cachedWaitingTime = Date.now() / 1000;
                resolve(cachedWaiting);
            }
        });
    });
}

我已经实现了一些缓存来减少服务器负载。缓存变量在别处定义。

我遇到的问题是,在 2-10 秒之后,来自我的 React 应用程序对这个特定查询的 POST 请求停止得到解决,我必须重新加载页面才能让它们再次开始被接受。奇怪的是,其他请求都能顺利通过。

我尝试了各种解决方案,比如切换到使用我目前使用的代理方法,我也考虑过在 Express 代码中内置防 DDOS 机制的可能性,但我可以'找不到任何证据。

非常感谢您对此问题的任何帮助。

【问题讨论】:

  • 为什么不直接使用订阅?
  • @dan-klasson 我不知道,我对 React 很陌生。您有可以帮助我入门的链接吗?
  • 与 GraphQL 相关。查看适用于您的客户端和服务器的文档
  • 谢谢。我找到了一些关于如何设置订阅的文档。但我真的需要吗?使用常规客户端更新请求是否有任何巨大的缺点?
  • 那么您将不得不每隔 X 秒不断地轮询一次,不是吗?

标签: node.js reactjs express asynchronous graphql


【解决方案1】:

事实证明,最好的解决方案是输入并解释您的代码 :)

这段代码:

if (cachedWaitingTime + cachedWaitingInterval > currentTime) {
    return cachedWaiting;
}

在一个承诺中,所以真的应该这样做:

resolve(cachedWaiting);

而不是返回它。

就是这样。我现在正在踢自己。

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2022-01-13
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多