文档章节

Grpc初体验安装测试

晓阳
 晓阳
发布于 2015/04/19 20:19
字数 1015
阅读 716
收藏 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


© 著作权归作者所有

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

评论(1)

晓阳
晓阳
http://www.molotang.com/articles/51.html
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...

陈晓风
2018/07/01
0
0
通过阿里云容器服务K8S Ingress Controller实现gRPC服务访问

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

chenqz
2018/06/01
0
0
gRPC Windows编译应用

gRPC Windows编译 从github上clone出来后进行cmake的编译,参考上面的文档,需要注意的点: 必须安装所有的依赖,包括Perl,Go,YASM,Git,CMake 不要使用--recursive来递归clone,因为墙的...

水海云
2018/06/20
0
0
.net core grpc consul 实现服务注册 服务发现 负载均衡(二)

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

蜗牛丨
2018/08/19
0
0

没有更多内容

加载失败,请刷新页面

加载更多

如何在React工程中使用JavaScript Barcode SDK创建Web条形码应用

基于WebAssembly构建的Dynamsoft JavaScript Barcode SDK让Web开发者能够创建适用于浏览器的高性能条码应用。这篇文章分享下如何使用React快速创建一个简单的Web条形码扫描应用。 下载 Node...

yushulx
29分钟前
1
0
java lambda笔记

c#中的lambda表达式简直不要太爽,但是感觉java的lambda和c#比有待继续提高。 先搞个筛选List集合的东西,我们先搞个集合玩玩。 List<Person> person = new ArrayList<Person>();Person p...

朝如青丝暮成雪
29分钟前
0
0
最严新规发布 网络短视频平台该如何降低违规风险?

1月9日中国网络视听节目服务协会对外正式发布了多项规范,对版权视频保护及违规内容,都进行了更加详细的标准制定,整体政策更加严格。 规范规定,网络短视频平台应当履行版权保护责任,不得...

阿里云官方博客
38分钟前
1
0
深入解读阿里云数据库POLARDB核心功能物理复制技术

日志是数据库的重要组成部份,按顺序以增量的方式记录了数据库上所有的操作,日志模块的设计对于数据库的可靠性、稳定性和性能都非常重要。 可靠性方面,在有一个数据文件的基础全量备份后,...

zhaowei121
44分钟前
1
0
CentOS 非root 用户 使用sudo 命令免密码

1. 使用su/su - 命令进入root权限下; 2. 给/etc/sudoers文件添加写权限 chmod u+w /etc/sudoers 3.找到“root ALL=(ALL) ALL ”,在后面添加:"dba ALL=(ALL) NOPASSWD: ALL" 4.保存退出,并......

驛路梨花醉美
44分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部