Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Serverless and SSR

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Serverless and SSR example analysis, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

What is SSR?

SSR, as its name implies, is Server-Side Render, or server-side rendering. The principle is very simple: the server directly renders the HTML string template, and the browser can directly parse the string template to display the page, so the content of the first screen no longer depends on Javascript rendering (CSR-client rendering).

Core benefits of SSR:

Loading time of the first screen: because it is HTML straight out, the browser can directly parse the string template to display the page.

SEO-friendly: it is precisely because the server rendering output to the browser is a complete html string, so that the search engine can crawl the real content, which is good for SEO.

SSR needs to pay attention to:

Although SSR can render pages quickly, pages cannot interact with UI until UI frameworks such as React are successfully loaded.

TTFB (Time To First Byte), that is, the first byte time will be longer, because SSR needs to render a more correct HTML fragment on the server side than CSR, so the loading time will be longer.

More server-side load. Because SSR relies on Node.js services to render pages, it obviously takes up more server CPU resources than CSR applications that only provide static files. In the case of React, its renderToString () method is a synchronous CPU binding call, which means that the server cannot process other requests until it is complete. Therefore, in high concurrency scenarios, you need to prepare the corresponding server load and make a good caching strategy.

What is Serverless?

Serverless, which is an abstraction of computing resources in the development of cloud computing, relies on third-party services, so developers can focus more on developing their own business code without paying attention to the allocation, expansion and deployment of underlying resources.

Features:

Developers only need to focus on the business and need not care about the allocation, expansion and deployment of the underlying resources.

Use and charge on demand

Automatic expansion and reduction

For a more detailed introduction to Serverless, it is recommended to read "what does Serverless bring to the front end"

Serverless + SSR

Combined with the characteristics of Serverless and SSR, we can find that they are a perfect match. With the help of Serverless, the front-end team does not need to pay attention to the deployment, operation and maintenance of the SSR server, which can greatly reduce the deployment operation and maintenance costs, better focus on business development, and improve development efficiency.

At the same time, there is no need to worry about the performance of the SSR server. Theoretically, Serverless can be expanded indefinitely (of course, cloud vendors have an expansion limit for ordinary users).

How to quickly Serverless SSR applications?

Since Serverless has natural advantages for SSR, how can we migrate SSR applications to Serverless architecture?

This article will take the Next.js framework as an example to take you to quickly experience the deployment of a Serverless SSR application.

With the Nextjs component of Serverless Framework, you can basically seamlessly migrate to Tencent Cloud function SCF.

1. Initialize the Next.js project $npm init next-app serverless-next$ cd serverless-next# compile the static file $npm run build2. Install Serverless CLI$ npm install serverless-G3 globally. Configure severless.ymlorg: orgDemoapp: appDemostage: devcomponent: nextjsname: nextjsDemoinputs: src:. / functionName: nextjsDemo region: ap-guangzhou runtime: Nodejs10.15 exclude:-.env apigatewayConf: protocols:-https environment: release4. Deployment

Authentication is required during deployment. If your account is not logged in or registered with Tencent Cloud, you can log in and register directly through the QR code in the command line scanned by Wechat. Of course, you can also create .env file directly under the project to configure Tencent Cloud SecretId and SecretKey. As follows:

TENCENT_SECRET_ID=123TENCENT_SECRET_KEY=123

Execute the deployment command:

$serverless deploy

The following serverless commands are all abbreviated to sls.

After the deployment is successful, you can directly access the domain name generated by the API gateway.

Links like https://service-xxx-xxx.gz.apigw.tencentcs.com/release/.

Migration of existing Next.js applications

If your project is a custom Server based on Express.js, you need to create a new sls.js entry file in the project root directory. You only need to copy the original Node.js Server entry file to sls.js, and then make a few modifications. The default entry sls.js file is as follows:

Const express = require ('express'); const next = require (' next'); const app = next ({dev: false}); const handle = app.getRequestHandler (); / / put the original service logic into the asynchronous function `createServer () `async function createServer () {/ / the internal content needs to be modified according to the project requirements, basically the original code await app.prepare () of your `server.js`; const server = express () Server.all ('*', (req, res) = > {return handle (req, res);}) / / define the returned binary file type / / since `gzip` is enabled by default in Next.js framework, it needs to be `[* / *']` / / if the project turns off the compression of `gzip`, you need to customize the configuration for image files, such as `['image/jpeg',' image/png']` server.binaryTypes = ['* / *']; return server;} / / export function createServer () module.exports = createServer

After adding the entry file, re-execute the deployment command sls deploy to OK.

Optimization of Serverless deployment Plan

So far, we have successfully migrated the entire Next.js application to Tencent Cloud's Serverless architecture, but there is a problem here, that is, all static resources are deployed to the cloud function SCF, which results in a lot of static source requests for each page request. For SCF, the concurrency is relatively high at the same time, and it is easy to cause cold start. And a large number of static resources are output through SCF and then returned through the API gateway, which will not only increase the link length, but also lead to slow loading of static resources, which will virtually drag down the loading speed of web pages.

Cloud vendors generally provide cloud object storage. Tencent Cloud is called COS (object Storage). Using it to store our static resources has a natural advantage. And start to use 50GB floor blocks! Free capacity (it's also good to save your favorite HD movies).

If static resources are uploaded to COS when our project is deployed, and then static pages are rendered through SCF, this not only supports SSR, but also solves the problem of static resource access. COS also supports CDN acceleration, which makes static resource optimization more convenient.

So how do we upload static resources to COS?

Log in to [Tencent Cloud COS console] (https://console.cloud.tencent.com/cos5)-> create Bucket-> obtain COS access Link-> build Next.js Project-> Click COS upload button-> Select upload File-> start upload-> finish configuring COS components for Literary and artistic Youth practices-> build Next.js Project-> execute commands for deploying COS components-> finish

Next, let's learn how literary and artistic youth do it.

Create a COS folder under the project and create a cos/serverless.yml configuration file:

Org: orgDemoapp: appDemostage: devcomponent: cosname: serverless-cosinputs: # src is configured as the target directory built by your next project src:.. / .next/static # since the next framework automatically appends the _ next prefix to static files, you need to configure the target directory for uploading COS as / _ next targetDir: / _ next/static bucket: serverless-bucket region: ap-guangzhou protocol: https acl: permissions: public-read

Generate rules based on COS access links:

: / /-.cos..myqcloud.com

It can be directly inferred that the access URL after deployment is: https://serverless-bucket-1251556596.cos.ap-guangzhou.myqcloud.com

Then create a new next.config.js file in the project change directory and configure assetPrefix as the link:

Const isProd = process.env.NODE_ENV = = 'production';module.exports = {assetPrefix: isProd? 'https://serverless-bucket-1251556596.cos.ap-guangzhou.myqcloud.com':',}

Note: if you directly configure the CDN domain name for the COS.

Then perform the build:

$npm run build

Then add the deployment command and deploy it to the cos command:

$sls deploy-- target=./cos & & sls deploy

Then we can wait patiently for the deployment to be completed.

Serverless + Next.js deployment flowchart

The overall deployment flow chart of the optimized project is as follows:

Although it may seem like a lot of steps at first, after the project is configured once, and then deployed, you only need to execute the build and deployment commands.

Performance analysis.

Rely on Serverless Component, although we can deploy SSR applications quickly. But for developers, performance is the most important thing. So how does the Serverless scheme perform?

In order to compare with traditional SSR services, I specifically found a CVM (Tencent Cloud server) and deployed the same Next.js application. The pressure test and performance analysis were carried out respectively.

The stress test configuration is as follows:

Initial number of people per stage increase number of people per stage duration (s) maximum number of packages interval time (ms) timeout time (ms) 55301000000

Tencent WeTest is used in this stress test.

Comparison of page access performance

All use Chrome browsers

Configuration of TTFBFCPTTI Tencent Cloud CVM2 core, 4G memory, 10m bandwidth 50.12ms2.0s2.1s Tencent Cloud Serverless128M memory 69.88ms2.0s2.2s stress test performance comparison 1. Response time:

The solution configures the maximum response time P95 time-consuming P50 time-consuming average response time Tencent Cloud CVM2 core, 4G memory, 10m bandwidth 8830ms298ms35ms71.05 ms Tencent Cloud Serverless128M memory 1733ms103ms73ms76.78 ms2.TPS:

Solution configuration average TPS Tencent Cloud CVM2 core, 4G memory, 10m bandwidth 727.09 / s Tencent Cloud Serverless128M memory 675.59 / s budget comparison

Directly above:

Comparison and analysis

From the point of view of the page performance of a single user, the Serverless scheme is slightly inferior to the server scheme, but the page performance index can be optimized. From the pressure test, although the average response time of Serverless is slightly longer than that of CVM, the maximum response time and P95 time of CVM are much better than that of CVM, and the maximum response time of CVM is even close to 3 times that of Serverless. And when the concurrency gradually increases, the response time of CVM changes obviously, and becomes larger and larger, while Serverless is stable, except for a few cold start, it can basically be within 200ms.

It can be seen that with the increase of concurrency, SSR will lead to more and more server load, which will increase the response time of the server; while Serverless has the ability to automatically expand and shrink, so it is relatively stable.

Of course, due to the limited test conditions, there may not be enough comprehensive consideration, but from the pressure test figure, it is fully in line with the theoretical expectations.

However, from the perspective of price comparison, the Serverless solution close to the configuration is basically cheap, and in many cases, the free quota can already meet the demand. Here, in order to increase the Serverless cost, the number of calls and memory size are estimated to be increased, but even so, the server solution is still close to 10 times that of the Serverless solution!

After reading the above, have you mastered the method of example analysis of Serverless and SSR? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report