跟著《架構探險》學輕量級微服務架構 (二)

coding01發表於2017-09-22

架構探險
架構探險

回顧 —— 微服務

微服務是一種分散式系統架構,它建議我們將業務劃分為更加細粒度的服務,並使每個服務的責任單一且可獨立部署,服務內部高內聚,隱含內部細節,服務之間低耦合,彼此相互隔離。此外,我們根據面向服務的業務領域來建模,對外提供統一的 API 介面。微服務的思想不只是停留在開發階段,它貫穿於設計、開發、測試、部署、運維等軟體生命週期階段。
引用於《架構探險》

寫程式碼

上一篇主要簡單搭建了 Spring Boot 框架,寫了一個簡單的路由/hello,Spring Boot 的其它功能根據後續的學習,再不斷完善,接下來我們開始下一個概念:

1. 微服務開發框架 —— Spring Boot 框架
2. 微服務閘道器 —— Node.js
3. 微服務註冊與發現 —— ZooKeeper
4. 微服務封裝 —— Docker
5. 微服務部署 —— Jenkins, GitLab

微服務閘道器 —— Node.js

微服務閘道器是微服務架構中的核心元件,它是客戶端請求的門戶,它是呼叫具體服務端的橋樑。
來自於《架構探險》

簡單的說,微服務閘道器是一個伺服器,也可以說是進入系統的唯一入口。這與物件導向設計模式中的 Facade 模式很像。微服務閘道器封裝內部系統的架構,並且提供 API 給各個客戶端。它還可能還具備授權、監控、負載均衡、快取、請求分片和管理、靜態響應處理等功能。

《架構探險》一書使用 Node.js 實現服務閘道器的重要特性之一:反向代理。

安裝 Node.js 就不在這裡描述了,如果是 Mac 系統,可以直接使用 brew (brew.sh/) 命令安裝。

1. 安裝 npm 國內映象

npm install cnpm -g --registry=https://registry.npm.taobao.org複製程式碼

2. 安裝反向代理外掛 Http Proxy 模組:

cnpm install http-proxy --save複製程式碼

3. 編寫 app.js:

var http = require('http');

var httpProxy = require('http-proxy');

var PORT = 1234;

var proxy = httpProxy.createProxyServer();
proxy.on('error', function( err, req, res) {
    res.end(); // 輸出空白響應資料
});

var app = http.createServer(function (req, res) {
    proxy.web(req, res, {
        target: 'http://localhost:8080'  // 目標地址
    });
});

app.listen(PORT, function() {
    console.log('server is running at %d', PORT);
});複製程式碼

執行 app.js 應用程式:

node app.js複製程式碼

我們修改上一篇寫的 Spring Boot 應用,讓訪問 http://localhost:8080/ 可以直接訪回「你好 葉梅樹」。

這樣我們可以直接訪問 http://localhost:1234/ 看看「反向代理」能不能起到作用,反向到: http://localhost:8080/,如下:

這就表明了我們的反向代理起到作用了。

Node.js 叢集環境

Node.js 採用了單執行緒模型,且擁有基於事件驅動的非同步非阻塞 I/O 特性,可高效利用 CPU 資源,但並不能說明 Node.js 只能執行在單核 CPU 下。事實上,Node.js 原生已支援叢集特性。如下程式碼所示:

var http = require('http');

var cluster = require('cluster');

var os = require('os');

var PORT = 1234;

var CUPS = os.cpus().length; // 獲取 CPU 核心數

if (cluster.isMaster) {
    // 當前程式為主程式
    for (var i = 0; i < CUPS; i++) {
        cluster.fork();
    }
} else {
    // 當前程式為子程式
    var app = http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<h1>Hello</h1>');
        res.end();
    })

    app.listen(PORT, function () {
        console.log('server is running at %d', PORT);
    })
}複製程式碼

注:通過 OS 模組獲取主機的 CPU 核心數,利用 Cluster 模組來判斷當前程式是否為主執行緒或者是子執行緒,如果是主執行緒則建立子執行緒,然後利用子執行緒來執行相關的程式程式碼,這裡 CPU 核心數越多,建立的子執行緒越多,支援的併發量也就越高。

Node.js 執行工具比較

1. supervisor。主要用於開發階段,能夠實時監控原始檔的變化,自動重新載入,檢視執行結果,提供開發效率。

2. forever (github.com/foreverjs/f…)。

# 啟動
forever start ./bin/www  #最簡單的啟動方式
forever start -l forever.log ./bin/www  #指定forever日誌輸出檔案,預設路徑~/.forever
forever start -l forever.log -a ./bin/www  #需要注意,如果第一次啟動帶日誌輸出檔案,以後啟動都需要加上 -a 引數,forever預設不覆蓋原檔案
forever start -o out.log -e err.log ./bin/www  #指定node.js應用的控制檯輸出檔案和錯誤資訊輸出檔案
forever start -w ./bin/www  #監聽當前目錄下檔案改動,如有改動,立刻重啟應用,不推薦的做法!如有日誌檔案,日誌檔案是頻繁更改的

# 重啟
forever restart ./bin/www  #重啟單個應用
forever restart [pid]  #根據pid重啟單個應用
forever restartall  #重啟所有應用

# 停止(和重啟很類似)
forever stop ./bin/www  #停止單個應用
forever stop [pid]  #根據pid停止單個應用
forever stopall  #停止所有應用

# 檢視forever守護的應用列表
forever list複製程式碼

3. pm2 (github.com/Unitech/pm2)。

npm install -g pm2  # 安裝pm2
# Fork mode
pm2 start app.js --name my-api # Name process

# Cluster mode
pm2 start app.js -i 0        # Will start maximum processes with LB depending on available CPUs
pm2 start app.js -i max      # Same as above, but deprecated.

# Listing

pm2 list               # Display all processes status
pm2 jlist              # Print process list in raw JSON
pm2 prettylist         # Print process list in beautified JSON

pm2 describe 0         # Display all informations about a specific process

pm2 monit              # Monitor all processes

# Logs

pm2 logs [--raw]       # Display all processes logs in streaming
pm2 flush              # Empty all log file
pm2 reloadLogs         # Reload all logs

# Actions

pm2 stop all           # Stop all processes
pm2 restart all        # Restart all processes

pm2 reload all         # Will 0s downtime reload (for NETWORKED apps)

pm2 stop 0             # Stop specific process id
pm2 restart 0          # Restart specific process id

pm2 delete 0           # Will remove process from pm2 list
pm2 delete all         # Will remove all processes from pm2 list

# Misc

pm2 reset <process>    # Reset meta data (restarted time...)
pm2 updatePM2          # Update in memory pm2
pm2 ping               # Ensure pm2 daemon has been launched
pm2 sendSignal SIGUSR2 my-app # Send system signal to script
pm2 start app.js --no-daemon
pm2 start app.js --no-vizion
pm2 start app.js --no-autorestart複製程式碼
feature forever pm2
keep alive
coffeescript
Log aggregation
api
terminal monitoring
clustering
Json configuration

從這表可以看出,pm2 相比較 forever,功能更加強大一些。在現實生產環境下,我們用 pm2更多一些,因為都是工具,更多的就看你用的順不順手,然後再根據每個工具的優劣,合理使用。

總結

學習 Node.js 的東西太多太多了,這只是冰山一角。這裡主要是利用 Node.js 的「反向代理」來搭建 「微服務閘道器」,學習「微服務閘道器」的基本概念。


明天接著學習,coding01 值得您關注

qrcode
qrcode


也很感謝您能看到這了

qrcode
qrcode

相關文章