go-micro+php+consul implements simple microservices

藏色散人
Release: 2023-04-08 10:16:02
forward
2967 people have browsed it

go-micro+php+consul implements simple microservices

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

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

定义我们的服务,这里定义两个rpc服务,Register和User

// 修改proto
syntax = "proto3";

package go.micro.srv.user;

service User {
    rpc Register(RegisterRequest) returns (UserInfo) {}
    rpc User(UserInfoRequest) returns (UserInfo) {}
    rpc Stream(StreamingRequest) returns (stream StreamingResponse) {}
    rpc PingPong(stream Ping) returns (stream Pong) {}
}


message UserInfoRequest {
    int64 userId  = 1;
}

message RegisterRequest {
    string username  = 1;
    string email     = 2;
    string password  = 3;
}

message UserInfo {
    int64  id       =  1;
    string username =  2;
    string email    =  3;
}



message StreamingRequest {
    int64 count = 1;
}

message StreamingResponse {
    int64 count = 1;
}

message Ping {
    int64 stroke = 1;
}

message Pong {
    int64 stroke = 1;
}
Copy after login

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

protoc --proto_path=${GOPATH}/src:. --micro_out=. --go_out=. proto/user/user.proto
Copy after login

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

type User struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *User) Register(ctx context.Context, req *user.RegisterRequest, rsp *user.UserInfo) error {
    log.Log("Received User.Register request")
    rsp.Id    = 1
    rsp.Email = req.Email
    rsp.Username = req.Username
    return nil
}


func (e *User) User(ctx context.Context, req *user.UserInfoRequest, rsp *user.UserInfo) error {
    log.Log("Received User.Register request")
    rsp.Id    = 1
    rsp.Email = "741001560@qq.com"
    rsp.Username = "chensi"
    return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *User) Stream(ctx context.Context, req *user.StreamingRequest, stream user.User_StreamStream) error {
    log.Logf("Received User.Stream request with count: %d", req.Count)

    for i := 0; i < int(req.Count); i++ {
        log.Logf("Responding: %d", i)
        if err := stream.Send(&user.StreamingResponse{
            Count: int64(i),
        }); err != nil {
            return err
        }
    }

    return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *User) PingPong(ctx context.Context, stream user.User_PingPongStream) error {
    for {
        req, err := stream.Recv()
        if err != nil {
            return err
        }
        log.Logf("Got ping %v", req.Stroke)
        if err := stream.Send(&user.Pong{Stroke: req.Stroke}); err != nil {
            return err
        }
    }
}
Copy after login

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

func main() {
    //initCfg()
    // New Service

    micReg := consul.NewRegistry()

    service := micro.NewService(
        micro.Server(s.NewServer()),
        micro.Name("go.micro.srv.user"),
        micro.Version("latest"),
        micro.Registry(micReg),
    )

    // Initialise service
    service.Init()

    // Run service
    if err := service.Run(); err != nil {
        log.Fatal(err)
    }
}
Copy after login

我们使用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
Copy after login

这时候可以启动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
Copy after login

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

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

namespace App\Grpc;


use Go\Micro\Srv\User\RegisterRequest;
use Go\Micro\Srv\User\UserInfo;
use Hyperf\GrpcClient\BaseClient;

class UserClient extends BaseClient
{
    public function Register(RegisterRequest $argument)
    {
        return $this->simpleRequest(
            &#39;/user.User/Register&#39;,
            $argument,
            [UserInfo::class, &#39;decode&#39;]
        );
    }
Copy after login

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

新建一个路由

Router::addRoute(['GET', 'POST', 'HEAD'], '/grpc', 'App\Controller\IndexController@grpc');

编写控制器

public function grpc ()
{

        $client = new \App\Grpc\UserClient(&#39;127.0.0.1:9527&#39;, [
            &#39;credentials&#39; => 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 [
            &#39;id&#39; => $message
        ];
    }
Copy after login

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

```

// psr-4 下面新增两个行
"autoload": {
        "psr-4": {
            "App\\": "app/",
            "GPBMetadata\\": "grpc/GPBMetadata",
            "Go\\": "grpc/Go"
        },
        "files": []
    }
Copy after login

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

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

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

<?php
declare(strict_types=1);

namespace App\Register;

use Hyperf\Consul\Health;
use Psr\Container\ContainerInterface;
use Hyperf\Guzzle\ClientFactory;

class ConsulServices
{

    public $servers;
    private $container;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getServers()
    {
        $health = new Health(function ()  {
            return $this->container->get(ClientFactory::class)->create([
                &#39;base_uri&#39; => &#39;http://127.0.0.1:8500&#39;,
            ]);
        });
        $resp = $health->service("go.micro.srv.user");
        $servers = $resp->json();
        if (empty($servers)){
            $this->servers = [];
        }
        foreach ($servers as $server) {
            $this->servers[] = sprintf("%s:%d",$server[&#39;Service&#39;][&#39;Address&#39;],$server[&#39;Service&#39;][&#39;Port&#39;]);
        }
    }
}
Copy after login

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

&#39;callbacks&#39; => [
//        SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, &#39;beforeStart&#39;],
        SwooleEvent::ON_BEFORE_START => [\App\Bootstrap\ServerStartCallback::class, &#39;beforeStart&#39;],
        SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, &#39;onWorkerStart&#39;],
        SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, &#39;onPipeMessage&#39;],
    ],
可以在ServerStartCallback类里面请求consul进行服务发现 后面拿到参数就好了。

namespace App\Bootstrap;
use App\Register\ConsulServices;
class ServerStartCallback
{
    public function beforeStart()
    {
        $container = \Hyperf\Utils\ApplicationContext::getContainer();
        $container->get(ConsulServices::class)->getServers();
    }
}
Copy after login

改造一下原来的控制器

public function grpc ()
{

        $container = \Hyperf\Utils\ApplicationContext::getContainer();
        $servers = $container->get(ConsulServices::class)->servers;
        if (empty($servers)) {
            return [
                &#39;errCode&#39; => 1000,
                &#39;msg&#39;     => &#39;服务不存在&#39;,
            ];
        }
        $key = array_rand($servers,1); // 哈哈哈一个简单的负载均衡
        $hostname = $servers[$key];
        $client = new \App\Grpc\UserClient($hostname, [
            &#39;credentials&#39; => 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 [
            &#39;id&#39; => $message
        ];
    }
Copy after login

 

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

The above is the detailed content of go-micro+php+consul implements simple microservices. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!