在Debian上使用Node.js实现并发控制,可以通过以下几种方法:
const fs = require('fs').promises;
async function readFiles() {
try {
const data1 = await fs.readFile('file1.txt', 'utf-8');
console.log(data1);
const data2 = await fs.readFile('file2.txt', 'utf-8');
console.log(data2);
} catch (error) {
console.error(error);
}
}
readFiles();
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/file1') {
fs.readFile('file1.txt', 'utf-8', (err, data) => {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
});
} else if (req.url === '/file2') {
fs.readFile('file2.txt', 'utf-8', (err, data) => {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case, it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
const async = require('async');
const urls = ['url1', 'url2', 'url3'];
// 控制并发请求数为2
const limit = async.limit(2);
urls.forEach(url => {
limit(() => {
request(url, (error, response, body) => {
if (error) {
console.error(error);
} else {
console.log(body);
}
});
});
});
通过以上方法,可以在Debian上使用Node.js实现并发控制。在实际应用中,可以根据需求选择合适的方法。