consul 自动配置工具

2021-04-26 20:01:53 +08:00
 xxjwxc

consult

前言

使用

安装

go get -u github.com/xxjwxc/consult@master

新建一个连接

import (
	"github.com/xxjwxc/consult/consulkv"
)

conf := consulkv.NewConfig()

or

With Options

conf := consulkv.NewConfig(
    consulkv.WithPrefix(prefix),             // consul kv 前缀
    consulkv.WithAddress(address),           // consul 地址
    consulkv.WithAuth(username, password),   // cosul 用户密码
    consulkv.WithToken(token),               // cousl token
    consulkv.WithLoger(loger),               // loger
)

Init

if err := conf.Init();err !=nil {
    return err
}

Put

if err := conf.Put(key, value);err !=nil {
    return err
}

Delete

if err := conf.Delete(key);err !=nil {
    return err
}

Get

// scan
if err := conf.Get(key).Scan(x);err !=nil {
    return err
}

// get float
float := conf.Get(key).Float()

// get float with default
float := conf.Get(key).Float(defaultFloat)

// get int
i := conf.Get(key).Int()

// get int with default
i := conf.Get(key).Int(defaultInt)

... ...

监听

conf.Watch(path, func(r *Result){
    r.Scan(x)
})

停止监听

// stop single watcher
conf.StopWatch(path)

// stop multiple watcher
conf.StopWatch(path1, path2)

// stop all watcher
conf.StopWatch()

通过 tag 自动获取 /自动更新

import (
	"github.com/xxjwxc/consult"
)

type Info struct {
    Port  string  `yaml:"port" consul:"port"` // 端口号
}

var info Info
consult.AutoLoadConfig(conf, &info) //  自动加载

consult.AutoSetConfig(conf, &info, false) // 执行一次自动更新

完整例子


import (
	"fmt"
	"testing"

	"github.com/xxjwxc/consult/consulkv"
    "github.com/xxjwxc/consult"
)

type Config struct {
	MySQLInfo    MysqlDbInfo `yaml:"mysql_info" consul:"mysql_info"`
	Port         string      `yaml:"port" consul:"port"`                   // 端口号
}

// MysqlDbInfo mysql database information. mysql 数据库信息
type MysqlDbInfo struct {
	Host     string `validate:"required" consul:"host"`     // Host. 地址
	Port     int    `validate:"required" consul:"port"`     // Port 端口号
	Username string `validate:"required" consul:"username"` // Username 用户名
	Password string `consul:"password"`                     // Password 密码
	Database string `validate:"required" consul:"database"` // Database 数据库名
	Type     int    // 数据库类型: 0:mysql , 1:sqlite , 2:mssql
}

func main() {
	conf := consulkv.NewConfig(
		consulkv.WithPrefix("service/servername"),      // consul kv prefix
		consulkv.WithAddress("192.155.1.150:8500"), // consul address
	)
	if err := conf.Init(); err != nil {
		mylog.Error(err)
		return
	}

	var config Config
	consult.AutoLoadConfig(conf, &config) //  自动加载
	fmt.Println(config)

	consult.AutoSetConfig(conf, &config, false) // 执行一次更新
	fmt.Println(config)
}

更多:

xxjwxc consult consul

1059 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/773441

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX