1. Overview
1.概述
Typically when working with HTTP calls in our web applications, we’ll want a way to capture some kind of metrics about the requests and responses. Usually, this is to monitor the size and frequency of the HTTP calls our application makes.
通常情况下,当在我们的Web应用程序中使用HTTP调用时,我们会希望有一种方法来捕获关于请求和响应的某种指标。通常情况下,这是为了监测我们的应用程序进行的HTTP调用的大小和频率。
OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. In a previous tutorial, we looked at the basics of how to work with OkHttp.
OkHttp是一个适用于Android和Java应用程序的高效HTTP和HTTP/2客户端。在之前的教程中,我们研究了如何使用OkHttp的基础。
In this tutorial, we’ll learn all about how we can capture these types of metrics using events.
在本教程中,我们将学习所有关于如何使用事件来捕获这些类型的指标。
2. Events
2.事件
As the name suggests, events provide a powerful mechanism for us to record application metrics relating to the entire HTTP call life cycle.
顾名思义,事件为我们提供了一个强大的机制来记录与整个HTTP调用生命周期有关的应用指标。
In order to subscribe to the events we are interested in all, we need to do is define an EventListener and override the methods for the events we want to capture.
为了订阅我们感兴趣的事件,我们需要做的就是定义一个EventListener并重载我们想要捕获的事件的方法。
This is particularly useful if, for example, we only want to monitor failed and successful calls. In that case, we simply override the specific methods that correspond to those events within our event listener class. We’ll see this in more detail later.
例如,如果我们只想监控失败和成功的调用,这就特别有用。在这种情况下,我们只需在我们的事件监听器类中覆盖对应于这些事件的特定方法。我们将在后面看到更多的细节。
There is at least a couple of advantages to using events in our applications:
在我们的应用程序中使用事件,至少有几个好处。
- We can use events to monitor the size and frequency of the HTTP calls our application makes
- This can help us quickly determine where we might have a bottleneck in our application
Finally, we can also use events to determine if we have an underlying problem with our network as well.
最后,我们还可以利用事件来确定我们的网络是否有潜在的问题。
3. Dependencies
3.依赖性
Of course, we’ll need to add the standard okhttp dependency to our pom.xml:
当然,我们需要将标准的okhttp依赖性添加到我们的pom.xml。
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
We’ll also need another dependency specifically for our tests. Let’s add the OkHttp mockwebserver artifact:
我们还需要另一个专门用于测试的依赖项。让我们添加OkHttp mockwebserver artifact。
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
Now that we have all the necessary dependencies configured, we can go ahead and write our first event listener.
现在我们已经配置了所有必要的依赖,我们可以继续编写我们的第一个事件监听器。
4. Event Methods and Order
4.事件方法和顺序
But before we start defining our own event listener, we’re going to take a step back and briefly look at what event methods are available to us and also the order we can expect events to arrive in. This will help us when we dive into some real examples later on.
但在我们开始定义我们自己的事件监听器之前,我们要退一步,简要地看看有哪些事件方法可供我们使用,以及我们可以期待事件到来的顺序。这将有助于我们在以后深入研究一些真实的例子。
Let’s assume we’re dealing with a successful HTTP call with no redirects or retries. Then we can expect this typical flow of method calls.
让我们假设我们正在处理一个成功的HTTP调用,没有重定向或重试。那么我们可以期待这个典型的方法调用流程。
4.1. callStart()
4.1.callStart()
This method is our entry point, and we’ll invoke it as soon as we enqueue a call or our client executes it.
这个方法是我们的入口点,一旦我们排队调用或我们的客户端执行,我们就会调用它。
4.2. proxySelectStart() and proxySelectEnd()
4.2.proxySelectStart() 和proxySelectEnd()
The first method is invoked prior to a proxy selection and likewise after proxy selection, including the lists of proxies in the order they will be attempted. This list can, of course, be empty if no proxy is configured.
第一个方法是在代理选择之前调用的,同样也是在代理选择之后调用的,包括按顺序尝试的代理的列表。当然,如果没有配置代理,这个列表可以是空的。
4.3. dnsStart() and dnsEnd()
4.3.dnsStart()/em>和dnsEnd()/em>
These methods are invoked just before DNS lookup and immediately after the DNS is resolved.
这些方法在DNS查询前和DNS解析后立即被调用。
4.4. connectStart() and connectEnd()
4.4.connectStart()和connectEnd()
These methods are invoked prior to establishing and closing a socket connection.
这些方法在建立和关闭一个套接字连接之前被调用。
4.5. secureConnectStart() and secureConnectEnd()
4.5.secureConnectStart()和secureConnectEnd()
If our call uses HTTPS, then interspersed between connectStart and connectEnd we’ll have these secure connect variations.
如果我们的调用使用HTTPS,那么在connectStart和connectEnd之间,我们会有这些安全连接的变化。
4.6. connectionAcquired() and connectionReleased()
4.6.connectionAcquired()和connectionReleased()
Called after a connection has been acquired or released.
在获得或释放一个连接后调用。
4.7. requestHeadersStart() and requestHeadersEnd()
4.7.requestHeadersStart()和requestHeadersEnd()
These methods will be invoked immediately prior to and after sending request headers.
这些方法将在发送请求头文件之前和之后立即被调用。
4.8. requestBodyStart() and requestBodyEnd()
4.8.requestBodyStart()和requestBodyEnd()
As the name suggests, invoked prior to sending a request body. Of course, this will only apply to requests that contain a body.
顾名思义,在发送请求正文之前调用。当然,这只适用于包含主体的请求。
4.9. responseHeadersStart() and responseHeadersEnd()
4.9.responseHeadersStart()和responseHeadersEnd()
These methods are called when response headers are first returned from the server and immediately after they are received.
这些方法在第一次从服务器返回响应头时和收到响应头后立即被调用。
4.10. responseBodyStart() and responseBodyEnd()
4.10.responseBodyStart()和responseBodyEnd()
Likewise, called when the response body is first returned from the server and immediately after the body is received.
同样地,在第一次从服务器返回响应体时和收到响应体后立即调用。
In addition to these methods, we also have three additional methods we can use for capturing failures:
除了这些方法之外,我们还有三种额外的方法可以用来捕获失败:。
4.11. callFailed(), responseFailed(), and requestFailed()
4.11.callFailed()、responseFailed()和requestFailed()
If our call fails permanently, the request has a write failure, or the response has a read failure.
如果我们的调用永久失败,请求有写失败,或者响应有读失败。
5. Defining a Simple Event Listener
5.定义一个简单的事件监听器
Let’s start by defining our own even listener. To keep things really simple, our event listener will log when the call starts and ends along with some request and response header information:
让我们从定义我们自己的偶数监听器开始。为了使事情变得非常简单,我们的事件监听器将记录呼叫开始和结束的时间以及一些请求和响应头信息。
public class SimpleLogEventsListener extends EventListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLogEventsListener.class);
@Override
public void callStart(Call call) {
LOGGER.info("callStart at {}", LocalDateTime.now());
}
@Override
public void requestHeadersEnd(Call call, Request request) {
LOGGER.info("requestHeadersEnd at {} with headers {}", LocalDateTime.now(), request.headers());
}
@Override
public void responseHeadersEnd(Call call, Response response) {
LOGGER.info("responseHeadersEnd at {} with headers {}", LocalDateTime.now(), response.headers());
}
@Override
public void callEnd(Call call) {
LOGGER.info("callEnd at {}", LocalDateTime.now());
}
}
As we can see, to create our listener, all we need to do is extend from the EventListener class. Then we can go ahead and override the methods for the events we care about.
正如我们所看到的,为了创建我们的监听器,我们需要做的只是从EventListener类中扩展出来。然后我们可以继续为我们所关心的事件覆盖方法。
In our simple listener, we log the time the call starts and ends along with the request and response headers when they arrive.
在我们的简单监听器中,我们记录了呼叫开始和结束的时间,以及请求和响应头信息的到达。
5.1. Plugging It Together
5.1.把它插在一起
To actually make use of this listener, all we need to do is call the eventListener method when we build our OkHttpClient instance, and it should just work:
要实际利用这个监听器,我们需要做的就是在构建我们的OkHttpClient实例时调用eventListener方法,它应该就能工作。
OkHttpClient client = new OkHttpClient.Builder()
.eventListener(new SimpleLogEventsListener())
.build();
In the next section, we’ll take a look at how we can test our new listener.
在下一节,我们将看看如何测试我们的新听众。
5.2. Testing the Event Listener
5.2.测试事件监听器
Now, we have defined our first event listener; let’s go ahead and write our first integration test:
现在,我们已经定义了我们的第一个事件监听器;让我们继续写我们的第一个集成测试。
@Rule
public MockWebServer server = new MockWebServer();
@Test
public void givenSimpleEventLogger_whenRequestSent_thenCallsLogged() throws IOException {
server.enqueue(new MockResponse().setBody("Hello Baeldung Readers!"));
OkHttpClient client = new OkHttpClient.Builder()
.eventListener(new SimpleLogEventsListener())
.build();
Request request = new Request.Builder()
.url(server.url("/"))
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals("Response code should be: ", 200, response.code());
assertEquals("Body should be: ", "Hello Baeldung Readers!", response.body().string());
}
}
First of all, we are using the OkHttp MockWebServer JUnit rule.
首先,我们正在使用OkHttp MockWebServer JUnit规则。
This is a lightweight, scriptable web server for testing HTTP clients that we’re going to use to test our event listeners. By using this rule, we’ll create a clean instance of the server for every integration test.
这是一个用于测试HTTP客户端的轻量级、可编写脚本的网络服务器,我们要用它来测试我们的事件监听器。通过使用这个规则,我们将为每个集成测试创建一个干净的服务器实例。
With that in mind, let’s now walk through the key parts of our test:
考虑到这一点,现在让我们走过我们测试的关键部分。
- First of all, we set up a mock response that contains a simple message in the body
- Then, we build our OkHttpClient and configure our SimpleLogEventsListener
- Finally, we send the request and check the response code and body received using assertions
5.3. Running the Test
5.3.运行测试
When we run our test, we’ll see our events logged:
当我们运行我们的测试时,我们会看到我们的事件被记录下来。
callStart at 2021-05-04T17:51:33.024
...
requestHeadersEnd at 2021-05-04T17:51:33.046 with headers User-Agent: A Baeldung Reader
Host: localhost:51748
Connection: Keep-Alive
Accept-Encoding: gzip
...
responseHeadersEnd at 2021-05-04T17:51:33.053 with headers Content-Length: 23
callEnd at 2021-05-04T17:51:33.055
6. Putting It All Together
6.归纳总结
Now let’s imagine we want to build on our simple logging example and record the elapsed times for each of the steps in our call chain:
现在让我们想象一下,我们想在我们简单的记录例子的基础上,记录我们调用链中每个步骤的时间流逝。
public class EventTimer extends EventListener {
private long start;
private void logTimedEvent(String name) {
long now = System.nanoTime();
if (name.equals("callStart")) {
start = now;
}
long elapsedNanos = now - start;
System.out.printf("%.3f %s%n", elapsedNanos / 1000000000d, name);
}
@Override
public void callStart(Call call) {
logTimedEvent("callStart");
}
// More event listener methods
}
This is very similar to our first example, but this time we capture the elapsed time from when our call started for each event. Typically this could be quite interesting to detect network latency.
这与我们的第一个例子非常相似,但这次我们捕捉到了每个事件从我们的调用开始时经过的时间。通常情况下,这对于检测网络延迟是非常有趣的。
Let’s take a look if we run this against a real site like our very own https://www.baeldung.com/:
让我们来看看,如果我们针对一个真实的网站,如我们自己的https://www.baeldung.com/,运行这个程序。
0.000 callStart
0.012 proxySelectStart
0.012 proxySelectEnd
0.012 dnsStart
0.175 dnsEnd
0.183 connectStart
0.248 secureConnectStart
0.608 secureConnectEnd
0.608 connectEnd
0.609 connectionAcquired
0.612 requestHeadersStart
0.613 requestHeadersEnd
0.706 responseHeadersStart
0.707 responseHeadersEnd
0.765 responseBodyStart
0.765 responseBodyEnd
0.765 connectionReleased
0.765 callEnd
As this call is going over HTTPS, we’ll also see the secureConnectStart and secureConnectStart events.
由于这个调用是通过HTTPS进行的,我们也会看到secureConnectStart和secureConnectStart事件。
7. Monitoring Failed Calls
7.监测失败的呼叫
Up until now, we’ve focussed on successfully HTTP requests, but we can also capture failed events:
到目前为止,我们主要关注的是成功的HTTP请求,但我们也可以捕捉失败的事件。
@Test (expected = SocketTimeoutException.class)
public void givenConnectionError_whenRequestSent_thenFailedCallsLogged() throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.eventListener(new EventTimer())
.build();
Request request = new Request.Builder()
.url(server.url("/"))
.build();
client.newCall(request).execute();
}
In this example, we’ve deliberately avoided setting up our mock web server, which means, of course, we’ll see a catastrophic failure in the form of a SocketTimeoutException.
在这个例子中,我们故意避免设置我们的模拟Web服务器,这意味着,当然,我们将看到一个灾难性的失败,其形式为SocketTimeoutException。
Let’s take a look at the output when we run our test now:
让我们看看我们现在运行测试时的输出。
0.000 callStart
...
10.008 responseFailed
10.009 connectionReleased
10.009 callFailed
As expected, we’ll see our call start, and then after 10 seconds, the connection timeout occurs, and consequently, we see the responseFailed and callFailed events logged.
正如预期的那样,我们将看到我们的呼叫开始,然后在10秒后,连接超时发生,因此,我们看到responseFailed和callFailed事件被记录。
8. A Quick Word on Concurrency
8.关于并发性的简短说明
So far, we have assumed that we do not have multiple calls executing concurrently. If we want to accommodate this scenario, then we need to use the eventListenerFactory method when we configure our OkHttpClient.
到目前为止,我们假设我们没有多个调用在同时执行并发。如果我们想适应这种情况,那么我们需要在配置我们的OkHttpClient时使用eventListenerFactory方法。
We can use a factory to create a new EventListener instance for each HTTP call. When we use this approach, it is possible to keep a call-specific state in our listener.
我们可以使用一个工厂来为每个HTTP调用创建一个新的EventListener实例。当我们使用这种方法时,就有可能在我们的监听器中保持一个特定于呼叫的状态。
9. Conclusion
9.结语
In this article, we’ve learned all about how to capture events using OkHttp. First, we began by explaining what an event is and understanding what kind of events are available to us and the order they arrive in when processing an HTTP call.
在这篇文章中,我们已经了解了所有关于如何使用OkHttp捕获事件。首先,我们首先解释了什么是事件,并了解了什么样的事件是我们可以利用的,以及在处理一个HTTP调用时它们到达的顺序。
Then we took a look at how we can define a simple event logger to capture parts of our HTTP calls and how to write an integration test.
然后,我们看了一下如何定义一个简单的事件记录器来捕获我们的HTTP调用的一部分,以及如何写一个集成测试。
As always, the full source code of the article is available over on GitHub.
一如既往,该文章的完整源代码可在GitHub上获得。