微服务实战Go Micro v3 系列(二)- HelloWorld


当前第2页 返回上一页

类似tcp通信,客户端和服务端可以互相发消息。

// 注意stream关键词在什么地方
rpc BidiHello(stream HelloRequest) returns (stream HelloResponse){
}

更多关于grpc教程请点击这里

编写 go-micro HTTP服务

安装 gofast插件

//gofast
go get -u -v github.com/gogo/protobuf/protoc-gen-gofast

开始编写 go-micro HTTP服务

创建 go-micro-examples 目录,然后在该目录下创建 helloworld目录

helloworld 目录下,创建 protohandler,并创建 main.go 和使用 go mod init 初始化项目,如下图所示

其它文件暂时忽略,后面会解释

在 proto 目录创建 helloworld.proto,并写入下面代码

syntax = "proto3";

package helloworld;

option go_package = "proto;helloworld";

service Helloworld {
    rpc Call(Request) returns (Response) {}
    rpc Stream(StreamingRequest) returns (stream StreamingResponse) {}
    rpc PingPong(stream Ping) returns (stream Pong) {}
}

message Message {
    string say = 1;
}

message Request {
    string name = 1;
}

message Response {
    string msg = 1;
}

message StreamingRequest {
    int64 count = 1;
}

message StreamingResponse {
    int64 count = 1;
}

message Ping {
    int64 stroke = 1;
}

message Pong {
    int64 stroke = 1;
}

进入该目录并输入以下命令

并生成 helloworld.pb.gohelloworld.pb.micro.go

main.go,创建服务并注册一下 handler,运行服务

package main

import (
    "github.com/asim/go-micro/v3"
    "github.com/asim/go-micro/v3/logger"
    "go-micro-examples/helloworld/handler"
    pb "go-micro-examples/helloworld/proto"
)

const (
    ServerName = "go.micro.srv.HelloWorld" // server name
)

func main() {
    // Create service
    service := micro.NewService(
        micro.Name(ServerName),
        micro.Version("latest"),
    )

    // Register handler
    if err := pb.RegisterHelloworldHandler(service.Server(), new(handler.Helloworld)); err != nil {
        logger.Fatal(err)
    }

    // Run service
    if err := service.Run(); err != nil {
        logger.Fatal(err)
    }
}

client 调用 service

创建 client 目录并创建client.go,写入一下代码

package main

import (
    "context"
    "fmt"
    "github.com/asim/go-micro/v3"
    helloworld "go-micro-examples/helloworld/proto"
)

func main() {
    // create a new service
    service := micro.NewService()

    // parse command line flags
    service.Init()

    // Use the generated client stub
    cl := helloworld.NewHelloworldService("go.micro.srv.HelloWorld", service.Client())

    // Make request
    rsp, err := cl.Call(context.Background(), &helloworld.Request{
        Name: "John",
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(rsp.Msg)
}

效果

先启用 go.micro.srv.HelloWorld 服务,然后再启动 client 调用,效果如下

启动 client 之后,输出 Hello World!

参考链接

  • ProtoBuf 入门教程
  • grpc 框架教程


返回前面的内容

相关阅读 >>

Golang 是什么

Golang 如何读取csv文件

教你使用Golang和lua实现一个值班机器人

Golang怎么搭一个网站

Go-carbon1.2.4发布了!新增系列时间比较方法

游戏服务器框架Gonet

Golang 架构设计原则 接口隔离原则

Go基础编程:数据类型

Go语言基础之基本数据类型

Golang制作简单代理定制

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...