以下代碼在我的 NGINX 服務器上 ping 一個 NGINX 位置塊,為您提供健康檢查狀態。
const ping = async () => {
const url = `http://10.10.1.100/status`;
const postData = {
method: 'POST', // *GET, POST, PATCH, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'text/plain; charset=ASCII'
},
body: 'PING'
}
try {
let factor = 1;
let timeout = 3000; // ms
let start = (new Date()).getTime();
const request = await fetch(url, postData);
let delta = new Date().getTime() - start;
delta *= (factor || 1);
if(delta > timeout) throw new Error(`PONG > ${timeout}ms. Server down?`);
if(!request.ok) throw new Error(`${request.status} ${request.statusText}`);
const response = await request.text();
if(!response) throw new Error(`${response}`);
document.getElementById('serverPongSpeed').innerText = `${delta.toFixed(0)}ms`;
// Do Something...
console.log(`%c${delta.toFixed(0)}ms ${response}`, "color: #c6ff00"); // Lime A400
} catch (error) {
console.log(error);
}
}
NGINX 位置塊:
location = /status {
access_log off;
default_type text/plain;
add_header "Access-Control-Allow-Methods" "POST";
add_header "Content-Type" "text/plain";
return 200 "PONG";
}
現在我像這樣運行它:
setInterval(ping, 3000); // Every 3 seconds
問題是,在測驗期間,當我關閉 NGINX 以查看 PING 不會中斷時會發生什么。它只是不斷發送 POST 請求。
也許這是我沒有發現的錯誤?或者可能沒有錯誤,因為提取有更大的超時?也許將 fetch 超時設定為 3 秒會觸發一些讓我捕捉的東西..
uj5u.com熱心網友回復:
以下是所需作業解決方案的修訂后完整示例。
javascript異步等待ping函式:
- Ping 功能設定為向 NGINX /status 位置塊發布請求。
- Ping 功能設定為 300 毫秒超時以指示可能的服務器停機。
- Ping 功能設定為使用預設閾值指示增加的網路延遲。
- Ping 功能設定為捕獲網路級錯誤和任何其他未知錯誤。
- Ping 函式將輸出回傳到控制臺。
...
window.onload = () => {
let precision = 2; // decimals
let pageLoadSpeed = ((window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart) / 1000).toFixed(precision);
document.getElementById('pageLoadSpeed').innerText = `${pageLoadSpeed}s`;
console.log(`%cPage loaded in ${pageLoadSpeed} seconds.`, "color: #c6ff00"); // Lime A400
let polling = null;
// Network latency thresholds
const settings = {
pingInterval: 5000, // ms
latency: {
factor: 1.0, // Adjust latency to a percentage of its total
high: 99, // ms
moderate: 66, // ms
low: 33, // ms
},
timeout: 300, // ms
consoleLogLimit: 10,
consoleLogCount: 0,
};
const ping = async() => {
const url = `http://10.10.1.100/status`;
const postData = {
method: 'POST', // *GET, POST, PATCH, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'text/plain; charset=ASCII'
},
body: 'PING'
}
try {
const startWatch = (new Date()).getTime();
const request = await fetch(url, postData);
const stopWatch = (new Date().getTime() - startWatch) * (settings.latency.factor || 1);
if (!request.ok) throw new Error(`${request.status} ${request.statusText}`);
const response = await request.text();
if (!response) throw new Error(`${response}`);
if (stopWatch >= settings.timeout) {
console.log(`%cPONG > ${settings.timeout}ms. Server down?`, "color: #d500f9"); // purple A400
} else if (stopWatch >= settings.latency.high) {
console.log(`%c${response}: ${stopWatch}ms High Latency`, "color: #ff1744"); // red A400
} else if (stopWatch >= settings.latency.moderate) {
console.log(`%c${response}: ${stopWatch}ms Moderate Latency`, "color: #ffc400"); // amber A400
} else if (stopWatch <= settings.latency.low) {
console.log(`%c${response}: ${stopWatch}ms Low Latency`, "color: #00e676"); // green A400
}
settings.consoleLogCount ;
// Prevents browser from getting sluggish
if (settings.consoleLogCount == settings.consoleLogLimit 1) {
// Reset count
settings.consoleLogCount = 0;
// Clear console
console.clear();
}
} catch (error) {
// Catch network level error
if (error instanceof TypeError && error.message == 'NetworkError when attempting to fetch resource.') {
// Clear console
// console.clear();
console.error(`NGINX offline or Network cable unplugged?`);
// Reset count
settings.consoleLogCount = 0;
// Stop polling
clearInterval(polling);
} else {
// Catch any other error
console.error(error);
}
}
}
polling = setInterval(ping, settings.pingInterval);
}
...
NGINX 服務器 /status 位置塊:
- 端點設定為僅接受
/location端點上的POST 請求。 - 端點訪問日志設定為禁用,因為我們真的不需要記錄它。
- 端點設定為回應內容型別設定為文本/純文本。
- 端點設定為接受來自任何來源的 POST 請求。
- 端點設定為在成功時回傳文本/純文本的 Content-Type,并帶有文本“PONG”回應。
...
location = /status {
access_log off;
default_type text/plain;
limit_except POST {
deny all;
}
add_header Access-Control-Allow-Origin "*" always;
add_header Access-Control-Allow-Methods "POST, OPTIONS" always;
add_header Content-Type "text/plain" always;
return 200 "PONG";
}
uj5u.com熱心網友回復:
您可以像這樣使用 ClearInterval() 方法:
var interval = setInterval(ping, 3000);
if(timeoutCounter > 3)
clearInterval(interval)
您需要更多代碼來計算超時/錯誤。類似于斷路器模式的東西
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394251.html
標籤:javascript nginx 设置间隔
上一篇:問題:nginx:[emerg]mkdir()"/var/cache/nginx/client_temp"failed(13:Permissiondenied)
