extraswoft / zipkin
为swoft的zipkin-sdk
v0.0.0.1
2018-10-16 12:48 UTC
Requires
This package is not auto-updated.
Last update: 2024-09-26 02:00:53 UTC
README
简介
本项目是swoft的zipkin客户端,以非侵入式的方式对项目环境进行跟踪,并异步上报到zipkin服务器。它可以与其他swoft项目或其他语言(如Java,Go)进行全链路监控。
配置步骤
1.composer
"jcchavezs/zipkin-opentracing": "^0.1.2", "opentracing/opentracing": "1.0.0-beta5", "extraswoft/zipkin": "*"
由于opentracing/opentracing的最新版本是开发版本,因此外部项目comoposer引入时会报错。因此,需要将配置显式地放入composer.json,然后执行 composer update。
2.config/properties/app.php 添加
需要在app文件中,beanScan里加上扫描我们的命名空间
'beanScan' => [ "ExtraSwoft\\Zipkin\\" ],
3.config/beans/base.php添加我们的中间件
'serverDispatcher' => [ 'middlewares' => [ \Swoft\View\Middleware\ViewMiddleware::class, ZipkinMiddleware::class // \Swoft\Devtool\Middleware\DevToolMiddleware::class, // \Swoft\Session\Middleware\SessionMiddleware::class, ] ],
4.在.env配置文件中添加以下配置
ZIPKIN_HOST: zipkin服务器的地址
ZIPKIN_RAND: 采样率,100为100%
#Zipkin ZIPKIN_HOST=http://0.0.0.0:9411 ZIPKIN_RAND=100
5.httpClient 的修改
当我们使用swoft官方的httpClient时,需要使用我们客户端的适配器
$client = new Client(['adapter' => new AddZipkinAdapter()]);
当然,你也可以查看我们适配器的源码并将其放入自己的适配器中,这很简单
源码修改
由于mysql,redis和http请求上没有钩子函数,因此我们需要自己实现。只需在请求开始和结束时触发事件即可。建议你自己或公司项目直接fork官方的swoft-component,然后根据需要开发,并隔一段时间同步最新代码。在swoft中,使用component这个仓库的composer。
1.mysql(协程)
在src/db/src/Db.php中,在$connection->prepare($sql);前添加(注意添加命名空间)
Log::profileStart($profileKey); + App::trigger('Mysql', 'start', $profileKey, $sql); $connection->prepare($sql); $params = self::transferParams($params); $result = $connection->execute($params);
在src/db/src/DbCoResult.php中,在Log::profileEnd($this->profileKey);后添加(注意添加命名空间)
$this->release(); Log::profileEnd($this->profileKey); + App::trigger('Mysql', 'end', $this->profileKey); return $result;
2.redis (非协程),协程可以根据需要添加
在src/redis/src/Redis.php中(注意添加命名空间)
在 $result = $connection->$method(...$params);前后添加
$connectPool = App::getPool($this->poolName); /* @var ConnectionInterface $client */ $connection = $connectPool->getConnection(); + App::trigger('Redis', 'start', $method, $params); $result = $connection->$method(...$params); $connection->release(true); + App::trigger('Redis', 'end'); return $result;
3.httpClient (协程)
在src/http-client/src/Adapter/CoroutineAdapter.php中
在 $client->execute($path);前添加
if ($query !== '') $path .= '?' . $query; $client->setDefer(); + App::trigger('HttpClient', 'start', $request, $options); $client->execute($path); App::profileEnd($profileKey);
在src/http-client/src/HttpCoResult.php中
在 $client->close();后添加
$this->recv(); $result = $client->body; $client->close(); + App::trigger('HttpClient', 'end'); $headers = value(function () { $headers = [];
完成
完成以上修改后,重新composer引入新的包,然后重启项目即可
使用zipkin server
docker run -d -p 9411:9411 openzipkin/zipkin
效果图
每个swoft项目通过这些步骤后都可以进行监控了,下面是两个swoft采用之后的全链路效果图
后记
如果您想对全链路有更深入的了解,或者想了解我的项目实现,甚至想将其应用到其他PHP框架或其他语言上,可以查看我写的这篇文章php全链路监控完全实现(以swoft为例)