调用api获取app_id_在api调用中使用相关ID

调用api获取app_id

Written by Nico Di Rocco, Senior Software Engineer and Rolph Haspers, Engineering Manager @ Leaseweb

由Leaseweb高级软件工程师Nico Di Rocco和工程经理Rolph Haspers撰写

Over the years, the IT industry has moved from a single domain, monolithic architecture to a microservice architecture. In a microservice architecture, complex processes are split into smaller and simpler sub-processes. While this kind of architecture has many benefits, there are also some downsides — for example, if you send one request to a Leaseweb API, it ends up in multiple requests in other backend systems [FIGURE 1]. How do you keep track of requests and responses processed by multiple systems? This is where Correlation IDs come into play.

多年来,IT行业已从单一域的整体架构转变为微服务架构。 在微服务架构中,复杂的流程分为较小和较简单的子流程。 尽管这种体系结构有很多好处,但也有一些缺点-例如,如果您向Leaseweb API发送一个请求,它最终会在其他后端系统中出现多个请求[图1]。 您如何跟踪多个系统处理的请求和响应? 这是相关ID起作用的地方。

Image for post
[FIGURE 1: Example request/response flow]
[图1:示例请求/响应流程]

使用关联ID (Using a Correlation ID)

A Correlation ID is a unique, randomly generated identifier value that is added to every request and response. In a microservice architecture, the initial Correlation ID is passed to your sub-processes. If a sub-system also makes sub-requests, it will also pass the Correlation ID to those systems.

关联ID是随机生成的唯一标识符值,该标识符值被添加到每个请求和响应中。 在微服务架构中,初始“相关性ID”将传递给您的子流程。 如果子系统也发出子请求,它也会将“相关性ID”传递给那些系统。

How you pass the Correlation ID to other systems depends on your architecture. At Leaseweb we are using REST APIs a lot, with HTTP headers to pass on the Correlation ID. As a rule, we assign a Correlation ID as soon as possible, and always use a Correlation ID if it is passed on. Our public API only accepts Correlation IDs from internally trusted clients. For any other client (such as an employee or customer API clients) a new Correlation ID is generated for the request.

如何将“相关性ID”传递给其他系统取决于您的体系结构。 在Leaseweb,我们大量使用REST API,并通过HTTP标头传递相关ID。 通常,我们会尽快分配一个关联ID,如果传递了关联ID,则始终使用该ID。 我们的公共API仅接受来自内部受信任客户端的相关ID。 对于任何其他客户端(例如员工或客户API客户端),都会为该请求生成一个新的关联ID。

相关ID的实际值 (Real Value of Correlation IDs)

The real value of Correlation IDs is realized when you also log the Correlation IDs. Debugging or tracing requests becomes much easier, as you can search all of your logs for the same Correlation ID. Combined with central logging solutions (such as the ELK stack), searching logs becomes even easier and can be done by non-technical colleagues. Providing tools to your colleagues to troubleshoot issues allows them to have more responsibility and gives you more time to work on more technical projects.

当您还记录相关ID时,将实现相关ID的实际值。 调试或跟踪请求变得更加容易,因为您可以在所有日志中搜索相同的相关性ID。 结合中央日志记录解决方案(例如ELK堆栈),搜索日志变得更加容易,并且可以由非技术人员完成。 向您的同事提供工具来解决问题可以使他们承担更多责任,并给您更多时间从事更多技术项目。

We mainly use Correlation IDs at Leaseweb for debugging purposes. When an error occurs, we provide the Correlation ID to the client/customer. If users provide the Correlation ID when submitting a support ticket, we can visualize the entire process needed to fulfil the client’s initial intent. This has significantly improved the time it takes us to fix bugs.

我们主要在Leaseweb中使用“关联ID”进行调试。 发生错误时,我们会向客户/客户提供相关ID。 如果用户在提交支持通知单时提供了“关联ID”,我们可以可视化实现客户最初意图所需的整个过程。 这大大缩短了我们修复错误所需的时间。

Image for post
[FIGURE 2: Example of one Correlation ID with multiple requests]
[图2:一个具有多个请求的关联ID的示例]

Debugging issues is a time-consuming process if Correlation IDs are not used. When your environment scales, you will need to find solutions to group transactions happening in your systems. By using a Correlation ID, you can easily group requests and events in your systems, allowing you to spend more time fixing the problem and less time trying to find it.

如果不使用相关ID,则调试问题是一个耗时的过程。 当您的环境扩展时,您将需要找到解决方案以对系统中发生的交易进行分组。 通过使用“相关性ID”,您可以轻松地在系统中对请求和事件进行分组,从而使您花费更多的时间来解决问题,而花费更少的时间来查找问题。

有关如何实现关联ID的实际示例 (Practical examples on how to implement Correlation IDs)

The following examples use Symfony, a popular web application framework. These concepts can also be applied to any other framework, such as Laravel, Django, Flask or Ruby on Rails.

以下示例使用流行的Web应用程序框架Symfony。 这些概念也可以应用于任何其他框架,例如Laravel,Django,Flask或Ruby on Rails。

If you are unfamiliar with the concept of Service Containers and Dependency Injection, we recommend reading the excellent Symfony documentation about it here: https://symfony.com/doc/current/service_container.html

如果您不熟悉服务容器和依赖注入的概念,建议您在此处阅读有关它的出色Symfony文档: https : //symfony.com/doc/current/service_container.html

使用Monolog将相关ID附加到您的应用程序日志中 (Using Monolog to append Correlation IDs to your application logs)

When processing a HTTP request your application often logs some information — such as when an error occurred, or an important change made in your system that you want to keep track of. When using the Monolog logging library in PHP (https://seldaek.github.io/monolog/), you can use the concept of “Processors” (read more about that here on symfony.com).

在处理HTTP请求时,您的应用程序通常会记录一些信息,例如发生错误的时间或您要跟踪的系统中的重要更改。 在PHP中使用Monolog日志记录库( https://seldaek.github.io/monolog/ )时,可以使用“处理器”的概念(有关更多信息,请访问symfony.com )。

One way to do this is by creating a Monolog Processor class:

一种方法是创建Monolog Processor类:

<?php
namespace App\Monolog\Processor;
use Symfony\Component\HttpFoundation\RequestStack;
class CorrelationIdProcessor
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function processRecord(array $record)
{
$request = $this->requestStack->getCurrentRequest();
if (!$request) {
return;
}
$correlationId = $request->headers->get(‘X-My-Correlation-ID');
if (empty($correlationId)) {
return;
}
// If we have a correlation id include it in every monolog line
$record['extra']['correlation_id'] = $correlationId;
return $record;
}
}

Then register this class on the service container as a monolog processor in services.yml:

然后在服务容器上将此类注册为services.yml中的独白处理器:

# app/config/services.ymlservices:
App\Monolog\Processor\CorrelationIdProcessor:
arguments: ["@request_stack"]
tags:
- name: monolog.processor
method: processRecord

Now, every time you log something in your application with Monolog:

现在,每次您使用Monolog在应用程序中记录某些内容时:

$this->logger->info('shopping_cart_emptied', ['cart_id' => 123])

You will see the Correlation ID of the HTTP Request in your log files:

您将在日志文件中看到HTTP请求的相关ID:

$ grep ‘shopping_cart_emptied’ var/logs/prod.log
[2020-07-03 12:14:45] app.INFO: shopping_cart_emptied {“cart_id”: 123} {"correlation_id":"d135d5f1-3dd0-45fa-8f26-55d8d6a44876"}

You can utilize the same pattern to log the name of the user that is currently logged in, the remote IP address of the API client, or anything else that makes troubleshooting faster for you.

您可以使用相同的模式来记录当前登录的用户名,API客户端的远程IP地址或其他可以使您更快地进行故障排除的方法。

进行子请求时,使用Guzzle附加相关ID (Using Guzzle to append Correlation IDs when making sub-requests)

If your API makes API calls to other microservices (and you use Guzzle to do this) you can make use of Handlers and Middleware.

如果您的API调用了其他微服务的API(并且您使用Guzzle做到了这一点),则可以使用Handlers和Middleware

Some teams at Leaseweb depend on many downstream microservices, and can therefore have multiple guzzle clients as services on the service container. While each Guzzle client is configured with its own base URL and/or authentication, it is possible for all of the Guzzle clients to share the same HandlerStack.

Leaseweb的某些团队依赖于许多下游微服务,因此可以在服务容器上将多个guzzle客户端作为服务。 虽然每个Guzzle客户端都配置有自己的基本URL和/或身份验证,但所有Guzzle客户端都可以共享相同的HandlerStack。

First, create the middleware:

首先,创建中间件:

<?php
namespace App\Guzzle\Middleware;
use Symfony\Component\HttpFoundation\RequestStack;
use Psr\Http\Message\RequestInterface;
class CorrelationIdMiddleware
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options = []) use ($handler) {
$request = $this->requestStack->getCurrentRequest();
if (!$request) {
return $handler($request, $options);
}
$correlationId = $request->headers->get(‘X-My-Correlation-ID');
if (empty($correlationId)) {
return $handler($request, $options);
}
$request = $request->withHeader(‘X-My-Correlation-ID’, $correlationId);
return $handler($request, $options);
};
}
}

Define this middleware as service on the service container and create a HandlerStack:

将此中间件定义为服务容器上的服务并创建HandlerStack:

# app/config/services.yml
services:
correlation_id_middleware:
class: App\Guzzle\Middleware:
arguments: ["@request_stack"]
correlation_id_handler_stack:
class: GuzzleHttp\HandlerStack
factory: ['GuzzleHttp\HandlerStack', 'create']
calls:
- [push, ["@correlation_id_middleware", "correlation_id_forwarder"]]

With these two services defined, you can now configure all your Guzzle clients using the HandlerStack so that the Correlation ID of the current HTTP request is forwarded to downstream HTTP requests:

定义了这两个服务后,您现在可以使用HandlerStack配置所有Guzzle客户端,以便将当前HTTP请求的关联ID转发到下游HTTP请求:

# app/config/services.yml
services:
my_downstream_api:
class:
arguments:
- base_uri: https://my-downstream-api.example.com
handler: "@correlation_id_handler_stack”

Now every API call that you make to https://my-downstream-api.example.com will include the HTTP request header ‘X-My-Correlation-ID’ and have the same value as the Correlation ID of the current HTTP request. You can also apply the same Monolog and Guzzle tricks described here to the downstream API.

现在,您对https://my-downstream-api.example.com进行的每个API调用都将包含HTTP请求标头'X-My-Correlation-ID',并且具有与当前HTTP请求的Correlation ID相同的值。 您还可以将此处描述的相同的Monolog和Guzzle技巧应用于下游API。

在错误响应中公开相关ID (Expose Correlation IDs in error responses)

The missing link between these processes is to now expose your Correlation IDs to your users so they can also log them or use them in support cases they report to your organization.

这些流程之间缺少的链接是现在向用户公开您的关联ID,以便他们也可以记录它们或在他们向组织报告的支持案例中使用它们。

Symfony makes this easy using Event Listeners. You can define Event Listeners in Symfony to pre-process HTTP requests as well as to post-process HTTP Responses just before they are returned by Symfony to the API caller. In this example, we will create a HTTP Response listener and add the Correlation ID of the current HTTP request as a HTTP Header in the HTTP Response.

Symfony使用事件侦听器使此操作变得容易。 您可以在Symfony中定义事件侦听器,以在HTTP请求被Symfony返回给API调用者之前,对HTTP请求进行预处理和后处理。 在此示例中,我们将创建一个HTTP响应侦听器,并在HTTP响应中添加当前HTTP请求的相关ID作为HTTP头。

First, we create a service on the Service Container:

首先,我们在服务容器上创建一个服务:

<?php
namespace App\Listener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class CorrelationIdResponseListener
{
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
if (!$request) {
return;
}
$correlationId = $request->headers->get(‘X-My-Correlation-ID');
if (empty($correlationId)) {
return;
}
$event->getResponse()->headers->set(‘X-My-Correlation-ID’, $correlationId);
}
}

Now configure it as a Symfony Event Listener:

现在将其配置为Symfony事件监听器:

# app/config/services.yml
services:
correlation_id_response_listener:
class: App\Listener\CorrelationIdResponseListener
arguments: ["@request_stack"]
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

Every response that is generated by your Symfony application will now include a X-My-Correlation-ID HTTP response header with the same Correlation ID as the HTTP request.

现在,Symfony应用程序生成的每个响应都将包含一个X-My-Correlation-ID HTTP响应标头,该标头具有与HTTP请求相同的相关ID。

关联ID的值 (The Value of Correlation IDs)

Using Correlation IDs throughout your whole stack gives you more insight into all (sub)requests during a transaction. Using the right tools allows others to debug issues, giving your developers more time to work on new awesome features.

在整个堆栈中使用相关性ID,可以使您更深入地了解交易期间的所有(子)请求。 使用正确的工具可以让其他人调试问题,从而使您的开发人员有更多时间来开发新的出色功能。

Implementing Correlation IDs isn’t hard to do, and can be achieved quickly depending on your software stack. At Leaseweb, the use of Correlation IDs has saved us hours of time while debugging issues on numerous occasions.

实施关联ID并不难,并且可以根据您的软件堆栈快速实现。 在Leaseweb,使用关联ID节省了我们数小时的时间,同时还多次调试问题。

Leaseweb的技术职业 (Technical Careers at Leaseweb)

We are searching for the next generation of engineers and developers to help us build infrastructure to automate our global hosting services! If you are interested in finding out more, check out our Careers at Leaseweb.

我们正在寻找下一代工程师和开发人员,以帮助我们构建基础架构以自动化我们的全球托管服务! 如果您想了解更多信息,请在Leaseweb上查看我们的职业

Originally published at https://www.leaseweb.com/labs on July 9, 2020.

最初于 2020年7月9日 发布在 https://www.leaseweb.com/labs

翻译自: https://medium.com/leaseweb/using-correlation-ids-in-api-calls-42b1cd84813b

调用api获取app_id

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值