首先我们用go-micro构建一个服务。(关于go-micro的使用可以参照官方实例或者文档)

//新建一个微服务
micro new --type "srv" user-srv

 

定义我们的服务,这里定义两个rpc服务,register和user
 1 // 修改proto
 2 syntax = "proto3";
 3 ​
 4 package go.micro.srv.user;
 5 ​
 6 service user {
 7     rpc register(registerrequest) returns (userinfo) {}
 8     rpc user(userinforequest) returns (userinfo) {}
 9     rpc stream(streamingrequest) returns (stream streamingresponse) {}
10     rpc pingpong(stream ping) returns (stream pong) {}
11 }
12 ​
13 ​
14 message userinforequest {
15     int64 userid  = 1;
16 }
17 ​
18 message registerrequest {
19     string username  = 1;
20     string email     = 2;
21     string password  = 3;
22 }
23 ​
24 message userinfo {
25     int64  id       =  1;
26     string username =  2;
27     string email    =  3;
28 }
29 ​
30 ​
31 ​
32 message streamingrequest {
33     int64 count = 1;
34 }
35 ​
36 message streamingresponse {
37     int64 count = 1;
38 }
39 ​
40 message ping {
41     int64 stroke = 1;
42 }
43 ​
44 message pong {
45     int64 stroke = 1;
46 }

 

然后生成执行下面命令我们就可以发现在proto文件中多出两个文件。这个proto为我们生成的,后面会用到。

protoc --proto_path=${gopath}/src:. --micro_out=. --go_out=. proto/user/user.proto

 

写我们的业务逻辑,修改handle/user.go文件

 1 type user struct{}
 2 ​
 3 // call is a single request handler called via client.call or the generated client code
 4 func (e *user) register(ctx context.context, req *user.registerrequest, rsp *user.userinfo) error {
 5     log.log("received user.register request")
 6     rsp.id    = 1
 7     rsp.email = req.email
 8     rsp.username = req.username
 9     return nil
10 }
11 ​
12 ​
13 func (e *user) user(ctx context.context, req *user.userinforequest, rsp *user.userinfo) error {
14     log.log("received user.register request")
15     rsp.id    = 1
16     rsp.email = "741001560@qq.com"
17     rsp.username = "chensi"
18     return nil
19 }
20 ​
21 // stream is a server side stream handler called via client.stream or the generated client code
22 func (e *user) stream(ctx context.context, req *user.streamingrequest, stream user.user_streamstream) error {
23     log.logf("received user.stream request with count: %d", req.count)
24 ​
25     for i := 0; i < int(req.count); i++ {
26         log.logf("responding: %d", i)
27         if err := stream.send(&user.streamingresponse{
28             count: int64(i),
29         }); err != nil {
30             return err
31         }
32     }
33 ​
34     return nil
35 }
36 ​
37 // pingpong is a bidirectional stream handler called via client.stream or the generated client code
38 func (e *user) pingpong(ctx context.context, stream user.user_pingpongstream) error {
39     for {
40         req, err := stream.recv()
41         if err != nil {
42             return err
43         }
44         log.logf("got ping %v", req.stroke)
45         if err := stream.send(&user.pong{stroke: req.stroke}); err != nil {
46             return err
47         }
48     }
49 }
50  

 

最后修改我们的main.go文件,服务发现使用时consul。

 1 func main() {
 2     //initcfg()
 3     // new service
 4 ​
 5     micreg := consul.newregistry()
 6 ​
 7     service := micro.newservice(
 8         micro.server(s.newserver()),
 9         micro.name("go.micro.srv.user"),
10         micro.version("latest"),
11         micro.registry(micreg),
12     )
13 ​
14     // initialise service
15     service.init()
16 ​
17     // run service
18     if err := service.run(); err != nil {
19         log.fatal(err)
20     }
21 }
22  

 

我们使用consul做微服务发现,当然首先你需要安装consul

wget https://releases.hashicorp.com/consul/1.2.0/consul_1.6.1_linux_amd64.zip
unzip consul_1.6.1_linux_amd64.zip
mv consul /usr/local/bin/

 

启动consul的时候由于在是本地虚拟机上面,所以我们可以简单处理

consul agent -dev  -client 0.0.0.0 -ui

 

这时候可以启动consul的ui了,我本地vagrant的虚拟机192.168.10.100,那么我们打开的是http://192.168.10.100:8500/ui/dc1/services

启动user-srv的服务发现consul里面出现 go.micro.srv.user 的服务注册信息了

下面来写hyperf的代码了。按照官方文档安装框架,安装的时候rpc需要选择grpc,需要注意的是你的系统上面需要安装php7.2以上的版本,swoole版本也需要4.3的版本以上,我用的是最新homestead,所以相对而言安装这些依赖比较简单,所以在此强烈推荐。

第一次启动时候官方会要求修改一些php.ini的参数,大家安装要求走就是了。

这部分的流程自己参照官方文档,至于一些扩展的安装可以谷歌或者百度。

安装好框架之后再根目录下面新建一个grpc和proto的目录,把go-micro里面user.proto文件复制到hyperf项目的proto的目录之下。然后在目录下执行命令

protoc --php_out=plugins=grpc:../grpc user.proto

 

执行成功之后会发现在grpc目录下多出两个文件夹。

接下来我们开始编写client的代码,在hyperf项目的app目录下新建一个grpc的目录并且新建一个userclient.php的文件

 1 namespace app\grpc;
 2 ​
 3 ​
 4 use go\micro\srv\user\registerrequest;
 5 use go\micro\srv\user\userinfo;
 6 use hyperf\grpcclient\baseclient;
 7 ​
 8 class userclient extends baseclient
 9 {
10     public function register(registerrequest $argument)
11     {
12         return $this->simplerequest(
13             '/user.user/register',
14             $argument,
15             [userinfo::class, 'decode']
16         );
17     }
18 ​

 

关于这一块的代码,其实官方文档写得特别详细,具体可以参照官方文档。

新建一个路由

router::addroute(['get', 'post', 'head'], '/grpc', 'app\controller\indexcontroller@grpc');

编写控制器

 1 public function grpc ()
 2 {
 3 ​
 4         $client = new \app\grpc\userclient('127.0.0.1:9527', [
 5             'credentials' => null,
 6         ]);
 7 ​
 8         $request = new registerrequest();
 9         $request->setemail("741001560@qq.com");
10         $request->setusername("chensi");
11         $request->setpassword("123456");
12 ​
13         /**
14          * @var \grpc\hireply $reply
15          */
16         list($reply, $status) = $client->register($request);
17 ​
18         $message = $reply->getid();
19         return [
20             'id' => $message
21         ];
22     }

 

这时候还需要吧根目录下的grpc目录加载进来。修改composer.json文件

```

// psr-4 下面新增两个行
"autoload": {
        "psr-4": {
            "app\\": "app/",
            "gpbmetadata\\": "grpc/gpbmetadata",
            "go\\": "grpc/go"
        },
        "files": []
    }

 

然后执行composer dump-autoload命令。然后启动hyperf项目,打开浏览器输入http://192.168.10.100:9501/grpc回车,这时候我们就能看到结果了。

这时候我们会发现一个问题,那就是consul在client端压根没用到,在代码中我们还是需要指明我们的端口号。然后再看看官方文档其实是支持consul的,那么将代码改造下。

在app下新建一个register的目录创建一个文件consulservices.php,然后开始编写服务发现的代码,安装consul包以后,由于官方提供的consul包没有文档所以需要自己去看源代码。官方在consul提供的api上面做了简单的封装,如kv、health等,在实例化话的时候需要穿一个客户端过去。下面提供一个简单的实例。

 1 <?php
 2 declare(strict_types=1);
 3 ​
 4 namespace app\register;
 5 ​
 6 use hyperf\consul\health;
 7 use psr\container\containerinterface;
 8 use hyperf\guzzle\clientfactory;
 9 ​
10 class consulservices
11 {
12 ​
13     public $servers;
14     private $container;
15 ​
16 ​
17     public function __construct(containerinterface $container)
18     {
19         $this->container = $container;
20     }
21 ​
22     public function getservers()
23     {
24         $health = new health(function ()  {
25             return $this->container->get(clientfactory::class)->create([
26                 'base_uri' => 'http://127.0.0.1:8500',
27             ]);
28         });
29         $resp = $health->service("go.micro.srv.user");
30         $servers = $resp->json();
31         if (empty($servers)){
32             $this->servers = [];
33         }
34         foreach ($servers as $server) {
35             $this->servers[] = sprintf("%s:%d",$server['service']['address'],$server['service']['port']);
36         }
37     }
38 }

 

这时候发现一个问题如果每次请求过来都去请求一次必然给consul造成很大的负荷。既然用到了swoole框架可以在每次swoole启动的时候去请求一次,然后把服务发现的信息存起来。修改配置文件server。

 1 'callbacks' => [
 2 //        swooleevent::on_before_start => [hyperf\framework\bootstrap\serverstartcallback::class, 'beforestart'],
 3         swooleevent::on_before_start => [\app\bootstrap\serverstartcallback::class, 'beforestart'],
 4         swooleevent::on_worker_start => [hyperf\framework\bootstrap\workerstartcallback::class, 'onworkerstart'],
 5         swooleevent::on_pipe_message => [hyperf\framework\bootstrap\pipemessagecallback::class, 'onpipemessage'],
 6     ],
 7 可以在serverstartcallback类里面请求consul进行服务发现 后面拿到参数就好了。
 8 
 9 namespace app\bootstrap;
10 ​
11 use app\register\consulservices;
12 ​
13 class serverstartcallback
14 {
15     public function beforestart()
16     {
17         $container = \hyperf\utils\applicationcontext::getcontainer();
18         $container->get(consulservices::class)->getservers();
19     }
20 }

 

 

改造一下原来的控制器

public function grpc ()
{
​
        $container = \hyperf\utils\applicationcontext::getcontainer();
        $servers = $container->get(consulservices::class)->servers;
        if (empty($servers)) {
            return [
                'errcode' => 1000,
                'msg'     => '服务不存在',
            ];
        }
        $key = array_rand($servers,1); // 哈哈哈一个简单的负载均衡
        $hostname = $servers[$key];
        $client = new \app\grpc\userclient($hostname, [
            'credentials' => null,
        ]);
        $request = new registerrequest();
        $request->setemail("741001560@qq.com");
        $request->setusername("chensi");
        $request->setpassword("123456");
​
        /**
         * @var \grpc\hireply $reply
         */
        list($reply, $status) = $client->register($request);
​
        $message = $reply->getid();
        return [
            'id' => $message
        ];
    }

 

重启服务,这时候然后刷新浏览器试试。这时候一个简单基于go rpc server和php client的微服务就搭建完成了。当然了这时候还没有心跳机制,hyperf官网提供了一个定时器的功能,我们定时去刷服务发现就好了。