RPCX分布式服务框架主要致力于提供高性能和透明化的RPC远程服务调用。
服务注册中心
RPCX的服务注册中心主要负责维护系统服务信息、服务提供方访问地址及可用状态。
服务注册中心和其他角色关系:
- 服务提供方定期向注册中心“发送心跳”,表示自己在线可用。
- 服务消费方向注册中心查询服务提供方信息。
- 注册中心通知服务消费方服务提供方在线、离线状态。
服务注册中心抽象
type ServiceDiscovery interface {
GetServices() []*KVPair
WatchService() chan []*KVPair
RemoveWatcher(ch chan []*KVPair)
Clone(servicePath string) ServiceDiscovery
Close()
}
GetServices:获取所有服务提供方信息。
WatchService:订阅服务提供方状态变化。
RemoveWatcher:取消订阅。
Zookeeper注册中心实现
type ZookeeperDiscovery struct {
pairs []*KVPair //服务提供方列表
chans []chan []*KVPair //用于对外通知的channel,提供方变更后发送信息到该通道
}
订阅服务提供方变更信息
func (d *ZookeeperDiscovery) WatchService() chan []*KVPair {
ch := make(chan []*KVPair, 10)
d.chans = append(d.chans, ch) //增加一个通知通道
return ch
}
服务提供方变更通知
func (d *ZookeeperDiscovery) watch()
for {
select {
case <-d.stopCh:
log.Info("discovery has been closed")
return
case ps := <-c:
if ps == nil {
break readChanges
}
var pairs []*KVPair // latest servers
for _, p := range ps {
pairs = append(pairs, &KVPair{Key: p.Key, Value: string(p.Value)})
}
d.pairs = pairs
//服务提供方有变更时,通知所有订阅者
for _, ch := range d.chans {
ch := ch
go func() {
defer func() {
if r := recover(); r != nil {
}
}()
select {
case ch <- pairs:
case <-time.After(time.Minute):
log.Warn("chan is full and new change has been dropped")
}
}()
}
}
}
系列文章