怎么啟動http服務(wù)和rpc服務(wù)

怎么啟動http服務(wù)和rpc服務(wù)?這篇文章運(yùn)用了實(shí)例代碼展示,代碼非常詳細(xì),可供感興趣的小伙伴們參考借鑒,希望對大家有所幫助。

創(chuàng)新互聯(lián)建站主要從事成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)鄂州,10多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108

開啟http服務(wù)

老規(guī)矩,先添加配置,順便把rpc的配置也寫進(jìn)去,config.json:

  "http_config": {
    "addr": ":8080"
  },
  "rpc_config": {
    "addr": ":8081"
  }

config.go:

type HttpConfig struct {
    Addr string `json:"addr"`
}

type RpcConfig struct {
    Addr string `json:"addr"`
}

接著,來看看process/http/http.go的內(nèi)容:

package http

import (
    "github.com/gin-gonic/gin"
    "go.uber.org/zap"
    "os"
)

var engine *gin.Engine

//啟動http服務(wù)
func StartHttpServer(addr string) {
    engine = gin.Default()
    Route()
    if err := engine.Run(addr); err != nil {
        zap.Error(err)
        os.Exit(1)
    }
}

//路由
func Route() {
    engine.GET("/server_time", GetServerTime)
}

我用了gin來提供http服務(wù),具體路由分發(fā)的方法寫在了dispatch.go里面,這里寫了一個簡單的示例接口,獲取服務(wù)器系統(tǒng)時(shí)間:

type Request struct {
}

type Response struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}

func GetServerTime(ctx *gin.Context) {
    resp := Response{}
    resp.Data, resp.Code, resp.Msg = controller.GetServerTime()
    ctx.JSON(resp.Code, resp)
}

我定義了一個請求結(jié)構(gòu)體和返回結(jié)構(gòu)體來統(tǒng)一一下,請求和返回的數(shù)據(jù)格式。GetServerTime調(diào)用了controller.GetServerTime()方法。我希望有個數(shù)據(jù)處理層來隔離接口。

rpc服務(wù)

我現(xiàn)在想對外提供rpc服務(wù),和http服務(wù)提供一樣的數(shù)據(jù)。我用的是grpc。

使用grpc

  1. 從 https://github.com/google/protobuf/releases下載對應(yīng)的安裝包,然后解壓,把protoc的執(zhí)行文件放到PATH里;

  2. 安裝 golang protobuf
    go get -u github.com/golang/protobuf/proto // golang protobuf 庫
    go get -u github.com/golang/protobuf/protoc-gen-go //protoc 轉(zhuǎn)換go工具

  3. 安裝 gRPC-go
    go get google.golang.org/grpc

編寫protobuf文件

我在process/rpc/server目錄下,創(chuàng)建了一個server.proto文件來定義接口協(xié)議:

syntax = "proto3"; //語法聲明

package server; //包名

service Server {
    rpc GetServerTime (ServerTimeRequest) returns (ServerTimeResponse);
}

message ServerTimeRequest {
}

message ServerTimeResponse {
    uint32 code = 1;
    string msg = 2;
    ServerTimeResponseData data = 3;
}

message ServerTimeResponseData {
    uint64 server_time = 1;
}

接著,進(jìn)到process/rpc/server目錄,并執(zhí)行生成go文件的命令,會生成一個go文件:

$ cd process/rpc/server
$ protoc --go_out=plugins=grpc:. server.proto

然后,我們寫一下我們的rpc服務(wù)端:

package rpc

import (
    "context"
    "github.com/TomatoMr/awesomeframework/process/controller"
    "github.com/TomatoMr/awesomeframework/process/rpc/server"
    "net"
)
import "google.golang.org/grpc"

type Server struct {
}

//啟動rpc服務(wù)
func StartRpcServer(addr string) {
    lis, err := net.Listen("tcp", addr)
    if err != nil {

    }
    s := grpc.NewServer() 
    server.RegisterServerServer(s, &Server{})
    if err := s.Serve(lis); err != nil {

    }
}

func (rp *Server) GetServerTime(ctx context.Context, request *server.ServerTimeRequest) (*server.ServerTimeResponse, error) {
    data, code, msg := controller.GetServerTime()
    resp := &server.ServerTimeResponse{}
    respData := &server.ServerTimeResponseData{}
    resp.Msg = msg
    resp.Code = uint32(code)
    respData.ServerTime = uint64(data.ServerTime)
    resp.Data = respData
    return resp, nil
}

調(diào)整入口文件

main.go

    //啟動http服務(wù)
    go http.StartHttpServer(config.GetConfig().HttpConfig.Addr)

    //啟動rpc服務(wù)
    go rpc.StartRpcServer(config.GetConfig().RpcConfig.Addr)

    logger.GetLogger().Info("Init success.")

    select {}

main.go添加了這幾行代碼,以go routine啟動了http服務(wù)和rpc服務(wù),因此,在最后用一個select來阻塞程序退出。

測試一下

寫一個rpc客戶端的test如下:

package main

import (
    "context"
    "github.com/TomatoMr/awesomeframework/process/rpc/server"
    "google.golang.org/grpc"
    "log"
    "time"
)

const (
    Addr = "127.0.0.1:8081"
)

func main() {
    conn, err := grpc.Dial(Addr, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    c := server.NewServerClient(conn)

    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    r, _ := c.GetServerTime(ctx, &server.ServerTimeRequest{})

    log.Printf("Data: %v", r.Data.ServerTime)
}

編譯:

$ go build

運(yùn)行:

$ awesomeframework --config=./config/config.json

測試:

$ curl localhost:8080/server_time
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    56  100    56    0     0  18666      0 --:--:-- --:--:-- --:--:-- 28000
{"code":200,"msg":"","data":{"server_time":1579597891}}

測試rpc接口的文件我放在了process/rpc/test/request.go

$ go run request.go
2020/01/21 17:18:08 Data: 1579598288

關(guān)于就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

本文標(biāo)題:怎么啟動http服務(wù)和rpc服務(wù)
分享路徑:http://muchs.cn/article30/jepdpo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、、全網(wǎng)營銷推廣App設(shè)計(jì)、面包屑導(dǎo)航、企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)