go-micro+php+consul implements simple microservices
首先我们用go-micro构建一个服务。(关于go-micro的使用可以参照官方实例或者文档)
//新建一个微服务 micro new --type "srv" user-srv
定义我们的服务,这里定义两个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; }
然后生成执行下面命令我们就可以发现在proto文件中多出两个文件。这个proto为我们生成的,后面会用到。
protoc --proto_path=${GOPATH}/src:. --micro_out=. --go_out=. proto/user/user.proto
写我们的业务逻辑,修改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 } } }
最后修改我们的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) } }
我们使用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的文件
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( '/user.User/Register', $argument, [UserInfo::class, 'decode'] ); }
关于这一块的代码,其实官方文档写得特别详细,具体可以参照官方文档。
新建一个路由
Router::addRoute(['GET', 'POST', 'HEAD'], '/grpc', 'App\Controller\IndexController@grpc');
编写控制器
public function grpc () { $client = new \App\Grpc\UserClient('127.0.0.1:9527', [ '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 ]; }
这时候还需要吧根目录下的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等,在实例化话的时候需要穿一个客户端过去。下面提供一个简单的实例。
<?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([ 'base_uri' => 'http://127.0.0.1:8500', ]); }); $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['Service']['Address'],$server['Service']['Port']); } } }
这时候发现一个问题如果每次请求过来都去请求一次必然给consul造成很大的负荷。既然用到了swoole框架可以在每次swoole启动的时候去请求一次,然后把服务发现的信息存起来。修改配置文件server。
'callbacks' => [ // SwooleEvent::ON_BEFORE_START => [Hyperf\Framework\Bootstrap\ServerStartCallback::class, 'beforeStart'], SwooleEvent::ON_BEFORE_START => [\App\Bootstrap\ServerStartCallback::class, 'beforeStart'], SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], ], 可以在ServerStartCallback类里面请求consul进行服务发现 后面拿到参数就好了。 namespace App\Bootstrap; use App\Register\ConsulServices; class ServerStartCallback { public function beforeStart() { $container = \Hyperf\Utils\ApplicationContext::getContainer(); $container->get(ConsulServices::class)->getServers(); } }
改造一下原来的控制器
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官网提供了一个定时器的功能,我们定时去刷服务发现就好了。
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
