欧美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)
	}
	//判斷方法名是否暴漏的,如果方法名不是暴露的,則會(huì)導(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()是不會(huì)發(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è),則會(huì)報(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
}

接收到請求后會(huì)不斷的解析請求 解析請求的兩個(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語言學(xué)習(xí)之條件語句使用詳解

    Go語言學(xué)習(xí)之條件語句使用詳解

    這篇文章主要介紹了Go語言中條件語句的使用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-04-04
  • Go語言中零拷貝的原理與實(shí)現(xiàn)詳解

    Go語言中零拷貝的原理與實(shí)現(xiàn)詳解

    零拷貝是相對于用戶態(tài)來講的,即數(shù)據(jù)在用戶態(tài)不發(fā)生任何拷貝,那么零拷貝的原理是什么,又是如何實(shí)現(xiàn)的呢,下面小編就來和大家詳細(xì)聊聊吧
    2023-08-08
  • 使用Go語言實(shí)現(xiàn)發(fā)送微信群消息

    使用Go語言實(shí)現(xiàn)發(fā)送微信群消息

    這篇文章主要為大家詳細(xì)介紹了如何使用Go語言實(shí)現(xiàn)發(fā)送微信群消息,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • 解決go echo后端處理跨域的兩種操作方式

    解決go echo后端處理跨域的兩種操作方式

    這篇文章主要介紹了解決go echo后端處理跨域的兩種操作方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Go語言JSON編解碼神器之marshal的運(yùn)用

    Go語言JSON編解碼神器之marshal的運(yùn)用

    這篇文章主要為大家詳細(xì)介紹了Go語言中JSON編解碼神器——marshal的運(yùn)用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-09-09
  • 使用go module導(dǎo)入本地包的方法教程詳解

    使用go module導(dǎo)入本地包的方法教程詳解

    go module 將是Go語言默認(rèn)的依賴管理工具。到今天 Go1.14 版本推出之后 Go modules 功能已經(jīng)被正式推薦在生產(chǎn)環(huán)境下使用了。本文重點(diǎn)給大家介紹如何使用 go module 導(dǎo)入本地包,感興趣的朋友一起看看吧
    2020-03-03
  • Golang 如何解析和生成json

    Golang 如何解析和生成json

    這篇文章主要介紹了Golang 如何解析和生成json,幫助大家更好的理解和學(xué)習(xí)golang,感興趣的朋友可以了解下
    2020-09-09
  • 解決Golang在Web開發(fā)時(shí)前端莫名出現(xiàn)的空白換行

    解決Golang在Web開發(fā)時(shí)前端莫名出現(xiàn)的空白換行

    最近在使用Go語言開發(fā)Web時(shí),在前端莫名出現(xiàn)了空白換行,找了網(wǎng)上的一些資料終于找到了解決方法,現(xiàn)在分享給大家,有需要的可以參考。
    2016-08-08
  • Golang實(shí)現(xiàn)基于Redis的可靠延遲隊(duì)列

    Golang實(shí)現(xiàn)基于Redis的可靠延遲隊(duì)列

    redisson?delayqueue可以使用redis的有序集合結(jié)構(gòu)實(shí)現(xiàn)延時(shí)隊(duì)列,遺憾的是go語言社區(qū)中并無類似的庫。不過問題不大,本文將用Go語言實(shí)現(xiàn)這一功能,需要的可以參考一下
    2022-06-06
  • 詳解如何使用Golang操作MongoDB數(shù)據(jù)庫

    詳解如何使用Golang操作MongoDB數(shù)據(jù)庫

    在現(xiàn)代開發(fā)中,數(shù)據(jù)存儲(chǔ)是一個(gè)至關(guān)重要的環(huán)節(jié),MongoDB作為一種NoSQL數(shù)據(jù)庫,提供了強(qiáng)大的功能和靈活的數(shù)據(jù)模型,與Golang的高性能和并發(fā)性能非常契合,本文將探討Golang與MongoDB的完美組合,介紹如何使用Golang操作MongoDB數(shù)據(jù)庫,需要的朋友可以參考下
    2023-11-11

最新評論