Stay Hungry,Stay Foolish!

Discover services with Consul

Discover services with Consul

https://www.consul.io/use-cases/discover-services

Use Consul as a centralized registry that discovers, tracks, and monitors your services. Consul can be your single source of truth for cataloging and maintaining a record of all your services.

 

https://github.com/mhdbs/consul-python-microservices/blob/master/microservice_sample_1/app.py

复制代码
import json
from time import sleep
import socket
import consul
import requests
from flask import Flask
app = Flask(__name__)

CONSUL_URL = 'http://consul:8500'
CONSUL_KEY = 'microservice_1'

ADDRESS = socket.gethostbyname(socket.gethostname())
PORT = 9000

@app.route('/')
def home():
    return 'Hello World from {address}'.format(address=ADDRESS)


@app.route('/health')
def hello_world():
    data = {
        'status': 'healthy'
    }
    return json.dumps(data)

@app.route('/register')
def register():
    url = CONSUL_URL + '/v1/agent/service/register'
    data = {
        'Name': 'microservice_1',
        'Tags': ['flask_app_python'],
        'Address': ADDRESS,
        'Port': 9000,
        'Check': {
            'http': 'http://{address}:{port}/health'.format(address=ADDRESS, port=PORT),
            'interval': '10s'
        }
    }
    app.logger.debug('Reg: ', data)
    res = requests.put(
        url,
        data=json.dumps(data)
    )
    c = consul.Consul()
    index = None 
    index, data = c.kv.get(CONSUL_KEY, index=index)
    app.logger.debug("KV Value : ",data['Value'])
    return res.text


if __name__ == '__main__':
    sleep(8)
    try:
        app.logger.debug(register())
    except:
        app.logger.debug('exception happend')
        pass
    app.run(debug=True, host="0.0.0.0", port=PORT)
复制代码

 

 

Demo

https://github.com/fanqingsong/consul-template-docker-compose/tree/master

https://github.com/fanqingsong/consul_demo

 

posted @   lightsong  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
历史上的今天:
2023-04-14 B. Two Sets
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示