您好,登錄后才能下訂單哦!
這篇文章主要講解了“Golang原生rpc的原理是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Golang原生rpc的原理是什么”吧!
創建rpc接口,需要幾個條件
方法的類型是可輸出的
方法的本身也是可輸出的
方法必須有兩個參數,必須是輸出類型或者是內建類型
方法的第二個參數是指針類型
方法返回的類型為error
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 three\n", 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: %q\n", 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: %q\n", 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: %q\n", 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 one\n", 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 error\n", 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的原理是什么”的內容了,經過本文的學習后,相信大家對Golang原生rpc的原理是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。