golang grpc服务端

1、服务端代码:

package main

import (
	"gitlab.liquidnetwork.com/box_backend/boxapigo/config"
	"gitlab.liquidnetwork.com/box_backend/boxapigo/go_grpc/heartbeat"
	"gitlab.liquidnetwork.com/box_backend/boxapigo/grpc_servers/heartbeat"
	"google.golang.org/grpc"
	"net"
	"runtime"
	"time"
)

const (
	oneDayInSeconds = 60 * 60 * 24
)

func main() {
    // 启动最大协程数
	runtime.GOMAXPROCS(6)
	lis, err := net.Listen("tcp", ":5591")

	if err != nil {
		panic(err)
	}

	s := grpc.NewServer()

    // 心跳检测服务器注册
	heartbeat.RegisterHeartbeatServer(s, &heartbeatserver.Heartbeat{})
	go s.Serve(lis)

    // 死循环防止进程退出
	for true {
		time.Sleep(time.Duration(oneDayInSeconds) * time.Second)
	}

}

2、心跳检测服务器代码

package heartbeatserver

import (
	"gitlab.liquidnetwork.com/box_backend/boxapigo/go_grpc/heartbeat"
	"golang.org/x/net/context"
)

type Heartbeat struct{}

func (h *Heartbeat) IsHaveHeartbeat(ctx context.Context, in *heartbeat.Request) (*heartbeat.Response, error) {
	return &heartbeat.Response{Code: 1, Message: "I am fine,thanks!"}, nil
}

3、心跳检测protobuf

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

option objc_class_prefix = "AUTH";

package heartbeat;

    // The greeting service definition.
service Heartbeat {
    // 心跳检测
    rpc IsHaveHeartbeat (Request) returns (Response) {}
}

// The request message containing the user's name.
message Request {
    string params = 1;
}

// The response message containing the greetings
message Response {
    int32 code = 1;
    string message = 3;
}

4、protobuf生成go文件

protoc --go_out=plugins=grpc:../go_grpc/ ./heartbeat/heartbeat.proto

你可能感兴趣的:(golang开发)