【发布时间】:2022-01-26 00:10:24
【问题描述】:
我已经使用 Nodejs 和 express 设置了一个在我的服务器上运行的 API。我是一个真正的新手。我用我当前的代码发现数据没有被缓存,并且每次页面请求它时都需要下载到我的应用程序,这很慢。 我知道 Redis 会缓存,但我不确定如何在我的代码中使用它。我的服务提供商确实有可用的 Redis 服务器实例。 我不想用错误的代码禁用我的应用程序,因为人们目前正在使用它。
这是我用于 API 的代码(JSON 数据被截断以更容易阅读代码)。任何帮助将不胜感激。
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
//const router = express.Router();
const port = 26695;
const cors = require('cors');
app.use(cors({credentials: true, origin: true}))
app.use(bodyParser.json());
// set the server to listen on port
app.listen(port, () => console.log(`Listening on port ${port}`));
// all of the code from the previous section should be here
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,OPTIONS,HEAD,PUT,POST,DELETE,PATCH');
res.header('Access-Control-Allow-Headers', 'origin, x-http-method-override, accept, content-type, authorization, x-pingother, if-match, if-modified-since, if-none-match, if-unmodified-since, x-requested-with');
res.header('Access-Control-Expose-Headers', 'tag, link, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes');
next();
};
module.exports = function allowCORS() {
return allowCrossDomain;
};
const cri = [{"criSingleOnly":"true","species":"All","fluids":"cri","criName":"","drugname":"Alfaxalone","dosetochange":"","perml":"mg/ml","dosemax":"0.4","dosage":"0.05","class":"loading","calcID":"Alfaxalone2L","concentration":"10","cridose":[{"dosemax":"9","dosevalue":"4","name":"Alfaxalone CRI","dosemin":"4","dosestep":"1","range":"4-9 mg/kg/hr"}],"indication":"","multiply":"1","dosevalue":"","dosestep":"0.01","route":"IV,SQ,IM","calc":"AlfaxaloneL","hide":"","appendose":" mg","loaddose":[{"dosemax":"9.7","dosevalue":"2","name":"Alfaxalone Loading","dosemin":"1.5","dosestep":"0.5","range":"1.5-9.7 mg/kg IV to Effect over 1min,IM"}],"doseT":"true","notes":"","appendvol":"","range":"","dosemin":"0.01","doseper":"0.05","perkg":"mg/kg","decimal":"2"}]
app.get("/cri", (request, response) => {
response.send(cri);
});
【问题讨论】:
-
我不确定我是否理解,因为您似乎只“下载”了一次
cri数组 -
每次用户访问某个页面时都会下载数据,可以在一个会话中多次访问。被缓存应该会加快页面访问的后续时间。 (数据为mb数)
-
您可以将一个充满客户端 IP 的对象作为密钥和静态版本作为
cri值,并且只发送差异 -
由于应用商店和 Play 商店的隐私限制,我无法获取应用用户 IP 地址。
-
啊,你可以创建一个 ID 系统而不是用户 ID(因为在第一次连接中,客户端会为客户端提供一些令牌,它是缓存对象服务器端的唯一键),并将这些键与静态你最后一次向他们发送对象的版本(客户将拥有什么)并且你每次发送差异(你如何做到这一点取决于你)
标签: node.js json express caching