Commit ffa98b7c authored by Liu lu's avatar Liu lu

使用协程上下文存储request_id作为唯一的标识

parent b0966f8e
......@@ -7,6 +7,7 @@ use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Meibuyu\Micro\Annotation\AsyncCoroutine;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Context;
/**
* @Aspect(
......@@ -29,9 +30,11 @@ class AsyncCoroutineAspect extends AbstractAspect
// 切面切入后,执行对应的方法会由此来负责
// $proceedingJoinPoint 为连接点,通过该类的 process() 方法调用原方法并获得结果
// 在调用前进行某些处理
return Coroutine::create(function ()use($proceedingJoinPoint){
$fd = Context::get('log_trace_request_id');
return Coroutine::create(function ()use($proceedingJoinPoint,$fd){
try {
Context::set('log_trace_request_id',$fd);
LogTraceHandler::recordProcess(
'投递到子协程任务,id:'.Coroutine::id()
.' ,类:'.$proceedingJoinPoint->className
......
......@@ -5,8 +5,10 @@ use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;
use Meibuyu\Micro\Annotation\LogTrace;
use Meibuyu\Micro\Handler\LogTrace\LogTraceHandler;
use Psr\Http\Message\ServerRequestInterface;
/**
* @Aspect(
......@@ -27,6 +29,9 @@ class LogTraceAspect extends AbstractAspect
public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
try {
$fd = Context::get(ServerRequestInterface::class)->getSwooleRequest()->fd;
Context::set('log_trace_request_id',$fd);
$originParams = [
'called_params'=>$proceedingJoinPoint->getArguments(),
'http_params'=>make(RequestInterface::class)->all()
......
......@@ -9,6 +9,7 @@ namespace Meibuyu\Micro\Handler\LogTrace;
use Meibuyu\Micro\Model\LogTrace;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Context;
use Swoole\Server;
use Throwable;
......@@ -66,10 +67,10 @@ class LogTraceHandler
* @return string
* @throws \Exception
*/
public static function getRequestId($isInAsyncCoroutine=false)
public static function getRequestId()
{
$workId = posix_getpid();
$cid = $isInAsyncCoroutine?Coroutine::parentId(Coroutine::id()):Coroutine::id();
$cid = Context::get('log_trace_request_id');
if(!$cid) throw new \Exception('无法使用协程标记录日志');
return container(Server::class)->stats()['start_time'] .$workId. $cid;
}
......@@ -114,7 +115,7 @@ class LogTraceHandler
$logInfo .= "\n\n";
container(LogTraceQueue::class)->addToQueue([
'request_id'=>$requestId?:self::getRequestId($isInAsyncCoroutine),
'request_id'=>self::getRequestId(),
'process_info'=>$logInfo
]);
// $log = LogTrace::where('request_id', self::getRequestId())->first();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment