Grpc初体验安装测试

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

grpc初体验安装测试

安装

Protobuf-3.0.0

下载链接:http://pan.baidu.com/s/1jGILD4q

安装参考:http://www.tuicool.com/articles/nYZrmi

Git

安装参考:http://www.oschina.net/code/snippet_4873_1376

Maven

安装参考:http://my.oschina.net/pengqiang/blog/275306?p={{currentPage+1}}

编译源码

grpc-java

下载链接:https://github.com/grpc/grpc-java

编译步骤请阅读README.md(因为都是英文的所以请仔细阅读)

grpc-go

下载链接:https://github.com/grpc/grpc-go

Go语言只要下载好放到go环境path下即可

编写proto文件

syntax = "proto3";

 

package proto;

 

option java_package = "io.grpc.ac.proto";

 

service AccountService {

  rpc QueryAll (QueryRequest) returns (QueryResponse) {}

  rpc QueryByPhone (QueryRequestPhone) returns (QueryResponseInt) {}

  rpc QueryByEmail (QueryRequestEmail) returns (QueryResponseInt) {}

  rpc Insert (Account) returns (InsertResponseInt) {}

}

 

message QueryRequestPhone {

  string phone = 1;

}

 

message QueryRequestEmail {

  string email = 1;

}

 

message QueryResponseInt {

  int32 c = 1;

}

 

message InsertResponseInt {

  int32 c = 1;

}

 

message QueryRequest {

  string userName = 1;

}

 

message Account {

  int32 id = 1;

  string userName = 2;

  string password = 3;

  int32 pwdStrong = 4;

  string phone = 5;

  string email = 6;

  string areaCode = 7;

  int32 type = 8;

  int32 enable = 9;

  int32 createTime = 10;

}

 

message QueryResponse {

  repeated Account accounts = 1;

}

编译proto文件-GO

编译链接:https://github.com/grpc/grpc-common/blob/master/go/README.md

编译proto文件-JAVA

编译链接:https://github.com/grpc/grpc-common/blob/master/java/javatutorial.md

 

Mysql

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (

  `id` bigint(20) unsigned NOT NULL,

  `username` varchar(20) NOT NULL,

  `password` varchar(32) NOT NULL,

  `pwd_strong` tinyint(3) unsigned NOT NULL,

  `phone` varchar(25) DEFAULT NULL,

  `email` varchar(40) DEFAULT NULL,

  `area_code` varchar(6) DEFAULT NULL,

  `type` tinyint(3) unsigned NOT NULL,

  `enable` tinyint(1) DEFAULT NULL,

  `createtime` bigint(20) unsigned NOT NULL,

  PRIMARY KEY (`id`),

  UNIQUE KEY `idx_username` (`username`),

  UNIQUE KEY `idx_phone_maill` (`phone`,`email`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

JAVA版服务端、客户端代码

package io.grpc.ac.proto;

 

import io.grpc.ServerImpl;

import io.grpc.ac.proto.Ac.Account;

import io.grpc.ac.proto.Ac.InsertResponseInt;

import io.grpc.ac.proto.Ac.QueryRequest;

import io.grpc.ac.proto.Ac.QueryRequestEmail;

import io.grpc.ac.proto.Ac.QueryRequestPhone;

import io.grpc.ac.proto.Ac.QueryResponse;

import io.grpc.ac.proto.Ac.QueryResponseInt;

import io.grpc.ac.proto.AccountServiceGrpc.AccountService;

import io.grpc.stub.StreamObserver;

import io.grpc.transport.netty.NettyServerBuilder;

 

import java.util.logging.Logger;

 

public class AcServer {

         private static final Logger logger = Logger.getLogger(AcServer.class

                            .getName());

         private int port = 9090;

         private ServerImpl server;

 

         private void start() throws Exception {

                   server = NettyServerBuilder

                                     .forPort(port)

                                     .addService(

                                                        AccountServiceGrpc

                                                                           .bindService(new AccountServiceImpl())).build()

                                     .start();

                   logger.info("Server started, listening on " + port);

                   Runtime.getRuntime().addShutdownHook(new Thread() {

                            @Override

                            public void run() {

                                     System.err

                                                        .println("*** shutting down gRPC server since JVM is shutting down");

                                     AcServer.this.stop();

                                     System.err.println("*** server shut down");

                            }

                   });

         }

 

         private void stop() {

                   if (server != null) {

                            server.shutdown();

                   }

         }

 

         public static void main(String[] args) throws Exception {

                   final AcServer server = new AcServer();

                   server.start();

         }

 

         private class AccountServiceImpl implements AccountService {

 

                   @Override

                   public void queryAll(QueryRequest request,

                                     StreamObserver responseObserver) {

                            logger.info(">>> request username = " + request.getUserName());

                            io.grpc.ac.proto.Ac.QueryResponse.Builder builder = QueryResponse

                                               .newBuilder();

                            for (int i = 1; i <= 10; i++) {

                                     Account account = Account.newBuilder().setId(i)

                                                        .setUserName(i + "").setPassword(i + "")

                                                        .setPwdStrong(i).setPhone(i + "").setEmail(i + "")

                                                        .setAreaCode(i + "").setType(i).setEnable(i)

                                                        .setCreateTime(i).build();

                                     builder.addAccounts(account);

                            }

                            QueryResponse queryResponse = builder.build();

                            responseObserver.onValue(queryResponse);

                            responseObserver.onCompleted();

                   }

 

                   @Override

                   public void queryByPhone(QueryRequestPhone request,

                                     StreamObserver responseObserver) {

                   }

 

                   @Override

                   public void queryByEmail(QueryRequestEmail request,

                                     StreamObserver responseObserver) {

                   }

 

                   @Override

                   public void insert(Account request,

                                     StreamObserver responseObserver) {

                   }

 

         }

 

}

 

package io.grpc.ac.proto;

 

import io.grpc.ChannelImpl;

import io.grpc.ac.proto.Ac.Account;

import io.grpc.ac.proto.Ac.QueryRequest;

import io.grpc.ac.proto.Ac.QueryResponse;

import io.grpc.transport.netty.NegotiationType;

import io.grpc.transport.netty.NettyChannelBuilder;

 

import java.util.concurrent.TimeUnit;

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class AcClient {

         private static final Logger logger = Logger.getLogger(AcClient.class

                            .getName());

 

         private final ChannelImpl channel;

         private final AccountServiceGrpc.AccountServiceBlockingStub blockingStub;

 

         public AcClient(String host, int port) {

                   channel = NettyChannelBuilder.forAddress(host, port)

                                     .negotiationType(NegotiationType.PLAINTEXT).build();

                   blockingStub = AccountServiceGrpc.newBlockingStub(channel);

         }

 

         public void shutdown() throws InterruptedException {

                   channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS);

         }

 

         public void queryAll() {

                   try {

                            logger.info(">>> execute query all");

                            QueryRequest queryRequest = QueryRequest.newBuilder()

                                               .setUserName("---test---").build();

                            QueryResponse queryResponse = blockingStub.queryAll(queryRequest);

                            logger.info(">>> query result count = "

                                               + queryResponse.getAccountsCount());

                            for (Account account : queryResponse.getAccountsList()) {

                                     printAccount(account);

                            }

                   } catch (RuntimeException e) {

                            logger.log(Level.WARNING, e.getMessage());

                            return;

                   }

         }

 

         private void printAccount(Account account) {

                   logger.info(String

                                     .format(">>> id[%s] username[%s] password[%s] pwd_strong[%s] phone[%s] email[%s] area_code[%s] type[%s] enable[%s] createtime[%s]",

                                                        account.getId(), account.getUserName(),

                                                        account.getPassword(), account.getPwdStrong(),

                                                        account.getPhone(), account.getEmail(),

                                                        account.getAreaCode(), account.getType(),

                                                        account.getEnable(), account.getCreateTime()));

         }

 

         public static void main(String[] args) throws Exception {

                   AcClient client = new AcClient("127.0.0.1", 9090);

                   try {

                            client.queryAll();

                   } finally {

                            client.shutdown();

                   }

         }

 

}

 

GO版服务端、客户端代码

package service

 

import (

    "ac/dao"

    pb "ac/proto"

    "fmt"

    "golang.org/x/net/context"

)

 

type acService struct{}

 

func (acs *acService) Insert(ctx context.Context, a *pb.Account) (*pb.InsertResponseInt, error) {

    fmt.Println("context = [", ctx, "]")

    fmt.Println("account = [", a, "]")

    return &pb.InsertResponseInt{C: 1}, nil

}

 

func (acs *acService) QueryAll(ctx context.Context, qr *pb.QueryRequest) (*pb.QueryResponse, error) {

    fmt.Println("context = [", ctx, "]")

    fmt.Println("query username = [", qr.UserName, "]")

    var accounts = make([]*pb.Account, dao.Size)

    count := dao.QueryAll(accounts)

    fmt.Println("query count = [", count, "]")

    if count >= len(accounts) {

        return &pb.QueryResponse{Accounts: accounts}, nil

    } else {

        return &pb.QueryResponse{Accounts: accounts[:count]}, nil

    }

}

 

func (acs *acService) QueryByPhone(ctx context.Context, qrp *pb.QueryRequestPhone) (*pb.QueryResponseInt, error) {

    fmt.Println("context = [", ctx, "]")

    fmt.Println("query phone = [", qrp.Phone, "]")

    return &pb.QueryResponseInt{C: 0}, nil

}

 

func (acs *acService) QueryByEmail(ctx context.Context, qre *pb.QueryRequestEmail) (*pb.QueryResponseInt, error) {

    fmt.Println("context = [", ctx, "]")

    fmt.Println("query email = [", qre.Email, "]")

    return &pb.QueryResponseInt{C: 1}, nil

}

 

func NewAcService() *acService {

    s := new(acService)

    return s

}

 

package main

 

import (

    pb "ac-client/proto"

    "fmt"

    "golang.org/x/net/context"

    "google.golang.org/grpc"

    "strconv"

)

 

var (

    ip   = "127.0.0.1"

    port = 9090

)

 

func main() {

    conn, err := grpc.Dial(ip + ":" + strconv.Itoa(port))

    panicErr(err)

    fmt.Println("connect to [", ip, port, "] success")

    defer conn.Close()

    c := pb.NewAccountServiceClient(conn)

 

    //    ci, err := c.Insert(context.Background(), &pb.Account{111, "ysh", "123456", 1, "xxxxx", "[email protected]", "314200", 1, 1, 1})

    //    panicErr(err)

    //    fmt.Println("insert return count = ", ci.C)

 

    userName := "test"

    r, err := c.QueryAll(context.Background(), &pb.QueryRequest{UserName: userName})

    panicErr(err)

 

    //    cp, err := c.QueryByPhone(context.Background(), &pb.QueryRequestPhone{Phone: "xxxxx"})

    //    panicErr(err)

    //    fmt.Println("query by phone and c = ", cp.C)

 

    //    ce, err := c.QueryByEmail(context.Background(), &pb.QueryRequestEmail{Email: "[email protected]"})

    //    panicErr(err)

    //    fmt.Println("query by email and c = ", ce.C)

 

    accounts := r.Accounts

    if len(accounts) == 0 {

        fmt.Println("query data is nil")

        return

    }

    for i := 0; i < len(accounts); i++ {

        account := accounts[i]

        fmt.Println(i, " : ", account)

    }

}

 

func panicErr(err error) {

    if err != nil {

        panic(err)

    }

}

 

完整测试代码

下载链接:

http://pan.baidu.com/s/1jGBud62

http://pan.baidu.com/s/1dDrl0Gh

http://pan.baidu.com/s/1i3CIabF


转载于:https://my.oschina.net/ysh3940/blog/403591

你可能感兴趣的:(golang,数据库,python)