0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

個人メモ:RPC?

Last updated at Posted at 2019-10-06

(grpc見る前にまず)RPCとは?

RPC ( Remote Procedure Call )
別プロセスの関数起動するため~~の規約

golandでRPC例を作ってみる

RPC例:円の半径を計算する関数を、別の端末での呼び出しを想定

フォルダ構成

1_rpc_CircleArea
|-- 1_server_pkg_rpc
|  -- main.go
|-- 2_client
|  -- main.go

サーバ側:1_server_pkg_rpc/main.go

package main

import (
	"math"
	"net"
	"net/http"
	"net/rpc"
)

type CircleArea struct {}

// (対象)関数名(clientからのリクエスト, clientへのレスポンス) エラー
func (c *CircleArea) CalculateCircleArea(r float32,area *float32)error  {
	*area = math.Pi * r * r // 圆形的面积:π * r * r
	return nil
}

func main() {
	// 1 初期化
	circleArea := new(CircleArea)
	// 2 rpcサービス登録
	_ = rpc.Register(circleArea)
	// 3 関数を httpに登録。httpを通じて、データ転送を実現
	rpc.HandleHTTP()
	// 4 特定のポートで、監視
	listen, _:=net.Listen("tcp", ":8001")
	http.Serve(listen,nil)
}

クライアント側:2_client/main.go

package main

import (
	"fmt"
	"net/rpc"
)

func main() {

	var round float32      // リクエスト用
	var area float32   // レスポンス用
	fmt.Printf("円の半径入力 --> ")
	fmt.Scanln(&round)

	// 1 サーバへ接続
	clent, _ := rpc.DialHTTP("tcp", "localhost:8001")
	//  2 サービスる呼び出し
	//      CircleArea.CalculateCircleArea:サーバ名 (golandで教えてくれないので、間違わないようにする→コピーしよう)
	//      r:計算用の円の半径
	//      &area: 計算後の円の面積
	_ =clent.Call("CircleArea.CalculateCircleArea", round, &area)
	fmt.Println("円の面積:",  area)
}

起動&実行結果

  • サーバ起動:
1_server_pkg_rpc>go run main.go
  • クライアント起動し、結果出力:
2_client>go run main.go

円の半径入力 --> 2
円の面積: 12.566371

0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?