java golang 服务端_gprc-java与golang分别实现服务端,客户端,跨语言通信(二.golang实现)...

1.编译器protoc, 下载地址:https://github.com/protocolbuffers/protobuf/releases  (下载对应的版本, 解压后放到go的bin中)

2.安装golang扩展, go get -u github.com/golang/protobuf/protoc-gen-go

3.grpc库, git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/gprc

4.编写DIL文件

syntax = "proto3";

package helloworld;

// The greeting service definition.

service Greeter {

// Sends a greeting

rpc SayHello (HelloRequest) returns (HelloReply) {}

}

// The request message containing the user's name.

message HelloRequest {

string name = 1;

}

// The response message containing the greetings

message HelloReply {

string message = 1;

}

5.生成文件, 在IDL文件目录执行: protoc --go_out=plugins=grpc:. ./hello.proto

6.服务端代码:

package main

import (

"fmt"

"golang.org/x/net/context"

"google.golang.org/grpc"

"net"

pb "IDL文件生成的hello.pb.go"

)

type service struct{} //声明一个结构体, 实现服务

func (s *service) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { //服务逻辑, 出入参要和hello.pd.go中的方法一样

name := req.Name //请求结构体中的数据

fmt.Println("this is golang service, request...", name)

return &pb.HelloReply{

Message: "this is golang service", //返回数据

}, nil

}

func main() {

lis, err := net.Listen("tcp", ":50001")

if err != nil {

panic(err)

}

s := grpc.NewServer()

pb.RegisterGreeterServer(s, &service{}) //注册

_ = s.Serve(lis)

}

7.客户端代码

package main

import (

"fmt"

"golang.org/x/net/context"

"google.golang.org/grpc"

"hello.pb.go"

)

func main() {

conn, err := grpc.Dial("localhost:50001", grpc.WithInsecure()) //连接

if err != nil {

fmt.Println(err)

}

defer conn.Close()

hc := helloworld.NewGreeterClient(conn)

res, err := hc.SayHello(context.Background(), &helloworld.HelloRequest{

Name: "this is golang client request",

})

if err != nil {

fmt.Println(err)

}

fmt.Println("this is golang client, response...", res.Message)

}

java与go的客户端和服务端代码都完成了, 并且可以跨语言调用

6409e8166418816731743b7bbcad0931.png

61f1a7908ff564f8519fe0f1301667fc.png

跨语言通信需要注意, IDL一定要一致, IDL中的package定义也一定要一致, 是grpc服务名的一部分

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值