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

架構探險
架構探險

回顧 —— 微服務

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

寫代碼

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

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

微服務網關 —— Node.js

微服務網關是微服務架構中的核心組件,它是客戶端請求的門戶,它是調用具體服務端的橋樑。
來自於《架構探險》github

簡單的說,微服務網關是一個服務器,也能夠說是進入系統的惟一入口。這與面向對象設計模式中的 Facade 模式很像。微服務網關封裝內部系統的架構,而且提供 API 給各個客戶端。它還可能還具有受權、監控、負載均衡、緩存、請求分片和管理、靜態響應處理等功能。web

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

安裝 Node.js 就不在這裏描述了,若是是 Mac 系統,能夠直接使用 brew (brew.sh/) 命令安裝。設計模式

1. 安裝 npm 國內鏡像api

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

2. 安裝反向代理插件 Http Proxy 模塊:緩存

cnpm install http-proxy --save複製代碼

3. 編寫 app.js:bash

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
相關文章
相關標籤/搜索