隨著網路的發展,圖片和影片等媒體資源的使用越來越廣泛。身為網站經營者,如何快速、穩定地提供大量的圖片資源成為了一個必須考慮的問題。在此,我們介紹一種使用 nginx 與 Node.js 建立圖片伺服器的方案,來提供高效率、快速、可靠的圖片服務。
一、方案概述
此方案的主要組成部分如下:
在此方案中,nginx 來提供靜態檔案服務,而 Node.js 作為處理中心,負責處理圖片的縮放、裁剪、浮水印等操作。同時,利用 Redis 的快取機制,減少 Node.js 頻繁讀取圖片的次數,提高圖片處理速度與回應時間。
二、方案實作
#透過apt-get 安裝nginx:
sudo apt-get update sudo apt-get install nginx
透過nvm 安裝Node.js 和npm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash source ~/.bashrc nvm install <node-version>
sudo apt-get update sudo apt-get install redis-server
{ "name": "image-server", "version": "1.0.0", "description": "An image server based on Node.js", "main": "app.js", "dependencies": { "express": "^4.17.1", "sharp": "^0.28.3", "redis": "^3.0.2" } }
const express = require('express'); const sharp = require('sharp'); const redis = require('redis'); const app = express(); const port = process.env.PORT || 3000; // Connect to Redis const redisClient = redis.createClient(); // Handle image requests app.get('/:path', async (req, res) => { const { path } = req.params; const { w, h, q } = req.query; // Check if the image exists in Redis cache redisClient.get(path, async (err, cachedImage) => { if (cachedImage) { // Serve the cached image res.header('Content-Type', 'image/jpeg'); res.send(cachedImage); } else { // Read the original image const image = sharp(`images/${path}`); // Apply image transforms if (w || h) image.resize(Number(w), Number(h)); if (q) image.jpeg({ quality: Number(q) }); // Convert the image to Buffer const buffer = await image.toBuffer(); // Cache the image in Redis redisClient.set(path, buffer); // Serve the transformed image res.header('Content-Type', 'image/jpeg'); res.send(buffer); } }); }); // Start the server app.listen(port, () => { console.log(`Server is listening on port ${port}`); });
http { ... # Set proxy cache path proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m; proxy_cache_key "$scheme$request_method$host$request_uri"; ... server { listen 80; server_name example.com; location /images/ { # Enable proxy cache proxy_cache my_cache; proxy_cache_valid 60m; proxy_cache_lock on; # Proxy requests to Node.js app proxy_pass http://127.0.0.1:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Enable caching of proxied responses proxy_cache_revalidate on; proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504; } } }
以上是nginx加nodejs搭建圖片伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!