天天看點

基于go-micro,etcd,gorm,chennel開發的可擴充分布式id生成器微服務

目前實作美團leaf式資料庫自增id和雪花算法(github.com/zheng-ji/goSnowFlake現成輪子),其他方式會持續加入

leaf式資料庫自增id采用channel傳遞,可實作自定義擴充

/*
請求參數:

message RequestGetId {
  repeated int64 work_id = 1;
}

傳回參數:
message ResponseId {
  int64 id = 1;
  bool suc = 2;
  string msg = 3;
}

*/

  "get_type": "sql_auto_increment" // 同過修改配置檔案"get_type" 實作不同方法的切換

           

可以實作自定義id channel個數,僅需要修改配置檔案

"chan_count": 你想要的數量
           

可以通過以下方式建立client

var idCli idProto.IronIdService

func init() {
	reg := etcdv3.NewRegistry(func(op *registry.Options) {
		op.Addrs = []string{"192.168.50.15:2379"}
		etcdv3.Auth("edu", "123456")
	})
	service := micro.NewService(
		micro.Registry(reg),
		micro.Name("go.micro.service.idGetter"),
	)
	service.Init()
	rpcCli := service.Client()
	idCli = idProto.NewIronIdService("service.iron_id.server", rpcCli)
}
           

資料庫自增方式不支援一個服務同時生成多個不同的業務id,可以通過設定不同配置檔案,開啟多個服務來實作,通過servername來區配置設定置檔案格式如下

{
  "server_name": "service.iron_id.server",

  "etcd_addr": [
    "192.168.50.15:2379"
  ],
  "etcd_user": "edu",
  "etcd_pwd": "123456",

  "sql_addr": "192.168.50.15:33306",
  "sql_user": "edu",
  "sql_pass": "123456",
  "db_name": "iron_id",
  "sql_options": "?charset=utf8&parseTime=True&loc=Local",
  "max_conn": 20,
  "idle_conn": 10,
  "debug": false,

  "log_path": "/Users/huangxuchen/goproject/src/iron_id/log/",
  "log_file_name": "id_log.log",

  "step": 1000,
  "biz_tag": "pay_ordertag",
  "desc": "pay_ordertag_id",
  "chan_count": 3,
  "get_type": "sql_auto_increment" // or "snow_flake"
}
           

啟動

// 1、可以通過修改idserver.go中 init函數flag.StringVar(&configFile, "cf", "./conf/config.json", "press config.json path"),編譯即可啟動
func init() {
	var configFile string
	flag.StringVar(&configFile, "cf", "./conf/config.json", "press config.json path")
	flag.Parse()
	// initialize conf
	conf.InitConfig(configFile)
}
// 2、通過指令行[-cf]啟動
// e.g: ./service -cf=config_file_path 

           

繼續閱讀