首頁 > 軟體

Golang原生rpc(rpc伺服器端原始碼解讀)

2022-04-06 19:00:12

建立rpc介面,需要幾個條件

  • 方法的型別是可輸出的
  • 方法的本身也是可輸出的
  • 方法必須有兩個引數,必須是輸出型別或者是內建型別
  • 方法的第二個引數是指標型別
  • 方法返回的型別為error

rpc服務原理分析

server端

  • 服務註冊
  • 處理網路呼叫

服務註冊 通過反射處理,將介面存入到map中,進行呼叫 註冊服務兩個方法

func Register (rcvr interface{}) error {}
func RegisterName (rcvr interface{} , name string) error {}
//指定註冊的名稱

註冊方法的原始碼解讀 首先,無論是Register還是RegisterName底層程式碼都是呼叫register方法,進行服務註冊。 server.go register方法解讀

func (server *Server) register(rcvr interface{}, name string, useName bool) error {
	//建立一個service範例
	s := new(service)
	s.typ = reflect.TypeOf(rcvr)
	s.rcvr = reflect.ValueOf(rcvr)
	sname := reflect.Indirect(s.rcvr).Type().Name()
	//如果服務名為空,則使用預設的服務名
	if useName {
		sname = name
	}
	if sname == "" {
		s := "rpc.Register: no service name for type " + s.typ.String()
		log.Print(s)
		return errors.New(s)
	}
	//判斷方法名是否暴漏的,如果方法名不是暴露的,則會導致呼叫不成功,所以返回false
	if !token.IsExported(sname) && !useName {
		s := "rpc.Register: type " + sname + " is not exported"
		log.Print(s)
		return errors.New(s)
	}
	s.name = sname

	// Install the methods
	//呼叫suitableMethods函數,進行返回介面,在suitableMethods中判斷方法是否符合作為rpc介面的條件,如果符合,則進行新增到services中
	s.method = suitableMethods(s.typ, true)

	if len(s.method) == 0 {
		str := ""

		// To help the user, see if a pointer receiver would work.
		//如果方法系結到結構體的地址上,使用reflect.TypeOf()是不會發現方法的,所以也要進行查詢繫結到結構體地址上的方法
		method := suitableMethods(reflect.PtrTo(s.typ), false)
		if len(method) != 0 {
			str = "rpc.Register: type " + sname + " has no exported methods of suitable type (hint: pass a pointer to value of that type)"
		} else {
			str = "rpc.Register: type " + sname + " has no exported methods of suitable type"
		}
		log.Print(str)
		return errors.New(str)
	}
	//判斷服務介面是否已經註冊。
	if _, dup := server.serviceMap.LoadOrStore(sname, s); dup {
		return errors.New("rpc: service already defined: " + sname)
	}
	return nil
}

suitableMethod方法解讀

func suitableMethods(typ reflect.Type, reportErr bool) map[string]*methodType {
	//建立一個方法的切片
	methods := make(map[string]*methodType)
	for m := 0; m < typ.NumMethod(); m++ {
		method := typ.Method(m)
		mtype := method.Type
		mname := method.Name
		// Method must be exported.
		if method.PkgPath != "" {
			continue
		}
		// Method needs three ins: receiver, *args, *reply.
		//如果傳入的引數,不為三個,則會報錯,這裡為什麼是三個?
		//golang方法體中預設傳入結構體範例,所以request,*response,結構體範例一共三個引數
		if mtype.NumIn() != 3 {
			if reportErr {
				log.Printf("rpc.Register: method %q has %d input parameters; needs exactly threen", mname, mtype.NumIn())
			}
			continue
		}
		// First arg need not be a pointer.
		argType := mtype.In(1)
		if !isExportedOrBuiltinType(argType) {
			if reportErr {
				log.Printf("rpc.Register: argument type of method %q is not exported: %qn", mname, argType)
			}
			continue
		}
		// Second arg must be a pointer.
		//判斷第二個引數是否為指標,如果不為指標,則返回false。
		replyType := mtype.In(2)
		if replyType.Kind() != reflect.Ptr {
			if reportErr {
				log.Printf("rpc.Register: reply type of method %q is not a pointer: %qn", mname, replyType)
			}
			continue
		}
		// Reply type must be exported.
		if !isExportedOrBuiltinType(replyType) {
			if reportErr {
				log.Printf("rpc.Register: reply type of method %q is not exported: %qn", mname, replyType)
			}
			continue
		}
		// Method needs one out.
		//返回結果是否為一個值,且為error
		if mtype.NumOut() != 1 {
			if reportErr {
				log.Printf("rpc.Register: method %q has %d output parameters; needs exactly onen", mname, mtype.NumOut())
			}
			continue
		}
		// The return type of the method must be error.
		if returnType := mtype.Out(0); returnType != typeOfError {
			if reportErr {
				log.Printf("rpc.Register: return type of method %q is %q, must be errorn", mname, returnType)
			}
			continue
		}
		//將介面加入service
		methods[mname] = &methodType{method: method, ArgType: argType, ReplyType: replyType}
	}
	return methods
}

接收到請求後會不斷的解析請求 解析請求的兩個方法 readRequestHeader

func (server *Server) readRequestHeader(codec ServerCodec) (svc *service, mtype *methodType, req *Request, keepReading bool, err error) {
	// Grab the request header.
	//接收到請求,對請求進行編碼
	req = server.getRequest()
	err = codec.ReadRequestHeader(req)
	if err != nil {
		req = nil
		if err == io.EOF || err == io.ErrUnexpectedEOF {
			return
		}
		err = errors.New("rpc: server cannot decode request: " + err.Error())
		return
	}

	// We read the header successfully. If we see an error now,
	// we can still recover and move on to the next request.
	keepReading = true
//編碼後的請求,進行間隔,所以只要進行將.的左右兩邊的資料進行分割,就能解碼
	dot := strings.LastIndex(req.ServiceMethod, ".")
	if dot < 0 {
		err = errors.New("rpc: service/method request ill-formed: " + req.ServiceMethod)
		return
	}
	serviceName := req.ServiceMethod[:dot]
	methodName := req.ServiceMethod[dot+1:]

	// Look up the request.
	svci, ok := server.serviceMap.Load(serviceName)
	if !ok {
		err = errors.New("rpc: can't find service " + req.ServiceMethod)
		return
	}
	svc = svci.(*service)
	//獲取到註冊服務時,註冊的介面
	mtype = svc.method[methodName]
	if mtype == nil {
		err = errors.New("rpc: can't find method " + req.ServiceMethod)
	}
	return
}

readRequest方法

func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *methodType, req *Request, argv, replyv reflect.Value, keepReading bool, err error) {
	service, mtype, req, keepReading, err = server.readRequestHeader(codec)
//呼叫上面的readRequestHeader方法,進行解碼,並返返回介面資料
	if err != nil {
		if !keepReading {
			return
		}
		// discard body
		codec.ReadRequestBody(nil)
		return
	}

	// Decode the argument value.
	argIsValue := false // if true, need to indirect before calling.
	//判斷傳擦是否為指標,如果為指標,需要使用Elem()方法,進行指向結構體
	if mtype.ArgType.Kind() == reflect.Ptr {
		argv = reflect.New(mtype.ArgType.Elem())
	} else {
		argv = reflect.New(mtype.ArgType)
		argIsValue = true
	}
	// argv guaranteed to be a pointer now.
	if err = codec.ReadRequestBody(argv.Interface()); err != nil {
		return
	}
	if argIsValue {
		argv = argv.Elem()
	}

	replyv = reflect.New(mtype.ReplyType.Elem())

	switch mtype.ReplyType.Elem().Kind() {
	case reflect.Map:
		replyv.Elem().Set(reflect.MakeMap(mtype.ReplyType.Elem()))
	case reflect.Slice:
		replyv.Elem().Set(reflect.MakeSlice(mtype.ReplyType.Elem(), 0, 0))
	}
	return
}

call方法

func (s *service) call(server *Server, sending *sync.Mutex, wg *sync.WaitGroup, mtype *methodType, req *Request, argv, replyv reflect.Value, codec ServerCodec) {
	if wg != nil {
		defer wg.Done()
	}
	mtype.Lock()
	mtype.numCalls++
	mtype.Unlock()
	function := mtype.method.Func
	// Invoke the method, providing a new value for the reply.
	//呼叫call方法,並將引數轉化為valueof型引數,
	returnValues := function.Call([]reflect.Value{s.rcvr, argv, replyv})
	// The return value for the method is an error.
	//將返回的error進行讀取,轉化為interface{}型
	errInter := returnValues[0].Interface()
	errmsg := ""
	if errInter != nil {
	//將error進行斷言
		errmsg = errInter.(error).Error()
	}
	server.sendResponse(sending, req, replyv.Interface(), codec, errmsg)
	server.freeRequest(req)
}

註冊的大概流程

  • 根據反射,進行介面的獲取
  • 使用方法判斷介面是否符合作為rpc介面的規範(有兩個引數,第二個引數為指標,返回一個引數error)
  • 如果不符合規範,將返回error,符合規範,將存入map,進行提供呼叫

接收請求的大概流程

  • 首先,不斷的接收資料流,並進行解碼,解碼之後為data.data,所以我們需要使用 . 作為分隔符,進行資料的截切和讀取
  • 將讀取的資料在註冊的map中進行查詢,如果查詢到,返回相關的service和其他資料
  • 進行呼叫

到此這篇關於Golang原生rpc(rpc伺服器端原始碼解讀)的文章就介紹到這了,更多相關Golang原生rpc內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com