高大上的微服務可以很簡單,使用node寫微服務


安裝

npm install m-service --save

使用

編寫服務處理函數

// dir1/file1.js
// 使用傳入的console參數輸出可以自動在日志里帶上request id,便於跟蹤一個請求在所有微服務上的日志
// 返回值如果是非null,則會把該值JSON.stringify后作為結果返回,若是promise,則等待promise的結果再返回
module.exports.f1 = (console, query, body, req, res)=>{
	return {query, body, msg:'success'};
}

普通web服務模式

按照普通的web方式的方式提供服務

// web.js
let ms = require('m-service');

ms.createApp({
  services:{
    port: 5500,
    dir: __dirname,
    names:['dir1'],
  }
});

//localhost:4000/api/dir1/file1/f1?p1=1&p2=2

微服務模式:

分三個角色

  • 服務中心----服務注冊,服務發現
  • 服務代理----提供集成的web接口,用戶使用統一的url訪問所有微服務,屏蔽微服務內部的細節
  • 微服務----提供實際的處理服務,並將服務注冊到服務中心

啟動三個服務角色

// s1.js
let ms = require('m-service');

ms.createApp({
  centers:"http://localhost:5000/api/center", //指定服務中心
  center:{ //啟動center,用於服務發現
    port:5000,
    dataFile:'/var/log/m-service.json',
  },
  proxy:{ //啟動proxy,自動處理服務發現,失敗重試
    port:4999,
  },
  services:{ //啟動服務
    port: 5500,
    dir: __dirname,
    names:['dir1'],
  }
});

//localhost:5500/api/dir1/file1/f1?p1=1&p2=2&直接訪問微服務
//localhost:4999/api/dir1/file1/f1?p1=1&p2=2&通過代理訪問微服務
//localhost:5000/api/center/register&查看在線服務

只啟動微服務

// dir2/file2.js
module.exports.f = (console, query, body)=>{
	return {query, body, msg:'success'};
}

// s2.js
let ms = require('m-service');
ms.createApp({
  centers:"http://localhost:5000/api/center", //指定服務中心
  services:{ //啟動服務
    port: 5501,
    dir: __dirname,
    names:['dir2'],
  }
});

現在可以訪問代理直接訪問所有微服務

localhost:4999/api/dir1/file1/f1?p1=1&p2=2&&通過代理訪問微服務
localhost:4999/api/dir2/file1/f1?p1=1&p2=2&&通過代理訪問微服務

開發

git clone https://github.com/yedf/micro-service.git
cd micro-service
cnpm install
sudo cnpm install -g typescript
npm start #啟動微服務的注冊中心、代理、服務名稱為dir1的微服務

啟動另一個微服務dir2

cd example && node s2.js


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM