go和python解码msgpack不一致

基于ectd实现go的服务注册

妙音 posted @ 2021年11月27日 18:42 in golang with tags etcd , 264 阅读
 

描述

 
    基于etcd实现go程序的服务注册,所看的学习资料均比较简单, 实际中要经过反复测试,自己写了一个先用着,有坑再填.
 

需求

 
1. 注册一个服务: 程序启动时
2. 注销服务: a. 程序异常退出时, 自动注销, 有5秒TTL延迟; b. 调用Stop()接口主动注销
3. 健壮性: a.ectd单节点重启, ectd本身支持; b. etcd全部重启后, 能够恢复正常
4. key的格式: 前缀/ip/pid
5. value: 字符串.(可以先转为json, 再转string)
 
 

创建etcd客户端

 

	
//不是重点, 摘要如下代码
 
cli, err := clientv3.New(clientv3.Config{
Endpoints:   ec.Endpoints,
DialTimeout: 5 * time.Second,
})
if err != nil {
log.Fatal(err)
}
 

创建Service对象, 包含服务注册

 
package main

import (
	"context"
	"errors"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/clientv3util"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"net"
	"os"
	"strings"
	"sync"
	"test/etcd"
	"time"
)


var IP string
var PID int


func init(){
	//日志
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoder := zapcore.NewConsoleEncoder(encoderConfig)

	//创建
	var clevel zapcore.Level
	clevel.Set("debug")
	log := zap.New(zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), clevel))
	//设为全局
	zap.ReplaceGlobals(log)

	//
	IP, _ = GetLocalIP()
	PID = os.Getpid()
}

func GetLocalIP() (string,error){
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		zap.S().Warn(err)
		return "", err
	}
	for _, addr := range addrs{
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback(){
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}
	return "", errors.New("unable to determine local ip")
}


func RegisterService(endpoints []string, key string, value string) *Service{
	s := &Service{
		Value: value,
		endpoints: endpoints,
	}

	s.TTL = 5
	s.Key = strings.Join([]string{key, IP, fmt.Sprintf("%d", PID)}, "/")

	s.init()

	return s
}


type Service struct{
	Key          	string		//key 格式: /前缀/名称/ip/pid
	Value           string		//存放信息
	endpoints    	[]string	//etcd地址
	//心跳
	IsAlive      	bool		//是否存活
	heartCancel 	context.CancelFunc	//取消心跳
	//租约
	TTL             int64		//租约(秒)
	grant			*clientv3.LeaseGrantResponse	//租约
}


func (s *Service) init(){
	//启用etcd连接
	etcd.EnableEtcd(s.endpoints)

	//心跳
	go s.start()
}

func (s *Service) start(){
	defer func(){
		s.IsAlive = false

		//注销服务
		s.deleteService()
		//关闭续约(如果共用会误关?)
		etcd.Cli().Lease.Close()
	}()

	var aliveRsp <-chan *clientv3.LeaseKeepAliveResponse
	var err error
	var ctx context.Context
	for{
		if !s.IsAlive{
			// 注册服务
			s.registerService()

			// 续期信号chan
			aliveRsp, err = etcd.Cli().KeepAlive(context.TODO(), s.grant.ID)
			if err != nil{
				zap.S().Warn(err)
			}

			ctx, s.heartCancel = context.WithCancel(context.Background())
		}

		// 监听心跳信号
		select{
		case rsp := <- aliveRsp:
            //异常时无信号
			if rsp ==nil{
				s.IsAlive = false
				zap.S().Info("service missing signal")
				time.Sleep(time.Second*5)
				continue
			}

			s.IsAlive = true
			zap.S().Debugf("service alive %v", rsp.ID)
		case <- ctx.Done():
			zap.S().Info("service stopping")
			return
		}
	}
}

//停止

func (s *Service) Stop(){
	s.heartCancel()
}
 
[佛說大乘無量壽莊嚴清淨平等覺經pdf](http://www.sxjy360.top/page-download/)
[净土大经科注2014-doc](http://www.sxjy360.top/page-download/)
[此生必看的科学实验-水知道答案](http://www.sxjy360.top/page-download/)
[印光大师十念法(胡小林主讲第1集)](http://www.sxjy360.top/page-download/)
 
Avatar_small
SBI Account Transfer 说:
2021年11月29日 21:02

State Bank of India has offered the facility to change or transfer their branch to another branch online in a simple way using the YONO SBI app, YONO Lite app, and SBI Online services. Any customer of SBI who needs to transfer to another branch can follow this guide to change their branch online & offline. That’s it you have submitted a service request successfully to change or transfer your branch using a mobile banking facility. SBI Account Transfer to Another Branch You will get an SMS message against the service request with complete information along with the status. If one does not know the account number and the IFSC code number of any person and one want to transfer the money, this is the best way to do so. Though there is a limit per day for the UPI transactions, it is the best method if one wants to transfer a small amount.

Avatar_small
YOLO 说:
2021年12月02日 19:49

slotok Just pick up the phone, whether the system

Avatar_small
AAA 说:
2021年12月23日 16:52

You have mentioned very interesting details ! ps decent web site . 안전놀이터

Avatar_small
building la-perla 说:
2022年1月07日 20:55

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks

Avatar_small
Digital_Zone 说:
2022年1月15日 20:53

Good website! I truly love how it is easy on my eyes it is. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which may do the trick? Have a great day! Zonnepanelen Halle

Avatar_small
Digital_Zone 说:
2022年1月15日 20:53

Thank you for some other informative website. The place else may just I get that kind of information written in such a perfect method? I have a venture that I am simply now running on, and I’ve been at the glance out for such info. Zonnepanelen

Avatar_small
Digital_Zone 说:
2022年1月15日 20:54

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! Werking zonnepanelen

Avatar_small
Digital_Zone 说:
2022年1月15日 20:54

Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though. Warmtepomp

Avatar_small
Digital_Zone 说:
2022年1月15日 21:25

Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. Zonnepanelen Haacht

Avatar_small
Digital_Zone 说:
2022年1月15日 21:30

Great job here on _______ I read a lot of blog posts, but I never heard a topic like this. I Love this topic you made about the blogger's bucket list. Very resourceful. Zonnepanelen installateur

Avatar_small
Digital_Zone 说:
2022年1月15日 21:33

Thanks a lot for sharing this excellent info! I am looking forward to seeing more posts by you as soon as possible! I have judged that you do not compromise on quality. Zonnepanelen Limburg

Avatar_small
Digital_Zone 说:
2022年1月15日 21:37

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. Warmtepomp prijs

Avatar_small
Digital_Zone 说:
2022年1月15日 21:41

Awesome article! I want people to know just how good this information is in your article. It’s interesting, compelling content. Your views are much like my own concerning this subject. Zonnepanelen Vlaams-Brabant

Avatar_small
Digital_Zone 说:
2022年1月15日 21:44

I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. Zonnepanelen Boutersem

Avatar_small
Digital_Zone 说:
2022年1月15日 21:47

I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing. Warmtepomp premies

Avatar_small
Digital_Zone 说:
2022年1月15日 21:50

You have performed a great job on this article. It’s very precise and highly qualitative. You have even managed to make it readable and easy to read. You have some real writing talent. Thank you so much. Zonnepanelen Diest

Avatar_small
Digital_Zone 说:
2022年1月15日 21:54

Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find so many useful info here in the post, we need work out more techniques in this regard, thanks for sharing. Zonnepanelen Heist-op-den-Berg

Avatar_small
Digital_Zone 说:
2022年1月15日 21:57

nice post, keep up with this interesting work. It really is good to know that this topic is being covered also on this web site so cheers for taking time to discuss this! Zonnepanelen Dilbeek

Avatar_small
Digital_Zone 说:
2022年1月15日 22:01

I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. Zonnepanelen Grobbendonk

Avatar_small
Digital_Zone 说:
2022年1月15日 22:04

Someone Sometimes with visits your blog regularly and recommended it in my experience to read as well. The way of writing is excellent and also the content is top-notch. Thanks for that insight you provide the readers! Zonnepanelen Drogenbos

Avatar_small
Digital_Zone 说:
2022年1月15日 22:08

What a thrilling post, you have pointed out some excellent points, I as well believe this is a superb website. I have planned to visit it again and again. Zonnepanelen Geel

Avatar_small
Digital_Zone 说:
2022年1月15日 22:11

I am unable to read articles online very often, but I’m glad I did today. This is very well written and your points are well-expressed. Please, don’t ever stop writing. Zonnepanelen Galmaarden

Avatar_small
Digital_Zone 说:
2022年1月15日 22:14

It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work and skill. Thanks. Zonnepanelen Geetbets

Avatar_small
Digital_Zone 说:
2022年1月15日 22:17

Only strive to mention one's content can be as incredible. This clarity with your post is superb! Thanks a lot, hundreds of along with you should go on the pleasurable get the job done. Zonnepanelen Essen

Avatar_small
Digital_Zone 说:
2022年1月15日 22:21

I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article... Zonnepanelen Glabbeek

Avatar_small
Digital_Zone 说:
2022年1月15日 22:24

Wow, What an Outstanding post. I found this too much informatics. It is what I was seeking for. I would like to recommend you that please keep sharing such type of info.If possible, Thanks. Zonnepanelen Edegem

Avatar_small
Digital_Zone 说:
2022年1月15日 22:27

You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. Zonnepanelen Gooik

Avatar_small
Digital_Zone 说:
2022年1月15日 22:31

Superior post, keep up with this exceptional work. It's nice to know that this topic is being also covered on this web site so cheers for taking the time to discuss this! Thanks again and again! Zonnepanelen Duffel

Avatar_small
Digital_Zone 说:
2022年1月15日 22:36

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Zonnepanelen Grimbergen

Avatar_small
Digital_Zone 说:
2022年1月18日 19:09 This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: คาสิโน
Avatar_small
Digital_Zone 说:
2022年1月18日 19:24

What a thrilling post, you have pointed out some excellent points, I as well believe this is a superb website. I have planned to visit it again and again. generic cialis

Avatar_small
panel systems 说:
2022年1月22日 17:02

It's a great pleasure reading your post. It's full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.

Avatar_small
dysport 说:
2022年1月26日 03:23

I really appreciate this wonderful post that you have provided for us. I assure you this would be beneficial for most people.

Avatar_small
Digital_Zone 说:
2022年1月28日 05:05 Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. tehdit suçu

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter