![](/img/trans.png)
[英]How do I change the port used by Remix.run's local development server?
[英]How do I use in-memory cache in Remix.run dev mode?
我需要從速度很慢且很少更改的 API 中獲取數據,所以我想我會使用內存緩存。 我首先嘗試了一種非常簡單的方法,只需將其保存到我的路徑中加載程序 function 的 scope 之外的變量中:
let cache;
export const loader = async () => {
if (!cache) {
// we always end up here
cache = await (await fetch("...)).json()
}
}
但這沒有用。 然后我嘗試了一個適當的緩存庫( lru-cache
),但那個緩存也總是空的。 然后我意識到整個文件都會在每個請求上重新加載,我猜這是一個開發模式的事情,所以我嘗試將緩存的創建移動到一個單獨的文件cache.server.ts並從那里導入它。
import LRU from "lru-cache";
console.log("Creating cache"); // this is logged on each request
const cache = new LRU({ max: 200 });
export default cache;
但是該文件似乎也會在每次請求時重新加載。
如果我構建了一個生產版本並運行它,一切都很好,但如果能有某種方法讓它在開發模式下也能工作,那就太好了。
Remix 清除開發中每個請求的require
緩存以支持<LiveReload/>
。 為了確保您的緩存能夠在這些清除中幸存下來,您需要將其分配給global
對象。
這是笑話教程中的一個示例
import { PrismaClient } from "@prisma/client";
let db: PrismaClient;
declare global {
var __db: PrismaClient | undefined;
}
// this is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
if (process.env.NODE_ENV === "production") {
db = new PrismaClient();
} else {
if (!global.__db) {
global.__db = new PrismaClient();
}
db = global.__db;
}
export { db };
https://remix.run/docs/en/v1/tutorials/jokes#connect-to-the-database
作為對 Kilimans 回答的跟進,我是這樣做的:
/*
* @see https://www.npmjs.com/package/node-cache
*/
import NodeCache from "node-cache";
let cache: NodeCache;
declare global {
var __cache: NodeCache | undefined;
}
const cacheSettings = {
stdTTL: 60 * 60 * 24,
checkperiod: 60 * 60 * 24,
};
if (process.env.NODE_ENV === "production") {
cache = new NodeCache(cacheSettings);
} else {
if (!global.__cache) {
global.__cache = new NodeCache(cacheSettings);
}
cache = global.__cache;
}
export { cache };
我在加載器中使用它:
import { getGitHubRepos } from "~/models/github.server";
import { cache } from "~/utils/cache";
export async function loader(args: LoaderArgs) {
if (cache.has("GitHubRepos")) {
return json(cache.get("GitHubRepos"));
}
const repos = await getGitHubRepos();
cache.set("GitHubRepos", repos);
return json(repos);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.