文档章节

Grpc初体验安装测试

晓阳
 晓阳
发布于 2015/04/19 20:19
字数 1015
阅读 655
收藏 2

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<QueryResponse> 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<QueryResponseInt> responseObserver) {

                   }

 

                   @Override

                   public void queryByEmail(QueryRequestEmail request,

                                     StreamObserver<QueryResponseInt> responseObserver) {

                   }

 

                   @Override

                   public void insert(Account request,

                                     StreamObserver<InsertResponseInt> 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", "ysh3940@sina.com", "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: "ysh3940@sina.com"})

    //    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


© 著作权归作者所有

共有 人打赏支持
晓阳
粉丝 10
博文 69
码字总数 52360
作品 0
徐汇
程序员
加载中

评论(1)

晓阳
晓阳
http://www.molotang.com/articles/51.html
通过阿里云容器服务K8S Ingress Controller实现gRPC服务访问

gRPC简介 gRPC是Google开源的一个高性能RPC通信框架,通过Protocol Buffers作为其IDL,可以在不同语言开发的平台上使用,同时基于HTTP/2协议实现,继而提供了连接多路复用、头部压缩、流控等...

chenqz
06/01
0
0
grpc加密TLS初体验(go、java版本)

grpc加密TLS初体验(go、java版本) grpc-go、java的安装编译helloworld可以参考如下文章 http://my.oschina.net/ysh3940/blog/403591 openssl的安装、生成秘钥证书可以参考如下文章 http:/...

晓阳
2015/06/10
0
9
mac下grpc(golang server + php client)实践

目前微服务这么流行,RPC框架也是百花齐放,本文讲述一下mac下grpc的开发环境搭建,其中server端使用golang,客户端使用php。 服务端 golang grpc安装 这里列出了一个参考,由于grpc在githu...

陈晓风
07/01
0
0
.net core grpc consul 实现服务注册 服务发现 负载均衡(二)

在上一篇 .net core grpc 实现通信(一) 中,我们实现的grpc通信在.net core中的可行性,但要在微服务中真正使用,还缺少 服务注册,服务发现及负载均衡等,本篇我们将在 .net core grpc 通信...

蜗牛丨
08/19
0
0
通过Nginx实现gRPC服务的负载均衡 | gRPC双向数据流的交互控制系列(3)

前情提要 本系列的第一篇文章 通过一个例子介绍了go语言实现gRPC双向数据流的交互控制,第二篇文章介绍了如何通过Websocket与gRPC交互。通过这两篇文章,我们可以一窥gRPC双向数据流的开发方...

阿狸不歌
08/23
0
0

没有更多内容

加载失败,请刷新页面

加载更多

sed命令

10月17日任务 9.4/9.5 sed 1.sed(上)(下) 1.sed 匹配功能 #sed -n ‘/root/’ p test.txt 将带有root的内容打印出来 同时支持 . * 还有 + 不过需要脱译,或者在前面选项加r。 支持{ } 支...

hhpuppy
33分钟前
1
0
day120-20181018-英语流利阅读-待学习

千禧一代注意了:一大波公司正向你的钱包袭来 Daniel 2018-10-18 1.今日导读 这几年,你有没有发现,不管是在微信公众号还是在抖音,有越来越多的商家和品牌开始玩起了网络用语和表情包,从卖...

飞鱼说编程
42分钟前
1
0
IOasd

能够使用FileUtils常用方法操作文件 字符流体系介绍 : 在 IO 开发中, 我们传输最频繁的数据为字符, 而以字节的方式来传输字符数据会使程序员丧失对数据内容的判断.因为程序员只认识字符, 不认...

码农屌丝
今天
0
0
创建第一个react项目

sudo npm i -g create-react-app@1.5.2 create-react-app react-app cd react-apprm -rf package-lock.jsonrm -rf node_modules #主要是为了避免报错npm installnpm start......

lilugirl
今天
3
0
在浏览器中进行深度学习:TensorFlow.js (八)生成对抗网络 (GAN)

Generative Adversarial Network 是深度学习中非常有趣的一种方法。GAN最早源自Ian Goodfellow的这篇论文。LeCun对GAN给出了极高的评价: “There are many interesting recent development...

naughty
今天
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部