NEXTJS放大服务器的慢速响应



我在AWS Amplify上安装了一个SSR应用程序Nextjs 12,速度太慢了。

记录getServerSideProps((,结果如下:加载页面需要9秒,但getServerSideProps中的代码只需不到0.5秒。

这是服务器日志:

START RequestId: 94ced4e1-ec32-4409-8039-fdcd9b5f5894 Version: 300
2022-09-13T09:25:32.236Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    1 [09:25:32.236] -
2022-09-13T09:25:32.253Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    2 [09:25:32.253] -
2022-09-13T09:25:32.255Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    3 [09:25:32.255] -
2022-09-13T09:25:32.255Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    4 [09:25:32.255] -
2022-09-13T09:25:32.431Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    5 [09:25:32.431] -
2022-09-13T09:25:32.496Z    94ced4e1-ec32-4409-8039-fdcd9b5f5894    INFO    6 [09:25:32.496] -
END RequestId: 94ced4e1-ec32-4409-8039-fdcd9b5f5894
REPORT RequestId: 94ced4e1-ec32-4409-8039-fdcd9b5f5894  Duration: 9695.59 ms    Billed Duration: 9696 ms    Memory Size: 512 MB Max Memory Used: 206 MB 

这就是代码:

export async function getServerSideProps(context) {
console.log("1 [" + new Date().toISOString().substring(11, 23) + "] -");
let req = context.req;
console.log("2 [" + new Date().toISOString().substring(11, 23) + "] -");
const { Auth } = withSSRContext({ req });
console.log("3 [" + new Date().toISOString().substring(11, 23) + "] -");
try {
console.log("4 [" + new Date().toISOString().substring(11, 23) + "] -");
const user = await Auth.currentAuthenticatedUser();
console.log("5 [" + new Date().toISOString().substring(11, 23) + "] -");
const dict = await serverSideTranslations(context.locale, ["common", "dashboard", "footer", "hedgefund", "info", "etf", "fs"]);
console.log("6 [" + new Date().toISOString().substring(11, 23) + "] -");
return {
props: {
exchange: context.params.exchange,
ticker: context.params.ticker,
username: user.username,
attributes: user.attributes,
...dict,
},
};
} catch (err) {
return {
redirect: {
permanent: false,
destination: "/auth/signin",
},
props: {},
};
}
}

这不是答案,而是另一种选择。

我尝试使用Amplify实现,因为Vercel业余爱好帐户上的getServerSideProps出现函数超时错误。然而,我认为Next.js部署到Amplify还没有优化。

我没有使用getServerSideProps,而是使用getStaticPathsgetStaticProps,因此我总是限制要从API获取的路径的数量。

在客户端

export const getStaticPaths: GetStaticPaths = async () => {
// This route to my API only gets paths(IDs)
const res = await getFetcher("/sentences-paths"); 
let paths = [];
if (res.success && res.resource) {
paths = res.resource.map((sentence: any) => ({
params: { sentenceSlug: sentence._id },
}));
}
return { paths, fallback: "blocking" };
};

关于API

const getSentencePaths = async (req, res) => {
const limit = 50;
Sentence.find(query)
.select("_id")
.limit(limit)
.exec()
.then((resource) => res.json({ success: true, resource }))
.catch((error) => res.json({ success: false, error }));
};

这意味着即使我有10万句话,在构建时也只有50句。其余的句子是按需生成的,因为我们有fallback: "blocking"。参见文档

以下是我的getStaticProps看起来像的样子

export const getStaticProps: GetStaticProps = async ({ params }) => {
const sentenceSlug = params?.sentenceSlug;
const response = await getFetcher(`/sentences/${sentenceSlug}`);
let sentence = null;
if (response.success && response.resource) sentence = response.resource;
if (!sentence) {
return {
notFound: true,
};
}
return {
props: { sentence },
revalidate: 60,
};
};

正如您在上面看到的,我使用revalidate: 60秒查看文档,但由于您想使用getServerSideProps,这不是完美的解决方案。

完美的解决方案是按需重新验证。这样,无论何时更改页面中使用的数据,例如更改sentence内容,都可以触发webhook来重新生成由getStaticProps创建的页面。因此,您的页面将始终更新。

通过这个youtube教程来实现按需重新验证,非常全面https://www.youtube.com/watch?v=Wh3P-sS1w0I&t=8s&ab_channel=TuomoKankaanp%C3%A4%C3%A4。

Vercel上的Next.js工作速度更快、效率更高。希望我能帮上忙。

[UPDATE]今天我意识到进入amplify,有人向我提出了";使用nextjs 12"的改进和性能;。

我做到了,它实际上变得更快了。。。不过它把我的后端环境搞砸了。。。

AWS利用NextJS 12增强性能-意外的后端环境交换机

最新更新