欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang原生rpc(rpc服務(wù)端源碼解讀)

 更新時(shí)間:2022年04月06日 17:23:16   作者:鹿灝楷silves  
本文主要介紹了Golang原生rpc(rpc服務(wù)端源碼解讀),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

創(chuàng)建rpc接口,需要幾個(gè)條件

  • 方法的類型是可輸出的
  • 方法的本身也是可輸出的
  • 方法必須有兩個(gè)參數(shù),必須是輸出類型或者是內(nèi)建類型
  • 方法的第二個(gè)參數(shù)是指針類型
  • 方法返回的類型為error

rpc服務(wù)原理分析

server端

  • 服務(wù)注冊
  • 處理網(wǎng)絡(luò)調(diào)用

服務(wù)注冊 通過反射處理,將接口存入到map中,進(jìn)行調(diào)用 注冊服務(wù)兩個(gè)方法

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

注冊方法的源代碼解讀 首先,無論是Register還是RegisterName底層代碼都是調(diào)用register方法,進(jìn)行服務(wù)注冊。 server.go register方法解讀

func (server *Server) register(rcvr interface{}, name string, useName bool) error {
	//創(chuàng)建一個(gè)service實(shí)例
	s := new(service)
	s.typ = reflect.TypeOf(rcvr)
	s.rcvr = reflect.ValueOf(rcvr)
	sname := reflect.Indirect(s.rcvr).Type().Name()
	//如果服務(wù)名為空,則使用默認(rèn)的服務(wù)名
	if useName {
		sname = name
	}
	if sname == "" {
		s := "rpc.Register: no service name for type " + s.typ.String()
		log.Print(s)
		return errors.New(s)
	}
	//判斷方法名是否暴漏的,如果方法名不是暴露的,則會導(dǎo)致調(diào)用不成功,所以返回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
	//調(diào)用suitableMethods函數(shù),進(jìn)行返回接口,在suitableMethods中判斷方法是否符合作為rpc接口的條件,如果符合,則進(jìn)行添加到services中
	s.method = suitableMethods(s.typ, true)

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

		// To help the user, see if a pointer receiver would work.
		//如果方法綁定到結(jié)構(gòu)體的地址上,使用reflect.TypeOf()是不會發(fā)現(xiàn)方法的,所以也要進(jìn)行查找綁定到結(jié)構(gòu)體地址上的方法
		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)
	}
	//判斷服務(wù)接口是否已經(jīng)注冊。
	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 {
	//創(chuàng)建一個(gè)方法的切片
	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.
		//如果傳入的參數(shù),不為三個(gè),則會報(bào)錯(cuò),這里為什么是三個(gè)?
		//golang方法體中默認(rèn)傳入結(jié)構(gòu)體實(shí)例,所以request,*response,結(jié)構(gòu)體實(shí)例一共三個(gè)參數(shù)
		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.
		//判斷第二個(gè)參數(shù)是否為指針,如果不為指針,則返回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.
		//返回結(jié)果是否為一個(gè)值,且為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
}

接收到請求后會不斷的解析請求 解析請求的兩個(gè)方法 readRequestHeader

func (server *Server) readRequestHeader(codec ServerCodec) (svc *service, mtype *methodType, req *Request, keepReading bool, err error) {
	// Grab the request header.
	//接收到請求,對請求進(jìn)行編碼
	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
//編碼后的請求,進(jìn)行間隔,所以只要進(jìn)行將.的左右兩邊的數(shù)據(jù)進(jìn)行分割,就能解碼
	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)
	//獲取到注冊服務(wù)時(shí),注冊的接口
	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)
//調(diào)用上面的readRequestHeader方法,進(jìn)行解碼,并返返回接口數(shù)據(jù)
	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()方法,進(jìn)行指向結(jié)構(gòu)體
	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.
	//調(diào)用call方法,并將參數(shù)轉(zhuǎn)化為valueof型參數(shù),
	returnValues := function.Call([]reflect.Value{s.rcvr, argv, replyv})
	// The return value for the method is an error.
	//將返回的error進(jìn)行讀取,轉(zhuǎn)化為interface{}型
	errInter := returnValues[0].Interface()
	errmsg := ""
	if errInter != nil {
	//將error進(jìn)行斷言
		errmsg = errInter.(error).Error()
	}
	server.sendResponse(sending, req, replyv.Interface(), codec, errmsg)
	server.freeRequest(req)
}

注冊的大概流程

  • 根據(jù)反射,進(jìn)行接口的獲取
  • 使用方法判斷接口是否符合作為rpc接口的規(guī)范(有兩個(gè)參數(shù),第二個(gè)參數(shù)為指針,返回一個(gè)參數(shù)error)
  • 如果不符合規(guī)范,將返回error,符合規(guī)范,將存入map,進(jìn)行提供調(diào)用

接收請求的大概流程

  • 首先,不斷的接收數(shù)據(jù)流,并進(jìn)行解碼,解碼之后為data.data,所以我們需要使用 . 作為分隔符,進(jìn)行數(shù)據(jù)的截切和讀取
  • 將讀取的數(shù)據(jù)在注冊的map中進(jìn)行查找,如果查找到,返回相關(guān)的service和其他數(shù)據(jù)
  • 進(jìn)行調(diào)用

到此這篇關(guān)于Golang原生rpc(rpc服務(wù)端源碼解讀)的文章就介紹到這了,更多相關(guān)Golang原生rpc內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Go語言中的多種測試方法

    Go語言中的多種測試方法

    本文主要介紹了Go語言中的多種測試方法,包括單元測試、表格驅(qū)動測試、基準(zhǔn)測試等,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-07-07
  • go語言if/else語句簡單用法示例

    go語言if/else語句簡單用法示例

    這篇文章主要介紹了go語言if/else語句用法,結(jié)合實(shí)例形式分析了go語言if else語句的判定與流程控制技巧,需要的朋友可以參考下
    2016-05-05
  • Go語言中異步回調(diào)的實(shí)現(xiàn)

    Go語言中異步回調(diào)的實(shí)現(xiàn)

    異步回調(diào)是一種常見的編程模式,用于處理并發(fā)任務(wù)和事件驅(qū)動的編程,本文主要介紹了Go語言中異步回調(diào)的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2025-05-05
  • go 判斷兩個(gè) slice/struct/map 是否相等的實(shí)例

    go 判斷兩個(gè) slice/struct/map 是否相等的實(shí)例

    這篇文章主要介紹了go 判斷兩個(gè) slice/struct/map 是否相等的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Go??import _ 下劃線使用

    Go??import _ 下劃線使用

    這篇文章主要為大家介紹了Go??import下劃線_使用小技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • 使用Golang?Validator包實(shí)現(xiàn)數(shù)據(jù)驗(yàn)證詳解

    使用Golang?Validator包實(shí)現(xiàn)數(shù)據(jù)驗(yàn)證詳解

    在開發(fā)過程中,數(shù)據(jù)驗(yàn)證是一個(gè)非常重要的環(huán)節(jié),而golang中的Validator包是一個(gè)非常常用和強(qiáng)大的數(shù)據(jù)驗(yàn)證工具,提供了簡單易用的API和豐富的驗(yàn)證規(guī)則,下面我們就來看看Validator包的具體使用吧
    2023-12-12
  • go進(jìn)行http請求偶發(fā)EOF問題分析

    go進(jìn)行http請求偶發(fā)EOF問題分析

    go使用連接池進(jìn)行http請求,一般都能請求成功,但偶然會出現(xiàn)請求失敗返回EOF錯(cuò)誤的情況,本文主要來帶大家分析一下為什么會出現(xiàn)這樣的問題并提供解決方法,需要的可以參考下
    2025-01-01
  • go中any類型的使用詳解

    go中any類型的使用詳解

    Go1.18新增any類型,替代interface{}用于表示未知類型,提升類型安全和代碼清晰度,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-08-08
  • Golang?Gin框架獲取請求參數(shù)的幾種常見方式

    Golang?Gin框架獲取請求參數(shù)的幾種常見方式

    在我們平常添加路由處理函數(shù)之后,就可以在路由處理函數(shù)中編寫業(yè)務(wù)處理代碼了,但在此之前我們往往需要獲取請求參數(shù),本文就詳細(xì)的講解下gin獲取請求參數(shù)常見的幾種方式,需要的朋友可以參考下
    2024-02-02
  • 快速掌握Go語言正/反向代理

    快速掌握Go語言正/反向代理

    這篇文章主要介紹了快速掌握Go語言正/反向代理的相關(guān)資料,需要的朋友可以參考下
    2022-11-11

最新評論