<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aviad Pines on Medium]]></title>
        <description><![CDATA[Stories by Aviad Pines on Medium]]></description>
        <link>https://medium.com/@aviadpines?source=rss-8c003a9a87e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Y081klVHApLxr0WZbNPpUg.jpeg</url>
            <title>Stories by Aviad Pines on Medium</title>
            <link>https://medium.com/@aviadpines?source=rss-8c003a9a87e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:31:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aviadpines/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding Critical Metrics to Spring Cloud Stream EventHub]]></title>
            <link>https://medium.com/@aviadpines/adding-critical-metrics-to-spring-cloud-stream-eventhub-39396f09ebb1?source=rss-8c003a9a87e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/39396f09ebb1</guid>
            <category><![CDATA[micrometer]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[event-hub]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Aviad Pines]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 12:56:44 GMT</pubDate>
            <atom:updated>2022-04-18T12:56:44.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Our production environments consist mainly of Spring Cloud Stream microservices, using EventHubs as their primary broker. As with every production-ready environment, we want to know whenever our services behave out of the norm. We do it by publishing constant metrics.</p><p>Spring Cloud Stream leverages Spring Boot Actuator and comes packed with an abundance of valuable metrics out of the box. Looking at our services, we saw that we are missing a few, mainly related to the broker we are consuming our messages from — the EventHub itself.</p><p>This article will explore how we have implemented an easily-expandable solution that gathers additional critical information about the arriving messages and the EventHub from which we consume these messages.</p><h3>What you should know already</h3><p>When writing this article, I took the liberty to assume that you are familiar with Spring Cloud Stream and metrics (in general and how they are used in Spring Boot).</p><p>If you need a quick refresher, look at the example services we have in our <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder">repository</a> (and another <a href="https://github.com/avpines/event-hub-binder-example">legacy repository</a>). Each uses the metrics library that we will describe here.</p><h3>Versions</h3><p>The code was written with the following Spring dependencies versions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a340a3cfd15c4227efe238baa254796/href">https://medium.com/media/8a340a3cfd15c4227efe238baa254796/href</a></iframe><h3>Needed EventHub metrics</h3><p>First and foremost, we were missing a metric to know the <strong><em>EventHub backlog size</em></strong>. This is a critical metric that without it, it will be harder to know if and by how much we need to scale up the related services.</p><p>The second metric is a <strong>counter</strong> to the <strong><em>number of messages consumed</em></strong>. This can tell us if we degraded our performance in the last deployment or something impeded our throughput (throughput comes free of charge when using a counter).</p><p>The third and final metric that we will see in this article is the <strong><em>batch size</em></strong> — count the number of messages per batch when a batch consumer is used. This metric can help us tweak our parameters, especially when using time-based batching.</p><p>The second and third metrics are not as critical, just helpful. The first metric, the backlog size, is an absolute must. Granted, you can get estimations by using the delay between when the message was enqueued and when it was processed, but this is more error-prone just by itself.</p><h3>Bird’s-eye view</h3><p>As we will see, to calculate our metrics, we need to intercept the incoming messages. We will do so by implementing the BindingMeterInterceptor, which will intercept each message and propagate it to all the beans of type MetricListener, and interface of our own as well.</p><p>Next, we will map our tags so that we will be able to identify from where the message came from, regardless of how a specific service named it — we will use the names as described in Azure and not service-specific terms like binder or binding. Since this code will be common to all metrics classes, it will reside in an abstract parent class AbstractMeterListener.</p><p>Finally, we will implement our actual metric classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHd6TQQo0sSg8gs6Uk5UIg.png" /></figure><h3>It’s in the headers</h3><p>One common thing to all of the metrics that we want is that they get information from the incoming message headers. The backlog size, for example, can be calculated by getting the message’s sequence number and subtracting it from the last sequence number that was enqueued to the EventHub. We can get both sequence numbers from the headers:</p><ol><li>The header name of the sequence number of the <em>current </em>message depends on whether we use a regular (not batch) or batch consumer. When using a regular consumer, the header will be azure_eventhubs_sequence_number, and when using a batch consumer, the header will be azure_eventhubs_batch_converted_sequence_number.</li><li>The sequence number of the <em>last</em> message that was enqueued to the EventHub can be found in the LastEnqueuedEventProperties instance, fetched from the azure_eventhubs_last_enqueued_event_properties header.</li><li>The difference between them is the amount of sequence numbers left in the EventHub, i.e. the EventHub backlog size.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e5e25509ccbe743f582d7e2def780c2/href">https://medium.com/media/9e5e25509ccbe743f582d7e2def780c2/href</a></iframe><h4>Last enqueued properties header</h4><p>The information about the last enqueued message is not present in the message headers by default, and they can be enabled via the spring.cloud.stream.eventhubs.bindings.&lt;binding_name&gt;.consumer.track-last-enqueued-event-properties, e.g.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d48d444ba34d75e599ec7eeb539a2505/href">https://medium.com/media/d48d444ba34d75e599ec7eeb539a2505/href</a></iframe><p>When enabled, all the properties should reside under the header azure_eventhubs_last_enqueued_event_properties</p><h3>Listen to all the messages</h3><p>So to get the information that we need, we need to review all incoming message headers. One easy way to do so is by using Spring’s <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/messaging/support/ChannelInterceptor.html">ChannelInterceptor</a> mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*qWenb9Gy2gDXj5WSZwG0lw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cabd1afeb0135b6406ed0b40a6240ffa/href">https://medium.com/media/cabd1afeb0135b6406ed0b40a6240ffa/href</a></iframe><p>ChannelInterceptor has multiple entry points that we can intercept the message. We will use public void afterSendCompletion(Message&lt;?&gt; message, MessageChannel channel, boolean sent, Exception ex):</p><ol><li>It will be invoked after sending, whether the message was sent successfully, failed, an exception was raised, etc.</li><li>Other methods might not be invoked from all channels types. For example, afterReceiveCompletion(Message&lt;?&gt; message, MessageChannel channel, Exception ex, Deque&lt;ChannelInterceptor&gt; interceptorStack) will only be invoked via channels implementing PollableChannel, so the simplest consumer DirectWithAttributesChannel, will not invoke this method.</li></ol><p>Since we want our solution to be extendable, we don’t want to calculate the information in afterSendCompletion or the class itself, as this can quickly devolve into an unmaintainable mess.</p><p>Instead, we will create a MeterListener interface and have our interceptor Autowire all the beans of that interface, propagating the information to them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d8f922b48ea1756c8fe14b9d9eeca11/href">https://medium.com/media/9d8f922b48ea1756c8fe14b9d9eeca11/href</a></iframe><p>We pass all the information we’ve received from afterSendCompletion except the message payload itself. Since the method will be invoked after working on the message (it was consumed or sent to the next broker), we can also propagate the payload. Since we wanted something that would work for all our services, agnostic to the payload, we’ve decided not to pass it to the listeners.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e658df14fcabcb086846fb8948bbc2c9/href">https://medium.com/media/e658df14fcabcb086846fb8948bbc2c9/href</a></iframe><h3>Adding meters</h3><p>We now have a way to get all the messages passed to our service, we know how to calculate what we want, it’s time to add the meters.</p><h4>Slicing the data</h4><p>Before implementing, we need to decide how to <strong>slice our data,</strong> i.e., what tags do we want. We want to know from which EventHub (destination) we are consuming, but is this enough? An EventHub can have up to 32 <a href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-features#partitions">partitions</a>, and each such partition has its offset. When a consumer consumes a message, it is consumed and <a href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-features#checkpointing">checkpointed</a> from a specific partition. Potentially, we can have a problem in one partition that we will miss because our granularity only allows us to look at the entire EventHub. Backlog size is a good example — the overall backlog decreases, hiding a single problematic partition. <strong>We want to be able to slice our data per partition as well</strong>.</p><p>What about consumer groups? Each consumer group provides a separate view, such that two services can consume events from the same EventHub and its partitions at their own pace. This means that we can have a partition stuck for one consumer group but not on another, which we can easily miss if we don’t have this granularity. <strong>We need to add the group as well to our tags</strong>.</p><p>The last thing to consider is that an EventHub name is unique in its namespace, so to ensure that we know for sure what EventHub we are consuming from, <strong>we need to add the namespace as well.</strong></p><p>To summarize, the tags we want to pinpoint the EventHub we measure are <strong>namespace</strong>, <strong>destination</strong>, <strong>group</strong>, and <strong>partition</strong>. This holds not only for measuring the backlog size but also for other metrics.</p><h4>Fetching the data</h4><p>Now that we have established what tags we need let’s see how we get this data. We’ll use an example application.yaml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c5aeed1102d6ca87c50ad8d56e6072/href">https://medium.com/media/36c5aeed1102d6ca87c50ad8d56e6072/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*ZyNEC5bq4kq1opuOBhP7Mw.png" /></figure><p>Let’s start by creating a class that we will use to parse all the information. Since the information that we fetch will be used by all the metrics, we can make this class an abstract class that will serve as the parent of the specific metrics classes.</p><p>All the binders and binding information that we need from the application.yaml is already parsed by Spring Cloud Stream and stored in the BindingServiceProperties , so we will Autowire it to our class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/441eedd073907e9579f666ddcd6abb43/href">https://medium.com/media/441eedd073907e9579f666ddcd6abb43/href</a></iframe><h4>Getting the destination and group</h4><p>Let’s start our parsing with the destination and group information:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f7746945a5cf46159955c035c98a85a/href">https://medium.com/media/2f7746945a5cf46159955c035c98a85a/href</a></iframe><p>Each binding information resides in a BindingProperties, which can be fetched from the BindingServiceProperties via bindingServiceProperties.getBindingProperties(“my-binding-in-0”). But how do we get the binding name from the code? Our channel of type MessageChannel doesn’t provide a lot of information. We have two ways:<br>If the channel extends AbstractMessageChannel, which there’s an excellent chance that it is (almost all the channels inherit from it), then we can call getBeanName(), it will give us exactly what we want (the bean name is the binding name).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64209e8cfaae52274c9a3d1cb85c90ea/href">https://medium.com/media/64209e8cfaae52274c9a3d1cb85c90ea/href</a></iframe><p>If the channel does not extend AbstractMessageChannel, we can attempt to parse the name from its toString(). A vast majority of Spring Integration’s framework uses IntegrationObjectSupport; this includes the message channels. Its toString() has the format bean &#39;bindingName&#39;, in our case, it will be bean ’my-binding-in-0&#39;. Getting the name of the binding from this string can be done via:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6de72fed0c1ecfe300bedb821f55f91c/href">https://medium.com/media/6de72fed0c1ecfe300bedb821f55f91c/href</a></iframe><p>Putting this all together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1044b3922f8e378cdc024f14acc9dcd4/href">https://medium.com/media/1044b3922f8e378cdc024f14acc9dcd4/href</a></iframe><p>Once we have the binding, we can get the destination via BindingProperties::getDestination, and the group via BindingProperties::getGroup:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4319f45c5d9222baa4b924b1de85823/href">https://medium.com/media/d4319f45c5d9222baa4b924b1de85823/href</a></iframe><h4>Getting the namespace</h4><p>Next, let’s extract the namespace. The namespace can be given either directly (if we are connecting via Service Principal or Managed Identity)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e31060e3f9b513c5cb67bd0766c41dc/href">https://medium.com/media/4e31060e3f9b513c5cb67bd0766c41dc/href</a></iframe><p>or by extracting it from the connection string</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cecd16b04360d34919587ee068bdf461/href">https://medium.com/media/cecd16b04360d34919587ee068bdf461/href</a></iframe><p>Both can be extracted from the binder’s environment spring.cloud.stream.binders.&lt;my-binder&gt;.environment</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0187e3b13e284496dc99bf49e0b506b5/href">https://medium.com/media/0187e3b13e284496dc99bf49e0b506b5/href</a></iframe><p>That’s a lot to digest. Let’s dive in:</p><p>We need to get the BinderProperties via the bindingServiceProperties.getBinders().get(”binderName”), the binder name is retrieved via fetchBinder(@NotNull MessageChannel channel) .</p><p>fetchBinderfirst tries to callBindingProperties#getBinder to get the binder name, with a caveat — if the binder is not specifically set in the binding, the default binder will be used, and BindingProperties#getBinder will return null. The default binder can be fetched via BindingServiceProperties#getDefaultBinder() but only if the property spring.cloud.stream.default-binder was explicitly set. Otherwise it will return null as well. Another way to find the default binder is by iterating over all the binders and filtering the default candidate — precisely what we do in fetchDefaultCandidate(). Spring Cloud Stream will ensure that we have only one and will fail the application if more than one, or none, were found.</p><p>Once we have the binder, we need to parse the environment, traverse over spring.cloud.azure.eventhubs (common to both the namespace and connection string) to get the last parameter, either namespace or connectrion-string.</p><p>If we are provided with the namespace, return it. If we are provided with the connection string, we need to parse it with parseConnectionString(@Nullable String connectionString). The connection String is in the format Endpoint=sb://my-eventhub-namespace.servicebus.windows.net/;SharedAccessKeyName=…;SharedAccessKey=…, we extract the namespace my-eventhub-namespace with the regex .*sb://(.*?)/, the name will be in the capture group.</p><p>Finally, if we don’t have the namespace or the connection string, we return “UNKNOWN”.</p><h4>Getting the partition</h4><p>The last property that we need to fetch is the partition, which is the only property that we use the header for and not the binding properties. The partition resides in one of two headers, azure_partition_id or azure_raw_partition_id:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/212fc0fc0881b189f9f3e3631a03372f/href">https://medium.com/media/212fc0fc0881b189f9f3e3631a03372f/href</a></iframe><p>(All EventHub headers can be found in com.azure.spring.eventhubs.support.EventHubsHeaders)</p><h3>Propagate the information to child classes</h3><p>Now that we know how to calculate all the values, we need to decide how to propagate them to the child classes. We can make all the appropriate methods protected, and each child class will call them to get the information, but that sounds like something that will lead to an error-prone code with a lot of duplications. Instead, we will first create an inner class that will hold all the new information:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a29e7ca06c5a1a94f3a4e2af740670f/href">https://medium.com/media/0a29e7ca06c5a1a94f3a4e2af740670f/href</a></iframe><p>We will override MeterListener’s void capture(MessageHeaders headers, MessageChannel channel, boolean sent, Exception ex) and use it to populate our new class. We will create an abstract method that our child classes will need to implement that uses this class. In short:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/105d62741ce77b7130e20ba30d8b32c5/href">https://medium.com/media/105d62741ce77b7130e20ba30d8b32c5/href</a></iframe><p>Our child classes will have to implement doCapture(EventInfo event).</p><p>Our AbstractMeterListener so far, with some tidying up, making a few strings constants, etc.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d3da33946352a55b158509fc2954b1d/href">https://medium.com/media/2d3da33946352a55b158509fc2954b1d/href</a></iframe><h3>Implement the Backlog class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SnQ-8A20R_rQadMBD0LwxQ.png" /></figure><p>At this point, we almost have everything we need — we have the tag information given to us in the doCapture method. We know how to calculate the backlog size (we saw how to do it with the computeSize method at the beginning of this article). All we are left with is to create the meter. Each meter will have to be registered with a MeterRegistry (All Micrometer meters have to). We need to see how we get a hold of one.</p><p><a href="https://medium.com/@aviadpines/dynamic-meters-and-metrics-with-micrometer-e7e16ce52371">Dynamic Meters and Metrics with Micrometer</a></p><p>We will do so by using MicroMeter’s MeterBinder interface, which lets you bind to a given registry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9ac3bdc859172747f018511a645884f/href">https://medium.com/media/d9ac3bdc859172747f018511a645884f/href</a></iframe><p>Spring Boot utilizes this interface and via the MeterRegistryConfigurer ensures that all MeterBinder beans will be called and bound to a Spring-managed meter registry. Sounds perfect — Our Backlog class will implement this interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dafe56768f83a2af12f9bfe3ce96fc7/href">https://medium.com/media/3dafe56768f83a2af12f9bfe3ce96fc7/href</a></iframe><p>Let’s review. Our class uses a SupplierDynamicGauge, a <a href="https://medium.com/@aviadpines/dynamic-meters-and-metrics-with-micrometer-e7e16ce52371">dynamic binder</a> (You can replace this implementation with pure Micrometer meters). Spring will call bindTo, at which point we will create our Gauge, with the tags discussed before — namespace, destination, group, and partition.<br>With Gauges, we need to have access to the object they measure, in this case, an AtomicLong. We hold all the objects in the handles map. Each time we receive a new event, we get the relevant handle or create it if it does not exist. Afterward, we calculate the size and set the object to that computed value visible by the gauge.</p><p>MeterBinder is nice, but it introduces a new problem for us — at some point we are going to be bound to the registry, but what happens if doCapture is called before we are bounded? This can be easily solved with a flag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cba5c2af958faf8ffae42e30b890264b/href">https://medium.com/media/cba5c2af958faf8ffae42e30b890264b/href</a></iframe><p>We will not use the meters until we know that they are bounded. Since the binding is part of Spring’s startup, we know the meters will be bound to a registry on startup. We are just taking a precaution in case the interceptor was initialized before.</p><h3>Adding batch support</h3><p>Currently, our Backlog class does not support a batch consumer because our computeSize(<a href="http://twitter.com/NotNull">@NotNull</a> EventInfo event) method assumes that the header is always EventHubsHeaders.SEQUENCE_NUMBER and is of type Long. This is not the case when dealing with a batch consumer. With a batch consumer, some of the headers have different names, are of type list, and contain all the information of each of the messages in the batch. <br>When consuming a single record, the headers are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47707e354e87ebf905e8ce4da90504fc/href">https://medium.com/media/47707e354e87ebf905e8ce4da90504fc/href</a></iframe><p>When consuming a batch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1c2024429d2a223e0054eb6f0e8e08d/href">https://medium.com/media/a1c2024429d2a223e0054eb6f0e8e08d/href</a></iframe><p>And each such list contains the information about each one of the events inside the batch, e.g,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/504e97d10a571d3628a20f28745e0f2b/href">https://medium.com/media/504e97d10a571d3628a20f28745e0f2b/href</a></iframe><p>Let’s change our method to support both options, either a long or a list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b354fcd2c88b48f24d858742c8276333/href">https://medium.com/media/b354fcd2c88b48f24d858742c8276333/href</a></iframe><p>We retrieve the header as Object, and check if it can be assigned to a list — if it can, we cast it and return the value of the last entry (the highest sequence number). We treat it as a single record if it’s not a list and cast it as long.<br>Note that if we get an empty list, it doesn’t necessarily mean that we don’t have any messages in the backlog — it can also mean that no messages were fetched in the allotted interval (when doing time-based batching). This is why we treat an empty list as a null value.</p><h3>Let’s see the output</h3><p>We will add a @Bean of type LoggingMeterRegistry to our consumer, and see the output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01525a972396322e7b801c4a6c1f5a9e/href">https://medium.com/media/01525a972396322e7b801c4a6c1f5a9e/href</a></iframe><h3>Last-minute changes and refactoring</h3><p>One of the changes that can be seen in the <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/main/eventhub-metrics">source on GitHub</a> is that I have refactored some of the code we created in AbstractMeterListener and moved it to a new class, EventHubPropertyExtractor. This is a non-mandatory design decision to separate between the two responsibilities — one is to capture the information and pass them to the specific listeners, while the other is more of a utility design to extract data from an EventHub.</p><p>Another change that we have made is to add autoconfiguration, so that any project that wishes to use the meters needs only to add this project as its dependency.</p><h3>Final thoughts and additional metrics</h3><p>In this article, we saw only one metric, the backlog size. However, we created a mechanism that will allow us to quickly implement additional metrics based on the information received from the EventHubs.</p><p>We have more examples in the source code, such as:</p><ol><li>The backlog delay (the difference between the enqueue time of the current and last events in the EventHub),</li><li>Absolute delay (the difference between now and the enqueue time of the last event),</li><li>Batch size when consuming batches.</li><li>The overall number of events processed.</li></ol><p>These meters are partitioned with the exact dimensions we used for the backlog size.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39396f09ebb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing Internal EventHub Client With Spring Cloud Stream]]></title>
            <link>https://medium.com/@aviadpines/customizing-internal-eventhub-client-with-spring-cloud-stream-ab3dd049f3a0?source=rss-8c003a9a87e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3dd049f3a0</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[event-hub]]></category>
            <dc:creator><![CDATA[Aviad Pines]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 08:28:43 GMT</pubDate>
            <atom:updated>2022-04-08T08:28:43.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>Customizing Internal Event Hubs Client With Spring Cloud Stream</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kSGt1prXE6eMky6l" /><figcaption>Photo by <a href="https://unsplash.com/@luk10?utm_source=medium&amp;utm_medium=referral">Lukas Tennie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Preface</h3><p>Spring Cloud allows us to create an event-driven application without worrying about the internal implementation of the specific broker that we are publishing to consume from. Having said that, when and if we do need to access a broker-specific parameter, we only have access to what the binder exposes to us via the application properties.</p><p>When it comes to the Spring Cloud Stream for Event Hubs, all the internal clients’ configurations (EventHubProducerAsyncClient and EventProcessorClient) are done for us via autoconfiguration. Most configurations are already exposed via the application properties, but what happens if we want to tweak the internal client directly?</p><p>We will show how to do just that and see how we can gain access to the internal clients.</p><h3>Customizing the Binder</h3><p>Since Spring Cloud Stream creates an Application Context per binder, we need to first gain access to these contexts. We can do that via the org.springframework.cloud.stream.binder.BinderCustomizer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef2819f568e1e1654417cfa96020bb7/href">https://medium.com/media/7ef2819f568e1e1654417cfa96020bb7/href</a></iframe><p>Only one such customizer is created during initialization, so we need to customize all of our binders via that Bean. Our Binder implementation, used in the Event Hubs binder, is of type EventHubsMessageChannelBinder. Due to the generics on the binder parameter, casting it to EventHubsMessageChannelBinder is done in two hops. The first hop is to eliminate the generic parameters, and the second is to cast it to the actual class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6baa08a16113e5cfb36da05bd25bd041/href">https://medium.com/media/6baa08a16113e5cfb36da05bd25bd041/href</a></iframe><p>The first casting to Binder simply eliminates the generics. In case we are using multiple binder types, and we want to do some checking before casting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ba929741ec61a21071c583469aee78/href">https://medium.com/media/98ba929741ec61a21071c583469aee78/href</a></iframe><p>We will later use the EventHubsMessageChannelBinder#addProducerFactoryCustomizer and EventHubsMessageChannelBinder#addProcessorFactoryCustomizer methods to add the factory customizers, that we will create next.</p><h3>Event Hubs Factory Customizers</h3><p>Now that we have access to the binder itself, and we know that it’s of type EventHubsMessageChannelBinder, it&#39;s time to move on to customize the client factory customizers, which are responsible for creating the internal clients.</p><p>We have two kinds of clients, EventHubProducerAsyncClient used for publishing events and EventProcessorClient, used for consuming events. Both clients have their factories, EventHubsProducerFactoryCustomizer and EventHubsProcessorFactoryCustomizer, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5689465b68d6b7ab9fefb666f521701d/href">https://medium.com/media/5689465b68d6b7ab9fefb666f521701d/href</a></iframe><p>Our factory customizer implementations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e6c133cfe9c97f3dced96cb2cb9efd7/href">https://medium.com/media/6e6c133cfe9c97f3dced96cb2cb9efd7/href</a></iframe><p>In both implementations, we checked if the default implementation is used. Both default implementation, since both have a method to add the builder customizers, coming up next.</p><h3>Builder Customizers</h3><p>Last step is to build the client builder customizers. They too have two implementations,AzureServiceClientBuilderCustomizer&lt;EventHubClientBuilder&gt; and AzureServiceClientBuilderCustomizer&lt;EventProcessorClientBuilder&gt;, the first for for producers and the second for the processors. Both use the same interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e723cdef04780b64dcf9f3e5f0255aa3/href">https://medium.com/media/e723cdef04780b64dcf9f3e5f0255aa3/href</a></iframe><p>The builders are what we came here for — they give the ability to customize the internal Event Hubs clients. For example, we can change the producer retry options:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6020423a12fb88854a64fcb74382a376/href">https://medium.com/media/6020423a12fb88854a64fcb74382a376/href</a></iframe><p>For the processor, we can offer a different checkpoint implementation change the checkpoint store to a different implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fbca276d550920e125642264be1ba4/href">https://medium.com/media/79fbca276d550920e125642264be1ba4/href</a></iframe><h3>Putting it all together</h3><p>Time to review what we have and stitch everything together.</p><p>We’ve created a BinderCustomizer bean, casting the binder parameter given to the implementation used in the Event Hubs binder - EventHubsMessageChannelBinder.</p><p>We then created two factory customizers beans, one for the producer — EventHubsProducerFactoryCustomizer, and one for the consumer, EventHubsProcessorFactoryCustomizer.</p><p>Finally, we have created the client builder customizers, AzureServiceClientBuilderCustomizer&lt;EventHubClientBuilder&gt; and AzureServiceClientBuilderCustomizer&lt;EventProcessorClientBuilder&gt;.</p><p>We will add the client builders to the factory customizers beans first, via their addBuilderCustomizer methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9ed64575ef1af8fa30ed92d96d1fa5/href">https://medium.com/media/df9ed64575ef1af8fa30ed92d96d1fa5/href</a></iframe><p>Since the factory customizers are beans, we can inject them to the BinderCustomizer bean:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/797be5eaa26b246d154d241bdb45e9a8/href">https://medium.com/media/797be5eaa26b246d154d241bdb45e9a8/href</a></iframe><h3>Testing that it works</h3><p>We want to check that the client was indeed changed to ensure that everything works. Adding logging to any of the methods we have created will test that the beans are created and invoked but will not tell us if the client was configured as expected, e.g., something overrode the configuration after our customizer was called.</p><p>My test was to change the connection string — we will be able to see that we are connecting to a completely different Event Hubs, or getting an exception if the new connection string is malformatted / the Event Hub doesn’t exist. Changing the EventHubsProcessorFactoryCustomizer that we have created above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82c39ddf0d78592f067cc78c1b5d7869/href">https://medium.com/media/82c39ddf0d78592f067cc78c1b5d7869/href</a></iframe><p>As expected, we got the exception java.lang.IllegalArgumentException: Connection string has invalid key value pair: not-really-a-connection-string . meaning that the connection string was indeed changed by the customizer.</p><h3>Source Code</h3><p>All the code presented here can be found on <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/main/eventhub-transformer-internal-client">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3dd049f3a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Hubs Dead Letter Queue with Spring Cloud Stream]]></title>
            <link>https://medium.com/@aviadpines/event-hubs-dead-letter-queue-with-spring-cloud-stream-2abe2241a452?source=rss-8c003a9a87e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2abe2241a452</guid>
            <category><![CDATA[event-hub]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aviad Pines]]></dc:creator>
            <pubDate>Mon, 24 Jan 2022 09:52:14 GMT</pubDate>
            <atom:updated>2022-01-25T17:58:46.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preface</h3><p>Our production pipelines handle hundred of thousands of events per second via multiple microservices and EventHubs. This kind of scale practically guarantees that a rogue message will pop and try to create some chaos once in a while. If it goes unhandled, we risk either creating a blockage, preventing message processing from the Event Hub partition, or worse, dropping the message, resulting in what we consider the worst-case scenario — data loss.</p><p>Consider message M causes an error while being processed. Since EventHub uses an offset to indicate the following message that it needs to consume, If we continue to the following message and checkpoint it, we will lose M as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*i31WMaHYnd_q-2hx1l4vhw.png" /><figcaption>Once an offset is checkpointed, by definition all the previous messages are considered checkpointed as well.</figcaption></figure><p>We need a solution that will not cause us any data loss but also will not cause the partition to be blocked until the problem is investigated and resolved.<br>A solution for such a problem is a Dead-Letter Queue (DLQ), which multiple message brokers have already implemented. A DLQ is a secondary channel to which messages that cannot be processed are sent. The message is not lost. It is sent to a different channel and can be investigated and resolved there. Meanwhile, the service can process the other messages in the partition.</p><p>EventHub doesn’t come out of the box with a DLQ. Instead, we will implement a logic one — our DLQ will be a different EventHub. If the service successfully processes the message, it will be published to the Event Hub as planned, and if an error occurs, it will be published to the DLQ EventHub instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeiteuQ_o941q4qxQwZvnA.png" /><figcaption>Processed messages are transformed and published to the outgoing Event Hub, and any corrupted message is sent to the DLQ</figcaption></figure><h3>Creating a basic service</h3><p>We will first create a simple service that receives a message from an incoming EventHub, transforms it, and send it to a different EventHub.</p><p>We will write the service to <strong>work both in versions 2.x and 4.x of </strong><a href="https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring"><strong>Spring Cloud Azure</strong></a><strong>, the Spring Cloud Stream Event Hub binder</strong>. We will point out when there are differences between the two.</p><p>Let’s start with the dependencies. <strong>For version 4.x:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18dff46f8fae26a846d0f65956237253/href">https://medium.com/media/18dff46f8fae26a846d0f65956237253/href</a></iframe><p><strong>For version 2.x</strong>, replace com.azure.spring:spring-cloud-azure-dependencies in the dependencyManagement section and spring-cloud-azure-starter-stream-eventhubs in the dependencies section with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63576a1af9b8f37970cc02b4de4509f/href">https://medium.com/media/a63576a1af9b8f37970cc02b4de4509f/href</a></iframe><p>Next, let’s define the service’s application.yaml . The service’s logic that we will implement shortly will reside in the method transform , and we will set our checkpoint-mode to MANUAL. <strong>For version 4.x</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5db2fd9e66aaab4b75aa1e5205e83cf/href">https://medium.com/media/e5db2fd9e66aaab4b75aa1e5205e83cf/href</a></iframe><p><strong>For version 2.x</strong>, the application.yaml will be slightly different:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e018f6ea9c8c117cfa42ba8820ec4ca2/href">https://medium.com/media/e018f6ea9c8c117cfa42ba8820ec4ca2/href</a></iframe><p>It is vital to set the checkpoint mode to manual, otherwise:</p><ol><li>Messages that were successfully processed through the service logic would be automatically checkpointed before ensuring that they were published successfully to the next EventHub, which might cause data loss if something happened between the message’s checkpointing and its publishing the next EventHub.</li><li>Any exception raised in the service logic will cause the message not to be checkpointed. Once we implement the DLQ, we want to checkpoint the message even if it caused an exception, <em>after</em> ensuring it was published to the DLQ.</li></ol><p>Next, we need to define our message and logic. We will use a very simple event, which we will even name SimpleEvent :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16add997c1b7fd9e94f09a03a1002fa5/href">https://medium.com/media/16add997c1b7fd9e94f09a03a1002fa5/href</a></iframe><p>The application.yaml indicates a few constraints that we have on implementing the service logic:</p><ol><li>The method name should be transform.</li><li>It needs to consume and publish messages since it has two bindings — transform-in-0 for consumption and transform-out-0 for publishing. This means that it should be a Function bean.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98fa413568e181738e805e7efa49257a/href">https://medium.com/media/98fa413568e181738e805e7efa49257a/href</a></iframe><p>Last thing (for now), is checkpointing. We set our checkpoint mode to manual, meaning that we need to checkpoint the message somewhere in our code explicitly.</p><p>Checkpointing within the transform logic provides a partial improvement but not a solution. It might give us the option not to checkpoint if a problem occurs. However, we still have the same issue when checkpointing automatically — an error that occurs after checkpointing but before publishing to the outgoing channel will cause the message will be lost.</p><p>Instead of checkpointing in the logic, we will use a ChannelInterceptor to intercept the message. We have two channels that we can intercept, and each interceptor has multiple interception points. Let’s find the best place to checkpoint.</p><p>Given two interceptors, one for the input channel and one for the output channel, we have three methods that will be invoked: preSend(message, channel), postSend(message, channel, sent), and afterSendCompletion(message, channel, sent, exception). The other three methods in the interceptor, preReceive(channel), postReceive(message, channel), and afterReceiveCompletion(message, channel, exception) are invoked only for pollable channels, so we dismiss them from the get-go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3BLyAx8RfC5nANYSRXS0g.png" /></figure><ul><li>preSend is invoked before we even call the service logic, so it is not good for us.</li><li>postSend is invoked after the service logic has finished, but will not be invoked if an exception was raised during the preSend or while sending the message itself, or if preSend returned null. We will need to have the ability to checkpoint even an exception was raised, so postSend is also not a good option.</li><li>afterReceiveCompletion is called after the send was completed, even if an exception was raised before. It will not be called only if preSend returned null (which means we explicitly want the message not to be sent). This is the best option for us.</li></ul><p>We will use the input channel, as its afterSendCompletion the last to be called, and the same implementation can be used for service which only consume messages.</p><p><strong>tl;dr</strong> We will use a ChannelInterceptor on the input-channel, using its afterSendCompletion method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed430f5ef4bbaf402ee1d5794148a25/href">https://medium.com/media/4ed430f5ef4bbaf402ee1d5794148a25/href</a></iframe><p>Starting our new service and sending a message to the incoming Event Hub, we can see the following logs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/767170d558e40ac78c7449945265a948/href">https://medium.com/media/767170d558e40ac78c7449945265a948/href</a></iframe><h3>Time to throw exceptions</h3><p>In its current implementation, any exception thrown in the transform() method will cause the message to not be sent, and our interceptor’s afterSendCompletion will not checkpoint the message since sent will be false.</p><p>What will happen to our service when an exception is thrown? In its current implementation, any exception thrown in the transform() method will cause the message to not be sent, and our interceptor’s afterSendCompletion will not checkpoint the message since sent will be equal to false.</p><p>Let’s update the service’s logic to throw an exception when we want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a81def929de435679e66034890a8406e/href">https://medium.com/media/a81def929de435679e66034890a8406e/href</a></iframe><p>We will throw an exception when the message’s data field equals ERROR. Indeed, when sending an event to the incoming Event Hub, we get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6ce7d32ef9388e50c9913a6fc85018/href">https://medium.com/media/0a6ce7d32ef9388e50c9913a6fc85018/href</a></iframe><p>We then enter a never-ending retry-loop — exception is thrown, the message is not checkpointed, and after a short while, it is consumed again, and so on. We don’t have data loss, but the partition is blocked.</p><h3>Adding a Dead Letter Queue</h3><p>The next step is to route the rogue messages to the DLQ, enabling us to checkpoint them and move on to the following events in line.</p><p>When an exception is raised, it is sent to the binding’s <strong><em>error channel</em></strong>, which accepts a thrown exception (wrapped) as its payload. The EventHub binder’s error channel is open by default and is named {destination}.{group}.errors.</p><p>We will see two methods to route the exception from the error channel, extract the failed message from it, and route it to the DLQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_e4KpLbKZa6SyYzl3q7YQ.png" /><figcaption>We will see two methods to implement the “magic” — routing the message from the error channel to the DLQ.</figcaption></figure><h4>Creating the DLQ binding</h4><p>First, we must create the DLQ itself. Like other channels in Spring-Cloud Stream, we will create a binding for it, starting with defining its function name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12838a3b84803ada1e274c2178b0795a/href">https://medium.com/media/12838a3b84803ada1e274c2178b0795a/href</a></iframe><p>Since the DLQ will not receive messages from an incoming Event Hub, only send, it only needs an outgoing binding, and naming conventions dictate that its name will be dlq-out-0</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/278e807d1a1fcaa191d907ab8e20d34c/href">https://medium.com/media/278e807d1a1fcaa191d907ab8e20d34c/href</a></iframe><p>In our example, transform-out-0 and dlq-out-0 point to two different Event Hubs in the same Event Hub Namespace. If you wish the DLQ to point to a different namespace, you will need to add the binder entry for it as well.</p><p>Our completeapplication.yaml will be, <strong>for version 4.x</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d7729211acab3d5a8368df7bae74082/href">https://medium.com/media/2d7729211acab3d5a8368df7bae74082/href</a></iframe><p>And <strong>for version 2.x:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a57d796a6adca8d7017be29d1dba01c/href">https://medium.com/media/2a57d796a6adca8d7017be29d1dba01c/href</a></iframe><p>Spring Cloud Stream also expects to find a Bean containing the dlq function logic, and since we only have an outgoing binder, it will expect a Supplier bean. Even though we will not use this function to send messages to the channel, it still needs to exist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b29386f2c9d9041e0c81ce6b5c278e57/href">https://medium.com/media/b29386f2c9d9041e0c81ce6b5c278e57/href</a></iframe><p>Notice that we chose a reactive supplier Supplier&lt;Flux&lt;Message&lt;?&gt;&gt;. This is because a regular supplier will be triggered every spring.cloud.stream.poller.fixed-delay milliseconds. On the other hand, a reactive supplier will be triggered only once and rely on the Flux to produce a stream of messages. Since we won’t use the supplier, triggering it only once is enough.</p><h4>Routing the messages to the DLQ via @ServiceActivator</h4><p>We will first implement our DLQ via Spring Integration’s @ServiceActivator, which enables the annotated version to handle messages sent to the activator’s inputChannel and send the result to the given outputChannel.</p><p>We will add the method to our EventHubTransformerDlq:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23b97ba1aaf7e9b17341d4bec0e01a51/href">https://medium.com/media/23b97ba1aaf7e9b17341d4bec0e01a51/href</a></iframe><ul><li>Our input channel &lt;input_channel&gt; is the binding’s <em>error channel</em>, {destination}.{group}.errors.</li><li>The output channel &lt;output_channel&gt; is the binding we have created for the DLQ — dlq-out-0. Therefore our annotation will be:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97f309b3d664109fd9f88837e6359656/href">https://medium.com/media/97f309b3d664109fd9f88837e6359656/href</a></iframe><h4>DLQ Interceptor</h4><p>Currently, any message with a problem will not be checkpointed by our interceptor. Even after we’ve successfully routed it to the DLQ, nothing will checkpoint it — the TransformerInputInterceptor was already called.<br>Once our message was routed and sent to the DLQ, we will need to checkpoint it to move to the subsequent events in the Event Hub. We will use the same trick and create an interceptor for the DLQ:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/659f8ecece28551b935d637a0bb4ae11/href">https://medium.com/media/659f8ecece28551b935d637a0bb4ae11/href</a></iframe><p>We can see the flow in the logs, TransformerInputInterceptor does not checkpoint the message, but DlqInterceptor does checkpoint it after it was sent to the DLQ:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3c8d6dff3b7ad01f069aa4d6761f0f4/href">https://medium.com/media/c3c8d6dff3b7ad01f069aa4d6761f0f4/href</a></iframe><h4>Using a dynamic input channel via an IntegrationFlow</h4><p>The main problem with using the @ServiceActivator is that <strong>we cannot set the input channel dynamically</strong>, and since it contains the actual Event Hub name, we will have to rebuild and release the service for each Event Hub — not something worth the time nor scalable.</p><p>To make things more dynamic, we will abandon the @ServiceActivator to create an IntegrationFlow, another Spring Integration component. The flow will read from the error channel, extract the message, and send it to the DLQ. Let’s replace the handleError method written before with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a4a19dd8a3c4b23b0029f4873bbf999/href">https://medium.com/media/3a4a19dd8a3c4b23b0029f4873bbf999/href</a></iframe><p>We build a new flow that takes input from the <em>dynamically created </em>error channel. We take the binding’s destination and group from our application.yaml, and inject them to destination and group arguments, respectively.</p><p>One thing that the @ServiceActivator did for us is to extract the id header and ErrorMessage. When using the IntegrationFlow, we receive the MessagingException directly and need to extract the message.</p><p>Finally, we send the transformed message to dlq-out-0 as indicated in the call to channel. We get the same result as we did with handleError, but we don’t need to hardcode the input channel, as we inject the values from the application.yaml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d846e5810fc0b4c5d7d94348cc058345/href">https://medium.com/media/d846e5810fc0b4c5d7d94348cc058345/href</a></iframe><p>We can see that the message was dynamically routed from the error channel my-dest.$Default.errors .</p><h3>Summary and further steps</h3><p>We have seen how a dead letter queue can help us avoid data loss while still being able to consume high volumes of data. Even though Event Hub doesn’t support a built-in DLQ, we have implemented a logical one. We saw how, by using interceptors, we could ensure that the messages will be checkpointed if and only if they were sent to either the target Event Hub or the DLQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hoHVzTwUkdRdsaT-kzYRw.png" /></figure><p>We have seen two ways to route the function from the binding’s error channel to the DLQ, and in both examples, we have routed the original message that failed. We will probably want to send more information about why the event failed in a production environment — the exception and any additional relevant metadata. Both routing options didn’t constrain us to the type of message we could send. We can create a wrapper containing any pertinent information. Whichever service we use to consume from the DLQ can use this information and decide on the appropriate action.</p><h3>Source code</h3><p>All the code presented here can be found on <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder">GitHub</a>, where the code for version 4.x is under branch main, and version 2.x is under <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/azure-spring-2.x">branch </a><a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/azure-spring-2.x">azure-spring-2.x</a>.</p><p>The code has the <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/main/eventhub-transformer-dlq">transformer</a> itself that we have created in this article and a <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/main/eventhub-producer">producer</a> and <a href="https://github.com/avpines/spring-cloud-stream-azure-eventhub-binder/tree/main/eventhub-consumer">consumer</a> to test the service easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2abe2241a452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Meters and Metrics with Micrometer]]></title>
            <link>https://medium.com/@aviadpines/dynamic-meters-and-metrics-with-micrometer-e7e16ce52371?source=rss-8c003a9a87e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e16ce52371</guid>
            <category><![CDATA[micrometer]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aviad Pines]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 15:21:46 GMT</pubDate>
            <atom:updated>2021-12-26T16:30:57.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVJbug4oWAVb-unFLTin2g.png" /></figure><h3>Preface</h3><p>Alerts, monitoring, and automated actions rely on metrics to ensure that all of our services are alive and well. Spring Boot leverages Micrometer, making creating metrics very simple, and with the different Spring Boot starters integrating these metrics with various monitoring systems became reasonably easy as well.</p><p>However, a recurring problem for me is the need for the meters to be more dynamic, mainly in allowing me to give different values to a given tag. Since in Micrometer, a meter ID is defined by its name and tags (key-value pairs), the tag value determines the meter, and different values result in separate meters. For example, these three meters are different:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f62faea47062e7287470a90e87a9278/href">https://medium.com/media/2f62faea47062e7287470a90e87a9278/href</a></iframe><p>Even though they have the same name and tag key, their tag values are different, resulting in separate tags, which will result in a different Meter ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4ee9850528fe2f72348a98fff002936/href">https://medium.com/media/d4ee9850528fe2f72348a98fff002936/href</a></iframe><p>For the same reason t4 will be the <em>same object </em>as t1 it has the same name and tags - it will <strong>not</strong> publish percentiles and will not have the new description.</p><p>This is a known issue, and Micrometer has <a href="https://github.com/micrometer-metrics/micrometer/search?q=dynamic+tag&amp;type=issues">open issues about it</a>. Some solutions exist, like <a href="https://dzone.com/articles/spring-boot-metrics-with-dynamic-tag-values">Hana Giat’s Multi-Tagged Metrics</a>, which I have used on multiple occasions. For a lot of the cases, this was sufficient. I could create, for example, a counter with a tag key exception and then dynamically put the exception class as the value, getting the number of times each exception was raised.</p><p>I’ve found two main things that were lacking in all of these solutions:</p><ol><li>While I can dynamically change the tags, I lose access to the inner builder and its customizations, so it is impossible, for example, to create two different timers that publish a different set of percentiles.</li><li>Gauges are supported in a very simplified manner; there is no ability to build a gauge with the same flexibility (either by providing an object and a function or providing a supplier) as when using it directly.</li></ol><h3>Making meters more dynamic</h3><p>Eventually, this is the exact problem that I’ve faced — multiple meters, where for each, I needed to define a different set of tag values and properties. Solving the problem resulted in this small library on <a href="https://github.com/avpines/dynamic-actuator-meters">GitHub</a>, <a href="https://github.com/avpines/dynamic-actuator-meters">dynamic-actuator-meters</a>, that we will explore in this article and see how it solves the problems described above.</p><p>For example, if we do wish to create two different timers, where each can have multiple tag-values, and each publish different percentiles, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5faa764687d2157fa5f5b08f1f1fa12/href">https://medium.com/media/e5faa764687d2157fa5f5b08f1f1fa12/href</a></iframe><p>as you can see, the customizer method lets us access the inner meter builder and manipulate it as needed by giving it a function Function&lt;Builder, Builder&gt;. Now we can get a Timer with a tag-value of our choosing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a24e5001aa0a16f88665d0757af78447/href">https://medium.com/media/a24e5001aa0a16f88665d0757af78447/href</a></iframe><p>This will record two days for a timer with the name a-timer-1 and a tag (tag-key-1, tag-value-1).</p><h4>Counters, Timers, and bears, oh my!</h4><p>The creation of most meters is similar. Creating Counters, Timers, and DistributionSummary remains similar when going dynamic as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b95bb7ceabd2f1c8d4a848da3a655a0d/href">https://medium.com/media/b95bb7ceabd2f1c8d4a848da3a655a0d/href</a></iframe><h4>Gauges — Same same, but different (Short intro to Gauges)</h4><p>As mentioned, the second thing that was lacking in the current solutions was the flexibility of Gauges, as they are a little different than the rest of the timers. As opposed to other meters where we increment, record, or do an explicit action ourselves, a Gauge retrieves an object’s value via a function supplied to it during construction. For example, we can gauge the size of a list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb8dd180ecfedae8b9563e0bc79ce83/href">https://medium.com/media/5bb8dd180ecfedae8b9563e0bc79ce83/href</a></iframe><p>As you can see, the builder requires more information than the rest of the meters, and it uses Generics:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a59c94deee1c061dba82fd238ea1ffda/href">https://medium.com/media/a59c94deee1c061dba82fd238ea1ffda/href</a></iframe><p>Furthermore, while we want the tag-keys common to all the underlying meters created by a dynamic meter, this is not the case for the gauge’s object and value function. Consider silly yet shows the point following cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a471dd913689b96acd9dabd0c8c76c6/href">https://medium.com/media/6a471dd913689b96acd9dabd0c8c76c6/href</a></iframe><p><strong>Same object, different value function: </strong>We have a list of strings, and we wish to gauge how many strings in that list have five or fewer characters and how strings have over five characters. This requires the gauges to have the same object but a different value function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d3281d1f71926ca93e203dd052c58e/href">https://medium.com/media/74d3281d1f71926ca93e203dd052c58e/href</a></iframe><p><strong>Different objects, same value function: </strong>Now consider that our implementation already separates the different string lengths into different lists — we will need the gauges to refer to other objects but use the same value function</p><p>The examples given here are straightforward, but once you have multiple gauges and tag values that change according to incoming input and requests, things can get quickly complicated if you’re using Gauges directly.</p><h4>Dynamic Gauges</h4><p>Creating a DynamicGauge is similar to how we do all the other dynamic meters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa1a9c3f63dd40b0198404c007b43c1/href">https://medium.com/media/baa1a9c3f63dd40b0198404c007b43c1/href</a></iframe><p>One noticeable difference is that DynamicGauge uses generics. This is to have type safety when creating the underlying gauges with their tag values. In the above example, since dg is of type DynamicGauge&lt;List&lt;String&gt;, list will have to be List&lt;String&gt;, or we will have a compilation error.</p><p>Let’s see how our dynamic gauge can handle the scenarios that we’ve described in the previous section. We will use the same DynamicGauge for both:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b082cad37be5248e12086c9ba332de3/href">https://medium.com/media/0b082cad37be5248e12086c9ba332de3/href</a></iframe><p>First case — same object, different value function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ee3d408a900350531fa3ad54d83c84/href">https://medium.com/media/94ee3d408a900350531fa3ad54d83c84/href</a></iframe><p>Second case — different objects, same value function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f69601fe192fe8533e9a397bd1ad95b/href">https://medium.com/media/2f69601fe192fe8533e9a397bd1ad95b/href</a></iframe><h4>Number-Supplier Gauge</h4><p>Micrometer 1.1.0 introduced a convenience builder method to build a Gauge with a Supplier&lt;Number&gt; type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53a6a68145b4f043fc5a98f30f8ae14/href">https://medium.com/media/f53a6a68145b4f043fc5a98f30f8ae14/href</a></iframe><p>Our library also supports this via the specialized SupplierDynamicGauge</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef8d03e0de218edb3ec8bd79f96a202/href">https://medium.com/media/cef8d03e0de218edb3ec8bd79f96a202/href</a></iframe><h3>Diving into the implementation details</h3><p>In the core of the dynamic meters lies DynamicMeter, which creates the underlying metrics if needed. The creation itself is built on top of Hana Giat’s solution and adds additional elements to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771b748a50693461d119baf8e87e96d9/href">https://medium.com/media/771b748a50693461d119baf8e87e96d9/href</a></iframe><p>Let’s start with the <strong>constructor: </strong>Besides registry, name, tagKeys and meters, which are straightforward and can be seen in other solutions, we see that we have more fields:</p><ol><li>newInnerBuilder is a function responsible for creating a new inner builder. Since there’s no hierarchy between the different meter builders, and as we saw, some builders require parameters, it is a function that receives the name and additional parameters and returns the corresponding builder.</li><li>tagger is another function responsible for tagging the meters. As we’ve mentioned, inner builders have no relationship between them, so we need to receive the way to tag as a parameter.</li><li>Next comes customzier, which we’ve seen in action in the examples. It is a function that allows us to customize the inner builder as we see fit.</li><li>Finally, the registrar function is responsible for registering the meter. Again, no builder hierarchy means that this too needs to be supplied as a parameter.</li></ol><p>getOrCreate, as the name suggests, is responsible for creating the underlying meters and storing them in the meters map.</p><p>reduceCustomziers takes all the customziers given to us in a collection and reduces them into a single operation that executes all the given customziers one after the other.</p><p>The last thing to mention in this class is the last generic type — R extends MeterParams. MeterParams is a marker interface for meters that use parameters, such as in the case of Gauges.</p><p>Let’s see a concrete implementation of DynamicMeter, DynamicTimerfor example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ad6373ce0a08bc740ec1df7493de76e/href">https://medium.com/media/9ad6373ce0a08bc740ec1df7493de76e/href</a></iframe><p>And the corresponding builder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12c88fb131fc5dc1e1dd4161303f838/href">https://medium.com/media/f12c88fb131fc5dc1e1dd4161303f838/href</a></iframe><p>Let’s focus on the build() method, which yields the actual DynamicTimer. We can see that our newInnerBuilder, tagger, and registrar, are constant, as for every Timer they are the same:</p><ul><li>We always create a new Timer via Timer#builder(name), so our newInnerBuilder will always be (s,p) -&gt; Timer.builder(s). Since we don’t use any additional params, p is never used.</li><li>Tagging is also done the same, via Builder#tags, so our tagger will always be (Builder b, Collection&lt;Tag&gt; t) -&gt; t != null ? b.tags(t) : b.</li><li>Finally, registration is always done via Builder#register, so our registrar will always be b -&gt; b.register(registry).</li></ul><p><strong>Once we know the meter we need to handle, all the functions become known, constant, and straightforward</strong>.</p><h4>Accepting parameters (The Gauges strike back)</h4><p>Dynamic Gauges are implemented in a very similar manner. The difference is that while other meters don’t accept parameters and therefore use VoidParams, DynamicGauge needs to get the object and value function. It does that via GaugeParams:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3966317e630ea2fb9d85ced09d06611/href">https://medium.com/media/a3966317e630ea2fb9d85ced09d06611/href</a></iframe><p>GaugeParams is also generic, which ensures our type safety.</p><p>The DynamicGauge itself looks similar to DynamicTimer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e52c0c2dda8ba134b60fe9e8ad7e71a3/href">https://medium.com/media/e52c0c2dda8ba134b60fe9e8ad7e71a3/href</a></iframe><p>and for the builder (simplified, you can look at GitHub for the way I’ve implemented it to support the SupplierDynamicGauge as well):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4c87b2447772b206ad9e752eabb33f/href">https://medium.com/media/6a4c87b2447772b206ad9e752eabb33f/href</a></iframe><p>We can see that the builder is very similar to the other builders we’ve seen before, with a slight change to the newInnerBuilder method. Instead of simply calling the underlying meter’s builder() method, it validates the parameters and calls Gauge’s builder with them.</p><p>Finally, OfType&lt;E&gt; is used to infer the Gauge’s generic type when using Class&lt;T&gt; is not possible, e.g., List&lt;String&gt;. It is a “Super Type Token”, coined in <a href="http://gafter.blogspot.com/">Neal Gafter’s blog</a>, and has multiple implementations since then; the most known is Jackson’s TypeReference&lt;T&gt;.</p><h3>Final remarks</h3><p>Even though we’ve mentioned Spring-Boot, we’ve seen that none of the library code uses Spring classes. One can easily replace the spring-boot-actuator dependency with Micrometer’s libraries, and they will be good to go.</p><p>And finally, all of the code shown here and more can be found on <a href="https://github.com/avpines/dynamic-actuator-meters">GitHub</a>. It includes a few additions and refactors that were omitted here for brevity.</p><p>I hope this was helpful, and I would love to hear your remarks/suggestions/comments/questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e16ce52371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Produce/Consume events with Spring Cloud Stream and Event Hub]]></title>
            <link>https://medium.com/@aviadpines/produce-consume-events-with-spring-cloud-stream-and-event-hub-4b41fdc1a9f6?source=rss-8c003a9a87e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b41fdc1a9f6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[event-hub]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Aviad Pines]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 10:49:56 GMT</pubDate>
            <atom:updated>2020-04-11T15:48:06.611Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spring-Cloud-Stream and Event Hubs Integration</h4><h3>Produce/Consume Events with Spring Cloud Stream and Event Hub</h3><h3>Preface</h3><p>This article aims to show how to use Microsoft’s Event Hub Binder with the current Spring-Cloud programming model, including a general introduction to Spring Cloud Stream. At the time of writing this article the documentation regarding <a href="https://docs.microsoft.com/en-us/azure/java/spring-framework/configure-spring-cloud-stream-binder-java-app-azure-event-hub">Microsoft’s Event-Hub Binder for Spring-Cloud Stream</a> uses the legacy annotation-based programming model.</p><p>All source code throughout this article can be found on <a href="https://github.com/avpines/event-hub-binder-example">Github</a>.</p><h3>Spring Cloud Stream</h3><p>Spring Cloud Stream is a framework for building message-driven microservice applications. It consists of three main concepts:</p><ul><li><strong>Destination Binders</strong>: Components responsible for providing integration with the external messaging systems. This article will concentrate solely on Microsoft’s Event Hub Binder, but Spring-Cloud Stream enables you to connect to many other systems as well such as Kafka or Rabbit.</li><li><strong>Bindings</strong>: Bridge between external messaging systems and application provided producers and consumers of messages (created by the Destination Binders).</li><li><strong>Message</strong>: The data structure used by producers and consumers to communicate with Destination Binders. In Event Hub terms, these are the events that we publish to and consume from the Event Hubs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Ek_889zu_hSot5gEyV2oZw.png" /></figure><p>So by simply adding spring-cloud-stream dependencies to the classpath of your application you will get immediate connectivity to a message broker exposed via provided spring-cloud-stream <em>binder</em> dependency (Event Hub in our case).</p><p>As you can see, the separation provided by Spring Cloud Stream makes the code that we are about to write binder-agnostic, meaning that <em>all</em> the code provided here will work with other binders as well, the only thing that needs to change is the configuration, which is binder-specific. <strong>Unless stated otherwise, the code provided will work with any binder provided as a dependency</strong>.</p><h3>Microsoft’s Event Hub Binder</h3><p>Microsoft provides and maintains its own binder to Azure Event Hubs, spring-cloud-azure-eventhubs-stream-binder. During the time of writing this article, the current version of the binder is <a href="https://mvnrepository.com/artifact/com.microsoft.azure/spring-cloud-azure-eventhubs-stream-binder/1.2.3">1.2.3</a>.</p><h3>Building an Application Using Event Hub’s Binder</h3><p>We will build a very simple application that will allow us to explore different ways to produce and consume messages via Spring Cloud Stream and Event Hubs. The application will:</p><ol><li><strong>Produce </strong>simple messages and send them to an Event Hub event-hub-a.</li><li><strong>Consume</strong> the message from the same Event Hub event-hub-a, manipulate it, and send it to a <em>different</em> Event Hub event-hub-b.</li><li><strong>Consume</strong> the message from the same Event Hub event-hub-b and log it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*boEACi25g4MHjecWpT2gpg.png" /><figcaption>Our Application</figcaption></figure><p>The application might seem a bit cumbersome, but it will allow us to visit a few important concepts we have in Spring Cloud Stream* in one application:</p><ol><li>Producing an event using a <em>Supplier</em> (1).</li><li>Manipulating an event using a <em>Function</em> (2).</li><li>Consuming an event using a <em>Consumer</em> (3).</li><li>Using multiple bindings in a single application.</li></ol><p>* These concepts are imported from Spring Cloud Function and are heavily used in Spring Cloud Stream.</p><h4>Needed Azure Resources</h4><p>We will need two Azure resources: an Event Hub to publish messages to and consume messages from, and a Storage Account that will be used to store the checkpoints.</p><p><strong>Event Hub: </strong>Create an Event Hub using <a href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-create">Microsoft’s Quickstart: Create an event hub using Azure portal</a>. For this article we have created a standard Event Hub with One Throughput Units named my-event-hub-namespace, and within that namespace two Event Hubs, event-hub-a and event-hub-b.</p><p><strong>Storage Account: </strong>A storage account is needed to save the checkpoints of each Event Hub, Create one using <a href="https://docs.microsoft.com/en-us/azure/storage/common/storage-account-create?tabs=azure-portal">Microsoft’s documentation</a>. we will use a <em>StorageV2</em> account named event-hub-checkpoints-storage (this is not the real name since storage account does not accept hyphens or spaces, but it will make it easier to follow this tutorial).</p><h3>Part I: The Application</h3><p>First we will create a brand new application using <a href="https://start.spring.io/">Spring Initializer</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvBdy0jZFQfZ8LGTGAt8Vw.png" /><figcaption>Creating a new application in Spring Initializer</figcaption></figure><p><strong>Group</strong>: com.avpines<br><strong>Artifact</strong>: event-hub-binder-example<br><strong>Name</strong>: event-hub-binder-example<br><strong>Description</strong>: Example for Integrating Spring Cloud Stream with Event-Hub<br><strong>Package name</strong>: com.avpines.example<br><strong>Packaging</strong>: Jar<br><strong>Dependencies: </strong>Cloud Stream, Spring Web, Lombok</p><p>Hit Generate. This will create a simple project with a main class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01955bc17694ad9035f42879f5f1d790/href">https://medium.com/media/01955bc17694ad9035f42879f5f1d790/href</a></iframe><p>We will need to add the Event Hub Binder dependency to our pom.xml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/950810a54fb548fec316806e9e6de21c/href">https://medium.com/media/950810a54fb548fec316806e9e6de21c/href</a></iframe><p>(1.2.3 is the newest version for the time of writing this article, you can check if there is a newer version on <a href="https://mvnrepository.com/artifact/com.microsoft.azure/spring-cloud-azure-eventhubs-stream-binder/1.2.3">Maven Central</a>)</p><h3>Part II: Producing a Message</h3><p>We will start with the message-producer, if you look at the drawing in the beginning of the section, this is part (1). We will create code that produces very simple string messages, and send it to Event Hub event-hub-a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*E7VxXOUj9E0vFNptfoXFiw.png" /><figcaption>First Step: Producing a message and sending it to event-hub-a</figcaption></figure><p>Translating this to the Spring Cloud Stream jargon, we want to:</p><ol><li>Write the code that produces a message.</li><li>Create an output <strong><em>binding</em></strong> from our message-producing code to Event Hub.</li><li>Configure that binding to point to our Event Hub event-hub-a.</li></ol><p>The first and second parts will be done by wrapping the code that produces the message with a @Bean of either a Function, Supplier, or Consumer type. <strong>Spring-Cloud-Stream, with its autoconfiguration and the additional Event-Hub Binder dependency, will recognize and </strong><a href="http://twitter.com/Bean"><strong>@</strong></a><strong>Bean of type </strong><strong>Function, </strong><strong>Supplier, or </strong><strong>Consumer and create a binding for it</strong>.<br>We will accomplish the third part, configuring the binding, by learning the naming conventions that Spring-Cloud-Stream gives these bindings.</p><p>Let’s start with the code. Our producer will create String messages, and as we explained, we want the producer to be wrapped in a <a href="http://twitter.com/Bean">@Bean</a> of type Function, Supplier, or Consumer. Since this is a producer, we will use a Supplier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb6d8e0107e3be774df101b7ec53804/href">https://medium.com/media/5eb6d8e0107e3be774df101b7ec53804/href</a></iframe><p>The produce() method above produces a random String quote. So how is this code triggered? How Function and Consumer are easier to understand in terms of triggering — an event arrives to the broker that they are bound to, and it triggers them, but what about a Supplier? It is by definition the source of the data, it isn’t subscribed to any input destination, so it has to be triggered in a different way.</p><p>The answer is that the framework itself, <strong>Spring-Cloud triggers it</strong> by providing a configurable polling mechanism. It’s important to note that for Supplier the framework also <strong>differentiates whether the Supplier is imperative or reactive:<br></strong>For <strong>imperative</strong> (non-reactive) Supplier @Bean, the triggering will occur every second, but this can be changed with the spring.cloud.stream.poller.fixed-delay property (time in milliseconds). Therefore for our produce() implementation above, a new string message will be created every second.</p><p>For <strong>reactive</strong> Supplier @Bean, however, the triggering will occur only once (if you are not familiar with reactive programming don’t worry, it is not needed for the rest of this article, you can safely skip this section). So if we change our produce() implementation to be reactive:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c0053c9f52e0561ec31754e97240ae/href">https://medium.com/media/42c0053c9f52e0561ec31754e97240ae/href</a></iframe><p>The method will be triggered only once and only a single message will be produced. We can tell the framework that even though this is a reactive Supplier, we still wish to poll it like an imperative one. This is done via the @PollableBean annotation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/becb2a9efeb259a6478086632eae99b3/href">https://medium.com/media/becb2a9efeb259a6478086632eae99b3/href</a></iframe><p>You can choose whichever implementation that you wish, and let’s move on to configuring our Event Hub and binding.</p><h4>Configuring Event Hub and Binding</h4><p>Now we need to configure our producer to send its messages to event-hub-a, or in Spring-Cloud Stream terms we need to configure the output binding.</p><p>We will take this chance to configure our application to connect to the Event Hub namespace itself in our application.yaml file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ebe4b1b8f0d7fdae7b00f25b3996d4/href">https://medium.com/media/06ebe4b1b8f0d7fdae7b00f25b3996d4/href</a></iframe><p><strong>EVENT_HUB_CONNECTION_STRING</strong> is the connection string to the Event Hub namespace, and is taken from Shared access policies → RootManageSharedAccessKey→ Connection string-primary key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZMqsXwm7XEQxaw6P2_Vrw.png" /><figcaption>Obtaining the Event Hub connection string property for our application.yaml</figcaption></figure><p><strong>STORAGE_ACCOUNT_ACCESS_KEY </strong>is the Storage Account access key, and is taken from Access Keys → key → key1 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdiyCRO8_FCHmsnkV6izFw.png" /></figure><p>Next we have to <strong>configure the binding</strong>. As we explained, Spring-Cloud Stream detects the Supplier @Bean and creates a binding for it — a bridge between our source code and the brokers exposed by the binder. The naming convention that Spring Cloud uses to automatically name our bindings is:</p><ul><li>input binding — &lt;functionName&gt; + -in- + &lt;index&gt;</li><li>output binding — &lt;functionName&gt; + -out- + &lt;index&gt;</li></ul><p>The index is always 0 for a typical single input/output function. Non-zero index is only relevant for Functions with multiple input and/or output arguments, which we will not cover in this article.</p><p>Going back to our produce() Supplier, it has only one output binding, and following the naming convention, its name will be produce-out-0. We want to direct this output binding to the destination event-hub-a, which can be configured via the property spring.cloud.stream.bindings.&lt;binding-name&gt;.destination, so our configuration will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00700da136af79185eaf93a8467714c3/href">https://medium.com/media/00700da136af79185eaf93a8467714c3/href</a></iframe><p>and our complete (so far) application.yaml file will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d8e76f08ae1181133b9302697c882b/href">https://medium.com/media/80d8e76f08ae1181133b9302697c882b/href</a></iframe><p>For a good checkpoint and sanity check, we can run our application now and see that it connects to Event Hub and starting to write the random quotes that it sends to event-hub-a:</p><pre>Producing quote: It’s not a bug – it’s an undocumented feature<br>Producing quote: Deleted code is debugged code<br>Producing quote: It’s not a bug – it’s an undocumented feature<br>Producing quote: Before software can be reusable it first has to be usable<br>Producing quote: Before software can be reusable it first has to be usable</pre><p>Yay.</p><h3>Part III: Receiving, Manipulating, Sending again</h3><p>Time for the next step, number (2) in our drawing — receiving the message from event-hub-a, manipulating it, and sending it to a different Event Hub event-hub-b.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*_CU8SZ8hnsodGRzcdicdCQ.png" /><figcaption>Second Step: Receiving a message, manipulating it, and sending it to a different Event Hub</figcaption></figure><p>This time we have an output binding like in the producer, and in addition, we have an input binding — receiving the message from event-hub-a. As we have mentioned before, Spring Cloud recognizes @Beans of types Function, Supplier, or Consumer, and the one that applies for both receiving an input argument and producing (returning) an output is the Function.<br>Therefore, we will create a Function that receives the same output as the producer, i.e. a String, and outputs the same String only all in uppercase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05301df3b3c314477386973a7ec11098/href">https://medium.com/media/05301df3b3c314477386973a7ec11098/href</a></iframe><p>The binding uses the same naming convention mentioned before</p><ul><li>uppercase-in-0 for the input binding, destination event-hub-a</li><li>uppercase-out-0 for the output binding, destination event-hub-b</li></ul><p>An input binding requires another parameter other than the destination — the <strong>consumer group</strong>. A consumer group is a view (state, position, or offset) of an entire event hub. Consumer groups enable multiple consuming applications to each have a separate view of the event stream, and to read the stream independently at their own pace and with their own offsets. We will use the default consumer group $Default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44cddcefe359052d9c158d3ae901e954/href">https://medium.com/media/44cddcefe359052d9c158d3ae901e954/href</a></iframe><p>If you will attempt to run the application now, it will not work. When you have a single Function / Supplier / Consumer <a href="http://twitter.com/Bean">@Bean</a>, it will be auto-discovered. Once you have more than one, you must define which of these beans should be bound. This is done via the spring.cloud.function.definition property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f11259d6f43d86f9794c00f1e4da6f/href">https://medium.com/media/d0f11259d6f43d86f9794c00f1e4da6f/href</a></iframe><p>It is recommended to <em>always</em> use this property, even when using a single Function / Supplier / Consumer <a href="http://twitter.com/Bean">@Bean</a>.</p><p>Let’s review our complete application.yaml and run our application again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf273e266abb43d34de33b496f3ea062/href">https://medium.com/media/cf273e266abb43d34de33b496f3ea062/href</a></iframe><p>Our application now should, in addition to everything it did before, to also consume the messages from event-hub-a, transform them to uppercase, and send them to event-hub-b:</p><pre>Producing quote: If at first you don’t succeed; call it version 1.0</pre><pre>Transforming string If at first you don’t succeed; call it version 1.0 to IF AT FIRST YOU DON’T SUCCEED; CALL IT VERSION 1.0</pre><pre>Producing quote: Deleted code is debugged code</pre><pre>Transforming string Deleted code is debugged code to DELETED CODE IS DEBUGGED CODE</pre><h3>Part IV: Consuming a Message</h3><p>The last part of our application is consuming the uppercased message from event-hub-b, and print it to the standard output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*73XjidUpLzK5tI2zakMvLg.png" /><figcaption>Third Step: Consuming a message</figcaption></figure><p>As you can guess, since we only want to consume a message, we will use a Consumer <a href="http://twitter.com/Bean">@Bean</a>, which requires only an input binding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e0cceb51f4cfe3ac660760e4db14297/href">https://medium.com/media/0e0cceb51f4cfe3ac660760e4db14297/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2562ea055a451996a39467f8997bfb2a/href">https://medium.com/media/2562ea055a451996a39467f8997bfb2a/href</a></iframe><h3>Part V: Running the Complete Application</h3><p>I just felt that this deserved its own part. Let’s run the entire application and see that, in addition to everything we’ve seen before, we are also seeing that the message was consumed:</p><pre>Producing message: If at first you don’t succeed; call it version 1.0</pre><pre>Transforming message If at first you don’t succeed; call it version 1.0 to IF AT FIRST YOU DON’T SUCCEED; CALL IT VERSION 1.0</pre><pre>Consumed message IF AT FIRST YOU DON’T SUCCEED; CALL IT VERSION 1.0</pre><pre>Producing message: One man’s crappy software is another man’s full-time job</pre><pre>Transforming message One man’s crappy software is another man’s full-time job to ONE MAN’S CRAPPY SOFTWARE IS ANOTHER MAN’S FULL-TIME JOB</pre><pre>Consumed message ONE MAN’S CRAPPY SOFTWARE IS ANOTHER MAN’S FULL-TIME JOB</pre><p>Success, and there was much rejoicing.</p><h3>Final Thoughts</h3><p>Spring Cloud Stream allows us to create broker-agnostic event-driven microservices in a surprisingly simple manner. Since all brokers are treated the same, configuring our Event Hub to communicate with it was a matter of adding a dependency and a little extra configuration, and very little knowledge if any regarding the specific broker that we decide to use.</p><p>Spring Cloud Stream takes all the boilerplate and hard work of configuring all the event-handling and lets you focus solely on the app-logic of your event-driven microservice.</p><p>This article attempted to show the basics of Spring Cloud Stream and Event Hubs, and there are a lot more things that can be done such as handling multiple brokers (for example if our event-hub-a and event-hub-b were in different namespaces), function composition and more. I’ll be happy to write more about either of these topics (or others) if there is an interest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b41fdc1a9f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>