安装 curl
sudo apt install curl
安装 consul
- 官网下载安装包https://www.consul.io/downloads.html
- 安装
#解压
unzip consul**.zip
#得到一个文件consul。
cp consul /usr/local/bin/
#验证
consul
consul agent -dev -client=0.0.0.0
# -client // 对外提供服务改成0.0.0.0
服务注册(dns)
- 先退出consul服务
- 定义服务
#创建配置文件夹
mkdir /etc/consul.d
#定义服务
sudo echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' | sudo tee /etc/consul.d/web.json
#重启consul服务,指定config-dir
consul agent -dev -ui -config-dir /etc/consul.d
服务注册(http api)
- 安装依赖
npm init -y
npm install --save-dev request koa koa-router
- index.js
const request = require('request');
const { networkInterfaces } = require('os');
const getIPAdress = () => {
let interfaces = networkInterfaces();
for (let devName in interfaces) {
let iface = interfaces[devName];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (
alias.family === "IPv4" &&
alias.address !== "127.0.0.1" &&
!alias.internal
) {
return alias.address;
}
}
}
};
const IP = getIPAdress();
let options = {
url: `http://127.0.0.1:8500/v1/agent/service/register`,
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
ID: 'cuic' + "_" + new Date().getTime(),
Name: 'cuic',
Address: IP,
Port: 3000,
Tags: ["activity", "nodejs"],
Check: {
HTTP: `http://${IP}:3000/healthCheck`,
Interval: "10s"
}
})
};
request.put(options, (error, response, body) => {
if (error) {
console.log("reg sendRequest error: ", error);
return;
}
});
- service.js
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/healthCheck', (ctx, next) => {
ctx.response.status = 200;
});
app.use(router.routes());
app.listen(3000);
console.log(`listen port : 3000`);
- 运行命令
node index.js
node service.js
安装 consul-template
#解压
unzip consul**.zip
#得到一个文件consul-template。
cp consul-template /usr/local/bin/
tpl文件
find_address.tpl
{{ key "/hashicorp/street_address" }}
编译(-once代表只编译一次)
consul-template -template "find_address.tpl:hashicorp_address.txt" -once
修改命令
consul kv put hashicorp/street_address "101 2nd St"
consul-template配置nginx.config
consul-template -consul-addr 127.0.0.1:8500 -template "./tmpltest.ctmpl:./result"
网友评论