In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you based on the Nuxt.js project server performance optimization and error detection example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Nuxt.js is a server-side rendering application framework based on Vue.js. Some points to be considered when developing isomorphic projects with nuxt.js are summarized as follows:
1. Node server performance optimization (improving the ability of node applications to handle high traffic)
For nuxt.js-based server rendering projects, there are the following server performance optimizations we can do (it should be noted that persistence caching should not be done in the local development environment, so that the problems of code in local development will not be exposed during caching)
Optimization point reference documents and ideas to optimize scenarios / conditions, especially the detection method 1. Page cache vue official document page content is not user-specific (that is, for the same URL, the same content is always rendered for all users) generally speaking, a page is persisted on the server side, so the component cache corresponding to the api cache of the page is meaningless, for cases where the page cache and the api cache exist at the same time (it may exist) The api cache time should be less than the page cache time, so as to keep the content of the api response up to date. 1. Code local testing: print the test log in asyncData, after the page cache, the server will not output the test log after the page is refreshed 2. Comparing the DOMContentLoaded time loaded on the html page, you can see that the cached value of the refreshed page is smaller than that of the first page loaded (not cached). The api cache in the axios request and response interceptor to do the interface response content is not user-specific (that is, for the same api interface URL That is, it always responds to the same content for all users.) the general request method is GET api request to compare the response time between the first request and the cached api interface. Component cache nuxtjs official website document vue official website document does not depend on the global state, and the component name value to be cached for sub-components that do not have side effects on the rendering context must be unique. ServerCacheKey is consistent with the page cache detection method according to the value of a prop as the only key detection method, which may be almost undetectable. 4. AsyncData function optimizes Promise.all the number of requested api interfaces in this function is more than 1, even more than 20. In this case, we can't use async await, request one request and then request the next (synchronous request interface) If there are 10 interfaces that need requests, and each interface responds for 1 second on average, it takes at least 10 seconds to respond to the html page; if you use Promise.all to request 10 interfaces asynchronously, the fastest response to the html page is 1 second; the asyncData function executes the code on the server side, so you must do a good job of fault tolerance In addition, if the function code has not been finished, the first response of the page will be suspended and will always be loaded. For the first time of loading, the shorter the execution time of the function, the shorter the response time of the page (the faster the page loads).
1. The realization of page cache function module.
We create a file ~ / serverMiddleware/page-cache.js in the project root directory
Import LRUCache from 'lru-cache'const cache = new LRUCache ({maxAge: 1000 * 60 * 2, / / valid for 2 minutes max: 1000 / / maximum number of caches}) export default function (req, res, next) {/ / the local development environment does not cache pages if (process.env.NODE_ENV! = =' development') {try {const cacheKey = req.url const cacheData = cache.get (cacheKey) if (cacheData) {return res.end (cacheData) 'utf8')} const originalEnd = res.end res.end = function (data) {cache.set (cacheKey, data) originalEnd.call (res,... arguments)}} catch (error) {/ / console.log (`page-cache-middleware: ${error} `) next ()} next ()}
2. Implementation of api cache function module.
We create two files ~ / plugins/axios/createCacheKey.js and ~ / plugins/axios/cache.js in the root directory of the project. In particular, the nuxt.js development environment cache.js plug-in code is refreshed on the page, and the routing switch is equivalent to running for the first time, so you will find that the cache function is invalid, and the test is valid only in the process.env.NODE_ENV = 'production' production environment.
/ / ~ / plugins/axios/createCacheKey.jsimport md5 from 'md5'/** * according to the request configuration, whether the request interceptor creates the cache key * @ param {Object} config * @ param {Boolean} isRequest * / export default function createCacheKey (config = {}, isRequest = false) {const {url, data, params, method, baseURL,} = config | {} let commonUrl = url / * * request interceptor config.url is unspliced baseURL The response.config.url in the response interceptor is spliced with baseURL. * in order to maintain unity, use the commonUrl of unified splicing baseURL. Note the following if condition judgment * / if (isRequest & &! commonUrl.match (baseURL) & &! commonUrl.match (/ ^ https?/)) {commonUrl =! baseURL.match (/. +\ / $/)? `${baseURL.replace (/\ / $/,')} ${url}`: `${baseURL} ${url}` / according to the request instruction, url, bodybody Parameter generation rule const rule = `method=$ {method}-url=$ {commonUrl}-data=$ {JSON.stringify (data | | {})}-params=$ {JSON.stringify (params | | {})} `/ / md5 encryption return md5 (rule)}
/ / ~ / plugins/axios/cache.js
Import LRUCache from 'lru-cache'import axios from' axios'import globalConfig from'. /.. / global-config'import createCacheKey from'. / createCacheKey'const cache = new LRUCache ({maxAge: 1000 * 60, / / valid for 60 seconds. If a page cache exists, the api cache time should be less than the page cache time. This is to keep the contents of the api response up-to-date max: 1000 / / maximum number of caches}) / * whether matchCacheCondition meets the persistence cache condition: server runtime & & non-local development environment & & api request is configured for get request mode * @ param {Object} config request * / function matchCacheCondition (config = {}) {return process.server & & process.env.NODE_ENV! = = 'development '& & config.method.toLowerCase () = =' get'} / * if caching is enabled on all pages Api cache is not necessary * / export default function ({$axios, redirect}) {$axios.interceptors.request.use (config = > {const {baseUrl} = globalConfig config.baseURL = baseUrl [process.env.environment] | baseUrl ['other'] / / Direct return config if (! matchCacheCondition (config)) {return config} const cacheKey = createCacheKey (config) if the cache condition is not met True) const cacheData = cache.get (cacheKey) if (cacheData) {const source = axios.CancelToken.source () config.cancelToken = source.token source.cancel ({cacheData, cacheKey, url: config.url}) return config} return config}) $axios.interceptors.response.use (response = > {if (matchCacheCondition (response.config)) {cache.set (createCacheKey (response.config), response)} return response} (error) = > {if (axios.isCancel (error) & & matchCacheCondition (response.config)) {/ / console.log (the cached interface url in the current page component asyncData or fetch function is: ${error.message.url} `) return Promise.resolve (error.message.cacheData)} / / the server prints api API request error log if (process.server) {try {const {config: {url} Message} = error | | {} console.log (`request url:$ {url}) Error message: ${message} `)} catch (error) {/ / console.log (error)}} / / the server side unifies the reject error object, so the asyncData,fetch function of the page component requests that the api interface must do catch processing return Promise.reject (error)})}
3. Component caching
Vue official website document original words: if renderer makes a cache hit during component rendering, then it will directly reuse the cached results of the entire subtree. This means that you should not cache components in the following situations:
It has subcomponents that may depend on the global state.
It has subcomponents that have side effects (side effect) on the rendering context.
Therefore, component caching should be used carefully to solve performance bottlenecks. In most cases, you should not and do not need to cache an instance component. The most common types of components that apply to caching are those that are repeated in large v-for lists. Because these components are usually driven by objects in the database collection (database collection), they can use a simple caching strategy: use their unique id, plus the last updated timestamp, to generate their cache key (cache key):
ServerCacheKey: props = > props.item.id +'::'+ props.item.last_updated
4. AsyncData function optimization of page components.
Give a simple example to optimize.
{async asyncData ({$axios}) {/ / 1. Catch processing is added so that the server side and the client side do not report errors at runtime, especially to prevent the server side from reporting no errors at runtime, otherwise the page will fail / / 2 and the catch function returns a Promise of an resolve empty literal object It shows that the future state of dataPromise1 is always resolved state const dataPromise1 = $axios.get ('/ api/data1'). Catch () = > Promise.resolve ({}) const dataPromise2 = $axios.get ('/ api/data2'). Catch () = > Promise.resolve ({}) const dataPromise3 = $axios.get ('/ api/data3'). Catch () = > Promise.resolve ({}) const dataPromise4 = $axios.get ('/ api/data4'). Catch () = > Promise. Resolve ({})) const dataPromise5 = $axios.get ('/ api/data5'). Catch (() = > Promise.resolve ({})) const dataPromise6 = $axios.get ('/ api/data6'). Catch () = > Promise.resolve ({})) const dataPromise7 = $axios.get ('/ api/data7'). Catch () = > Promise.resolve ({}) const dataPromise8 = $axios.get ('/ api/data8'). Catch () = > Promise.resolve ({}) / / make sure apiData has data const apiData = await new Promise (resolve = > {Promise.all ([dataPromise1) DataPromise2, dataPromise3, dataPromise4, dataPromise5, dataPromise6, dataPromise7, dataPromise8,]. Then (dataGather = > {resolve ({data1: dataGather [0], data2: dataGather [1], data3: dataGather [2], data4: dataGather [3], data5: dataGather [4], data6: dataGather [5], data7: dataGather [6], data8: dataGather [7],})}) return apiData}}
Second, node server error detection, fault-tolerant processing (to improve the fault-tolerant ability of node applications)
First of all, make sure to use the nuxt.js framework, the following functions in the vue components (page / non-page components) will be executed on the server side, so the code fault tolerance is very important. Once the function code execution goes wrong, the page will hang up.
Fetch
AsyncData
BeforeCreate
Created
1. Visible mistakes
Visible error means that in the development environment, as long as you js the error in the above functions such as fetch, there will be an error prompt locally, which is convenient for you to find and correct the error code logic.
2. Unknown / invisible errors (expose unknown errors)
An invisible error means that some error codes in asynchronous callbacks are not easy to find, and if the asynchronous behavior has not been triggered, the callback code that handles the asynchronous behavior will not be executed. But for the error troubleshooting of the api interface request callback for all pages (mainly fault-tolerant processing to make the code more robust, java interface request 404, interface data field / structure processing) we can do it well, very simply, we only need to change the request url in the request interceptor
$axios.interceptors.request.use (config = > {/ / TODO / / detect node application error caused by failed request for java interface config.url + ='/ xxxx' return config})
3. Processing of page refresh loading data that does not need to be rendered
Only the page component asyncData (the object returned by the function is fused with the component data), and the data processed by the fetch (update store operation) function is bound to the page, the page refresh loading server will render. Therefore, it is not recommended that the component obtain the data that the page refresh loads do not need to render by requesting the api API in the beforeCreate,created function. It only needs to be processed in the mounted function to prevent errors in the node application due to code errors.
The above is all the contents of the article "sample Analysis of Server-side performance Optimization and error Detection based on Nuxt.js Project". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.