Kitex 元信息傳遞擴展

2022-04-27 10:41 更新

元信息傳遞擴展

元信息透傳是基于傳輸協(xié)議透傳一些額外的 RPC 信息給下游,同時讀取傳輸協(xié)議中上游透傳的信息,透傳字段需結(jié)合內(nèi)部的治理能力,建議使用者自行擴展實現(xiàn)。

接口定義

// MetaHandler reads or writes metadata through certain protocol.
// The protocol will be a thrift.TProtocol usually.
type MetaHandler interface {
	WriteMeta(ctx context.Context, msg Message) (context.Context, error)
	ReadMeta(ctx context.Context, msg Message) (context.Context, error)
}

擴展示例

  • ClientMetaHandler

package transmeta

var	ClientTTHeaderHandler remote.MetaHandler = &clientTTHeaderHandler{}

// clientTTHeaderHandler implement remote.MetaHandler
type clientTTHeaderHandler struct{}

// WriteMeta of clientTTHeaderHandler writes headers of TTHeader protocol to transport
func (ch *clientTTHeaderHandler) WriteMeta(ctx context.Context, msg remote.Message) (context.Context, error) {
	ri := msg.RPCInfo()
	transInfo := msg.TransInfo()

	hd := map[uint16]string{
		transmeta.FromService:    ri.From().ServiceName(),
		transmeta.FromIDC:        ri.From().DefaultTag(consts.IDC, ""),
		transmeta.FromMethod:     ri.From().Method(),
		transmeta.ToService:      ri.To().ServiceName(),
		transmeta.ToMethod:       ri.To().Method(),
		transmeta.MsgType:        strconv.Itoa(int(msg.MessageType())),
	}
	transInfo.PutTransIntInfo(hd)

	if metainfo.HasMetaInfo(ctx) {
		hd := make(map[string]string)
		metainfo.SaveMetaInfoToMap(ctx, hd)
		transInfo.PutTransStrInfo(hd)
	}
	return ctx, nil
}

// ReadMeta of clientTTHeaderHandler reads headers of TTHeader protocol from transport
func (ch *clientTTHeaderHandler) ReadMeta(ctx context.Context, msg remote.Message) (context.Context, error) {
	ri := msg.RPCInfo()
	remote := remoteinfo.AsRemoteInfo(ri.To())
	if remote == nil {
		return ctx, nil
	}

	transInfo := msg.TransInfo()
	strInfo := transInfo.TransStrInfo()
	ad := strInfo[transmeta.HeaderTransRemoteAddr]
	if len(ad) > 0 {
		// when proxy case to get the actual remote address
		_ = remote.SetRemoteAddr(utils.NewNetAddr("tcp", ad))
	}
	return ctx, nil
}

  • 添加該 ClientMetaHandler

cli, err := xxxservice.NewClient(targetService, client.WithMetaHandler(transmeta.ClientTTHeaderHandler))


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號