gRPC实现简单helloworld

用golang,结合gRPC,实现远程调用,输出 hello world
关于gRPC的安装看《centos7安gRPC》



流程如下:

 1. 编写 .proto文件
 2. 用 protoc 工具生成go代码
 3. 编写 gRPC 服务端
 4. 编写 gRPC 客户端
 5. 运行测试


目录结构如下图示例:

1. 编写proto文件

syntax = "proto3";
// 指定proto版本,有多个版本,3是最新版本,更轻量化,支持更多语言

// 定义包名
package hello;

// 定义请求信息结构
message HelloRequest{
    string name = 1;
}

// 定义响应信息结构
message HelloResponse{
    string message = 1;
}

// 定义Hello服务
service Hello{
    // 定义服务中的方法
    rpc SayHello(HelloRequest)returns(HelloResponse){}
}

2. 生成go文件

protoc -I . --go_out=plugins=grpc:. ./hello.proto

3. 编写rpcServer文件

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	hello "imooc.com/tttt/t-grpc/hello/proto"
	"net"
)

type rpcServer struct{}

// 定义rpc服务的方法
func (s *rpcServer) SayHello(ctx context.Context,
	in *hello.HelloRequest) (*hello.HelloResponse, error) {
	return &hello.HelloResponse{
		Message: "hello " + in.Name,
	}, nil
}

func main() {
	// 新建tcp监听通道
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	// 实例化gRPC server
	server := grpc.NewServer()
	// 注册 server
	hello.RegisterHelloServer(server, &rpcServer{})

	fmt.Println("Listen on localhost:8080")
	// 启动监听
	server.Serve(listener)
}

4. 编写rpcClient文件

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	hello "imooc.com/tttt/t-grpc/hello/proto"
)

func main() {
	// 连接rpc通道
	conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
	if err != nil {
		grpclog.Fatalln(err)
	}
	defer conn.Close()

	// 初始化客户端
	cli := hello.NewHelloClient(conn)

	// 调用方法
	reqBody := &hello.HelloRequest{Name: "world"}
	res, err := cli.SayHello(context.Background(), reqBody)
	if err != nil {
		grpclog.Fatalln(err)
	}

	fmt.Println(res.Message)
}

运行服务端程序,输出如下图

运行客户端程序,输出如下图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值