網站首頁 編程語言 正文
創建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 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和其他數據
- 進行調用
原文鏈接:https://juejin.cn/post/7083083938603728903
相關推薦
- 2022-11-29 React?props全面詳細解析_React
- 2022-07-29 Linux文件管理方法介紹_linux shell
- 2022-12-27 詳解Golang中interface接口的原理和使用技巧_Golang
- 2022-04-08 WPF中Style樣式及其觸發器_基礎應用
- 2022-10-05 Ubuntu?Server?20.04?LTS?環境下搭建vim?編輯器Python?IDE的詳細步
- 2023-04-12 Android同步屏障機制sync?barrier實例應用詳解_Android
- 2023-02-01 python多線程、網絡編程、正則表達式詳解_python
- 2022-09-14 Gstreamer基礎知識教程_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支