
首先我们用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 <p> </p><p>最后修改我们的main.go文件,服务发现使用时consul。</p><pre class="brush:php;toolbar:false">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.zipunzip consul_1.6.1_linux_amd64.zipmv 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 appgrpc;
use gomicrosrvuserregisterrequest;
use gomicrosrvuseruserinfo;
use hyperfgrpcclientbaseclient;
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', 'appcontrollerindexcontroller@grpc');
编写控制器
public function grpc ()
{
$client = new appgrpcuserclient('127.0.0.1:9527', [
'credentials' => null,
]);
$request = new registerrequest();
$request->setemail("741001560@qq.com");
$request->setusername("chensi");
$request->setpassword("123456");
/**
* @var grpchireply $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 appregister;
use hyperfconsulhealth;
use psrcontainercontainerinterface;
use hyperfguzzleclientfactory;
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 => [hyperfframeworkbootstrapserverstartcallback::class, 'beforestart'],
swooleevent::on_before_start => [appbootstrapserverstartcallback::class, 'beforestart'],
swooleevent::on_worker_start => [hyperfframeworkbootstrapworkerstartcallback::class, 'onworkerstart'],
swooleevent::on_pipe_message => [hyperfframeworkbootstrappipemessagecallback::class, 'onpipemessage'],
],
可以在serverstartcallback类里面请求consul进行服务发现 后面拿到参数就好了。
namespace appbootstrap;
use appregisterconsulservices;
class serverstartcallback
{
public function beforestart()
{
$container = hyperfutilsapplicationcontext::getcontainer();
$container->get(consulservices::class)->getservers();
}
}
改造一下原来的控制器
public function grpc ()
{
$container = hyperfutilsapplicationcontext::getcontainer();
$servers = $container->get(consulservices::class)->servers;
if (empty($servers)) {
return [
'errcode' => 1000,
'msg' => '服务不存在',
];
}
$key = array_rand($servers,1); // 哈哈哈一个简单的负载均衡
$hostname = $servers[$key];
$client = new appgrpcuserclient($hostname, [
'credentials' => null,
]);
$request = new registerrequest();
$request->setemail("741001560@qq.com");
$request->setusername("chensi");
$request->setpassword("123456");
/**
* @var grpchireply $reply
*/
list($reply, $status) = $client->register($request);
$message = $reply->getid();
return [
'id' => $message
];
}
重启服务,这时候然后刷新浏览器试试。这时候一个简单基于go rpc server和php client的微服务就搭建完成了。当然了这时候还没有心跳机制,hyperf官网提供了一个定时器的功能,我们定时去刷服务发现就好了。
以上就是go-micro+php+consul实现简单的微服务的详细内容,更多请关注代码网其它相关文章!
发表评论