background
In modern distributed systems, OpenTelemetry has become a common standard for tracking and monitoring the performance and behavior of an application. OTLP (OpenTelemetry Protocol) is a data transmission protocol defined by the OpenTelemetry community, which is used to transfer tracking data between applications and tracking backends. This article will explain how to use Java to write code to receive and process OTLP data and how to integrate it into your application.
What is OTLP?
OTLP is a data transfer protocol defined by OpenTelemetry, which is used to transfer tracking data between an application and a tracking backend. It is an open standard protocol that supports multiple transmission protocols, such as gRPC, HTTP/JSON, etc. OTLP provides a unified way to transmit tracking data, allowing applications from different languages and platforms to be easily integrated into the tracking system.
Example of receiving OTLP data using Java
Receiving OTLP data in Java requires the Java SDK of OpenTelemetry. Here is a simple sample code that demonstrates how to receive and process OTLP data using Java:
import ; import ; import ; import ; import ; import ; import ; import ; import ; public class OTLPReceiverExample { public static void main(String[] args) { // Create OTLP Metric Exporter MetricExporterBuilder exporterBuilder = (); MetricExporter exporter = (); // Create Meter and Metric Producer SdkMeterProvider meterProvider = ().build(); Meter meter = ("OTLPReceiverExample"); MetricProducer metricProducer = meterProvider; // Create Interval Metric Reader IntervalMetricReaderBuilder readerBuilder = (); IntervalMetricReader reader = (exporter) .setMetricProducer(metricProducer) .build(); // Start Interval Metric Reader (); // Wait for a while to receive and process OTLP data try { (60 * 1000); // Wait for 60 seconds } catch (InterruptedException e) { (); } // Close Interval Metric Reader (); } }
This sample code creates an OTLP Metric Exporter and binds it with a Meter and Metric Producer. An Interval Metric Reader is then created and started to receive and process OTLP data. In the example, we simply waited for a while (60 seconds) to simulate the process of receiving and processing OTLP data.
How to use interface to accept OTLP data?
Data Receive
Controller
@PostMapping(value = "/log-otlp", produces = "application/x-protobuf", consumes = "application/x-protobuf") public ExportLogsServiceResponse insertOtlpLog( @RequestBody ExportLogsServiceRequest exportLogsServiceRequest) { ("insertOtlpLogs request is {}", ().print(exportLogsServiceRequest)); return (exportLogsServiceRequest); }
Intercept conversion
The normal http interface does not support the application/x-protobuf type, so you need to add an intercept and add a ProtobufHttpMessageConverter conversion.
import ; import ; import ; import ; import .MappingJackson2HttpMessageConverter; import ; import ; import ; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired AuthInterceptor authInterceptor; @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { (new ProtobufHttpMessageConverter()); // If you support JSON at the same time, you can add MappingJackson2HttpMessageConverter (new MappingJackson2HttpMessageConverter()); } @Override public void addInterceptors(InterceptorRegistry registry) { (authInterceptor).addPathPatterns("/**"); } }
Mock data sending
package ; import static .; import ; import ; import ; import ; import ; import ; import .; import .; import .; import .; import .; import .; import .; import ; import ; import ; import ; import ; import ; public class HttpDemo { public static void main(String[] args) throws InterruptedException, IOException { int i = 0; while (true) { sendData(); i++; ("This is the first execution" + i + "Second-rate"); (5000L); } } private static void sendData() throws IOException { Span span = buildSpan(); // Create ExportTraceServiceRequest ExportTraceServiceRequest requestData = () .addResourceSpans(newBuilder() .setResource(() .addAttributes(() .setKey("") .setValue(().setStringValue("darkraven").build()) .build()) .build()) .addScopeSpans(().addSpans(span))) .build(); // Create an OkHttpClient instance OkHttpClient client = new OkHttpClient(); // Replace with your interface URL String apiUrl = "http://localhost:32167/api/v1/insert/trace-otlp"; // Construct RequestBody, set to Protobuf format RequestBody body = ((), ("application/x-protobuf")); // Construct the request object Request request = new () .url(apiUrl) .post(body) .addHeader("apikey", "40c996be-cf3a-4ba0-9697-2feef2a76f0e") .build(); // Send a request and get a response try (Response response = (request).execute()) { if (!()) { throw new RuntimeException("Unexpected response code: " + response); } // Process the response content ("Response code: " + ()); ("Response body: " + ().string()); } } public static Span buildSpan() { . span = .() .setTraceId(("1234567890abcdef1234567890abcdef")) .setSpanId(("1234567890abcdef")) .setParentSpanId(("abcdef1234567890")) .setName("example-span") .setKind(..SPAN_KIND_CLIENT) .setStartTimeUnixNano(() * 1_000_000) .setEndTimeUnixNano((() + 1000) * 1_000_000) .setStatus(() .setCode(.STATUS_CODE_OK) .setMessage("example-status")) .addAttributes(() .setKey("attribute_key") .setValue(().setStringValue("attribute_value"))) .build(); return span; } public static String generateApiKey() { return ().toString(); } }
Summarize
This article describes an example of how to write code in Java to receive and process OTLP data. By using OpenTelemetry’s Java SDK, we can easily integrate OTLP data into our applications and send it to the tracking backend for analysis and monitoring via OTLP Metric Exporter. The use of the OTLP protocol makes it easier for us to implement tracking and monitoring functions in our applications, thereby better understanding of the performance and behavior of our applications.
The above is the detailed content of the complete guide to using Java to receive and process OpenTelemetry data. For more information about Java to receive and process OTLP data, please pay attention to my other related articles!