<?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 Daniel López on Medium]]></title>
        <description><![CDATA[Stories by Daniel López on Medium]]></description>
        <link>https://medium.com/@d.lopez.j?source=rss-92b74318ee92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yOXwO0zXMAEb7Zqd.</url>
            <title>Stories by Daniel López on Medium</title>
            <link>https://medium.com/@d.lopez.j?source=rss-92b74318ee92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:39:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d.lopez.j/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[On (virtual) threads and pools]]></title>
            <link>https://medium.com/@d.lopez.j/on-virtual-threads-and-pools-7bb34a894d51?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb34a894d51</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 17:02:02 GMT</pubDate>
            <atom:updated>2022-12-12T17:02:02.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>On Java (virtual) threads and pools</h3><figure><img alt="A loom with threads of different colours" src="https://cdn-images-1.medium.com/max/640/1*vgdIxveq0gl17DiXtWgRdg.jpeg" /><figcaption>Loom threads</figcaption></figure><p>Much has already been written about the new feature known as virtual threads, introduced as a preview in Java 19, and about the changes that this feature will enable. Among those, we can find that the new virtual threads are light, as opposed to the regular ones tied to native threads, so there is no need to cache or pool them. So far, so good.</p><blockquote><em>Native threads are considered heavy, so you can create a limited number of them, but virtual threads are light so they are virtually, pun intended, limitless.</em></blockquote><p>However, beware! We should not make the mistake of immediately assuming that given that there is no need to pool them, we can simply substitute the “now old-fashioned” pools of threads with a new executor service that simply spawns a new virtual thread for every task as fast as it can create them. Why? Because threads being heavy was not the only reason why we are using pools of threads.</p><p>In many occasions, the reason behind a pool of threads is controlling explicitly the level of concurrency that we want to allow for a certain set of tasks. For example, to prevent a resource from being “overwhelmed” if we know it is not prepared to handle more than a certain level of simultaneous requests. Yes, it might not be the ideal approach, as we are killing two birds with one stone (controlling concurrency and preventing the creation of too many heavy native threads) but that is how many pieces of software currently do it.</p><p>With the new virtual threads, why not send all the requests anyway and let the resources handle &amp; queue them as they see fit? Because doing so would put the control, the responsibility, and the burden at the resource. And that might not be convenient at all. The resource might not be in our control, and might simply refuse to do it, or be unable to carry those tasks; or, if it did carry them, we would lose control over how it is done, so we might not be happy with the results anyway. If the resource were in our hands, at a minimum we would need first to make sure that it is able to handle the load, or we would have to modify it so it is able to handle it.</p><blockquote><em>Simply spawning virtual threads puts the control, the responsibility, and the burden of handling concurrency at the resource on the other side of the task.</em></blockquote><p>Let’s see some examples, based on real-life code that I have had to work with, to see why a direct translation of pools of threads to simply spawning virtual threads might not be an appropriate strategy.</p><ol><li>We have an application that uses a pool of database connections with a max number of connections: nothing new. This pool is used by some interactive fast requests and by some background jobs that periodically fill up some cache data and for that, they run some slow queries. To control the number of slow heavy queries that are sent against the database concurrently we use a pool of threads, for two reasons: First, because sending too many of them at the same time does indeed make them slower as they interfere with each other. Second, because if we used all the connections of the database pool for the background jobs, then there would be no connection left for the interactive requests to use. Then the interactive requests would block waiting for the slow queries to finish and the latency would suffer.</li><li>There is another application where we have to update periodically some data that queries a third party service. It has to send a couple of thousand request every day but we use a pool to throttle the requests. Why? Because we know this external service is in a shared host with limited resources and sending more than a handful simultaneous requests simply increases the latency. Apart of our requests, this service has a very light load, so they do not intend to overprovision it to make it able to handle our daily requests, just so we can finish a background job faster.</li><li>I worked for some time in a B2B accommodation engine, designing the API. One of the things that we had in place was an API Gateway, to control customers who would pay a fee depending on the number of requests that they were allowed to make in a given interval of time. If they controlled the number of requests sent at their side, they could decide to queue the ones over their allotted quota. If they decided to simply send all their requests along, the API Gateway would simply block the ones over their quota, which was a loss for both parties.</li></ol><p>Those are just a couple of examples of “not too uncommon” situations where developers use nowadays a pool of threads to control the level of concurrency. If we simply substitute pools of threads with the new <em>VirtualThreadPerTaskExecutor</em>, we are going to <em>DoS</em> (Denial of Service attack) some our services.</p><blockquote><em>We have to be careful when moving to virtual threads, else we might </em>DoS<em> some of the services in use!</em></blockquote><p>So, <strong>does that mean we should skip virtual threads? No</strong>, what it means is that we should make sure that, if we need to control the level of concurrency of our tasks, we do so. We can accomplish that by using the good ol’ concurrency mechanisms that Java provides, for example: semaphores, and with a little code reuse, we can simplify the task and create a good candidate to replace our thread pools. In the next section I’ll show an example of how we can implement such a tool.</p><h3>Controlling the level concurrency with virtual threads</h3><figure><img alt="Threads passing through a needle hole" src="https://cdn-images-1.medium.com/max/640/1*g5dOl_9m0CVDmbL86IzQJw.jpeg" /><figcaption>Control your threads!</figcaption></figure><p>We have talked about why it is important to make the migration to virtual threads without losing control of how much load we are causing with our tasks. Now, we will explain how to do so, using the concurrency mechanisms provided by the language itself.</p><p>There are many solutions one could employ to limiting the concurrency of tasks being executed in Java, but we are going to use the <a href="https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/concurrent/Semaphore.html"><em>Semaphore</em></a> class, as it allows us to directly specify the number of threads we want to be able to execute a piece of code at the same time. We could have done something similar to the <a href="https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java"><em>ThreadPoolExecutor</em></a> class and keep the scheduled tasks in a queue, but in this case we opted for more straightforward approach, and let all the virtual threads be spawned, using the semaphore to control how many of them are executing the real work at the same time. Given that virtual threads are supposed to be light, we also wanted to check the behaviour when letting them all spawn at the same time.</p><p>You can see the simple implementation that I came up with at GitHub: <a href="https://github.com/Verdoso/jmh-throttled-virtual-threads/blob/master/src/main/java/org/greeneyed/jmh_throttled_virtual_threads/ThrottledVirtualThreadsExecutor.java">ThrottledVirtualThreadsExecutor</a> and we can see it in action in the next block.</p><blockquote><em>Java includes mechanisms to control the concurrency of our programs, and we can apply those same mechanisms to virtual threads.</em></blockquote><h3>Testing CPU bound tasks</h3><p>We have already mentioned that the problem with simply spawning virtual threads without control is the danger of overwhelming other services, but what about CPU bound tasks? I wanted to test how well virtual threads were performing when stressing the CPU and see if throttling them would make any difference, so I created and uploaded a sample project to GitHub, <a href="https://github.com/Verdoso/jmh-throttled-virtual-threads">jmh-throttled-virtual-threads</a>.</p><p>I used that code to simulate creating many threads to perform a CPU consuming task by executing some floating-point arithmetic (see the method <a href="https://github.com/Verdoso/jmh-throttled-virtual-threads/blob/master/src/main/java/org/greeneyed/jmh_throttled_virtual_threads/VirtualThreadsTester.java#L67"><em>VirtualThreadsTester.cpuConsumingMethod</em></a>). In order for the experiment to be more reliable, I launched it using the <a href="https://github.com/openjdk/jmh">JMH benchmarking framework.</a> as it runs the experiments repeatedly and adds a warm up phase to prevent some of the issues that plague short-lived microbenchmarks.</p><p>I performed the tests executing just the CPU consuming function and repeated them adding a small delay of 50ms to simulate some I/O task or other non-CPU related factor. The test launched 10.000 virtual threads to perform the specified task and the maximum level of concurrency allowed for the throttled executor was set to 30 simultaneous tasks.</p><p>After running some tests, the result were interesting:</p><h4>Pure CPU function</h4><pre>Benchmark                                   Mode  Cnt      Score    Error  Units<br>testFreeVirtualThreadsWithLongFactor        avgt   25  21764,275 ± 58,243  ms/op<br>testFreeVirtualThreadsWithSmallFactor       avgt   25     34,053 ±  0,197  ms/op<br>testThrottledVirtualThreadsWithLongFactor   avgt   25  21759,747 ± 66,738  ms/op<br>testThrottledVirtualThreadsWithSmallFactor  avgt   25     34,125 ±  0,104  ms/op</pre><p>In this results, you can see that there is no difference between controlling concurrency or not. In fact, if I ran the tests individually, grain of salt applied, I could see that with the small factor, the level of concurrency obtained was within a single digit so the throttling never limited anything. On the other hand, when the factor was big, the CPU consumed was so huge that it became the limiting factor before the throttling had any chance to limit the concurrency (30 is too big). Playing with the concurrency limit and the load factor, I was unable to come up with a combo that gets an unambiguous better result when throttling, and that’s good because it means that the JDK/OS combo are really good at handling the tasks/CPU.</p><p>But there is more</p><h4>CPU + small delay (50ms) function</h4><pre>Benchmark                                   Mode  Cnt      Score     Error  Units<br>testFreeVirtualThreadsWithLongFactor        avgt   25  22036,852 ± 134,104  ms/op<br>testFreeVirtualThreadsWithSmallFactor       avgt   25     95,549 ±   0,062  ms/op<br>testThrottledVirtualThreadsWithLongFactor   avgt   25  23505,818 ±  43,687  ms/op<br>testThrottledVirtualThreadsWithSmallFactor  avgt   25  20617,513 ±  11,155  ms/op</pre><p>Adding a small delay, 50ms, after the calculation changed things quite a bit. When the CPU was not the constraint (small factor), then limiting the number of simultaneous tasks via throttling made a big difference, for the worst. Checking the logs during the experiment told me that with the small delay, the level of concurrency without throttling got to 10.000, remember that without the delay it would not reach two digits. Given that the concurrency limit was set to 30 in the throttling experiment, it was clear where the delay comes from</p><p>Playing with the parameters (the delay, the concurrency limit) I saw different results, but the overall conclusion is that when the tasks are CPU-bound, the new virtual threads and the JDK do a very good job when we let them handle everything. But, if we wanted to remain in control and make sure we don’t simply consume as much CPU as available, we now had one way to do it.</p><blockquote><em>JDK/OS handle pretty well CPU bound tasks, but don’t let them consume all your resources</em></blockquote><h3>Some extra thoughts</h3><p>Taking into account that this different results happen with exactly the same code by simply changing one or two variables. It is quite clear, in case there was any doubt, that the best approach is not to follow one strategy blindly but to measure and see what will work best given the circumstances in each case, and then be ready to change if those circumstances change.</p><p>A <strong>conservative approach to move to virtual threads</strong> would be to replace all the “<em>Executors.newFixedThreadPool(int)</em>” calls with something like “<em>new ThrottledVirtualThreadsExecutor(int)</em>” and then play with the concurrency level to see how much the system can handle. If the tasks are CPU bound it is very likely that the system will support a higher concurrency level , no more native threads limit yay!, but be careful not to consume the whole CPU if that causes issues with other parts of your application (or the GC, for example). Be also aware that if the CPU consumption is high, spawning more tasks might not give yield better results, as the CPU itself is not changed. At the very least, your application will be a tad better as virtual threads are indeed lighter than regular ones.</p><p>Remember that, as there are limited resources, there is no such thing as THE bottleneck of an application, but just the CURRENT bottleneck. If we eliminate the current one, another one will surface so don’t let the next one in line catch you unprepared.</p><h3>Future experiments</h3><p>One could easily perform different experiments by changing the cpuConsumingMethod method and fiddling with the parameters or doing some other task, like some I/O intensive operation or querying a database. For example, using this project as a template, one could check if sending 10.000 simultaneous queries to a DB gives better performance than throttling them and, in that case, see which concurrency level get the better results). Be careful when doing this type of tests though, never in production, as you might <em>DoS</em> your DB. Monitoring the DB would be important, as your service might respond fine but might be making the DB unusable for anything else.</p><p>If you do your own tests and see some interesting results, please share them!</p><p>(Image by <a href="https://pixabay.com/users/annaer-35513/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=173821">Anna</a> and <a href="https://pixabay.com/users/myriams-fotos-1627417/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4854847">Myriams-Fotos</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=173821">Pixabay</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb34a894d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily connecting your Spring Boot applications to the Elastic Stack with Log4j2]]></title>
            <link>https://medium.com/@d.lopez.j/easily-connecting-your-spring-boot-applications-to-the-elastic-stack-with-log4j2-1809e81c6a2e?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/1809e81c6a2e</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[log4j2]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 08:45:37 GMT</pubDate>
            <atom:updated>2019-02-25T08:55:47.105Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that logging aggregators are becoming ubiquitous, a common issue that we, developers, have to face is how to connect the log output of our applications to those tools. Some of the issues that we encounter during that process are:</p><p>· Usually we don’t use <strong>an aggregator in development</strong>, we simply want to see all the logs in the development console, so the application has to start without issues when there is no aggregator listening.</p><p>· One does not simply throw the logs to Mordor… I mean the aggregator. <strong>We need to parse the different fields of the log lines so the messages can be easily filtered afterwards</strong>.</p><p>· <strong>The aggregator might go down</strong>, for some reason, and then it would be nice not to lose the logs completely.</p><p>· On the other hand, we have to be <strong>careful with the size of the logs generated in the machine where the app is deployed</strong>, as space is usually a concern, especially now that multiple small machines are now the norm.</p><p>As people used to store the logs in files the production machines, and then move/copy/process those files, a very common approach is to use one of the beats of the <a href="https://www.elastic.co/products">Elastic Stack</a> family, <a href="https://www.elastic.co/products/beats/filebeat">Filebeat</a>, to read those files and send them up the stack. That has the advantage of being simple and not requiring many modifications to our previuos flow, but it means we have now to process all those log lines in <a href="https://www.elastic.co/products/logstash">Logstash</a> and extract the different fields so the logs can be indexed properly. If you have had to create a 380-char regular expression to extract important fields from log lines, as I had to do, you know how “fun” that can get. We could also generate the log fields in JSON format and then send that to prevent the line parsing, but the logs files become then non human-readable.</p><p>Fortunately, there’s a very useful set of libraries from <a href="https://github.com/mp911de">Mark Paluch</a> that one can use: <a href="http://logging.paluch.biz/">Logstash/Gelf Loggers</a>. More specifically, I’m going to explain how to use the <a href="https://logging.apache.org/log4j/2.x/">Log4j2</a> one to connect the application directly to <a href="https://www.elastic.co/products/logstash">Logstash</a>. It communicates using a the Graylog Extended Logging Format, so there’s no need to parse the log lines in <a href="https://www.elastic.co/products/logstash">Logstash</a>, unless you want to.</p><p>So let’s start:</p><h4>Preparing the environment</h4><p>As I said before, we don’t want to try to connect to the log aggregator during development, so we create two different <a href="https://logging.apache.org/log4j/2.x/">Log4j2</a> configuration files: log4j2-spring.xml and log4j2-spring-prod.xml. The first one is the typical Log4j2 development configuration, and the second is the one that will be used in production. How do we tell <a href="https://spring.io/projects/spring-boot">Spring Boot</a> that we want to use one or the other depending on the environment? Well, that’s what profiles are for! Edit <strong>src/main/resources/application.yml</strong> and add a piece like this one at the end:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a447a8b49fcbdadc2d09c07579a0f8db/href">https://medium.com/media/a447a8b49fcbdadc2d09c07579a0f8db/href</a></iframe><p>This basically tells Spring Boot that the default logging configuration file is log4j2-spring.xml, found in the classpath. We also say explicitely that in test and devel we want to use that one, and then that in prod we want to use log4j2-spring-prod.xml. Why do we tell test and devel that we want to use that one explicitely? Because if we run some tests using the production configuration but overriding some values, we might start the application with the profile <em>prod,test</em> and if we did not tell Spring Boot again that we want to use log4j2-spring.xml in test, it would use log4j2-spring-prod.xml. This way we are safe that the latest active profile is the one that sets the logging configuration file to use. If we have other environments in the pipeline, with or without aggregators, changing the settings to decide which configuration to use in each environment is fairly easy.</p><p>Before delving into the configuration files, let’s make sure we have the Logstash/Gelf Logger library added to the project by editing the <strong>pom.xml</strong> and adding this dependency:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d640a75b7c60072cb414babaf64ddf/href">https://medium.com/media/40d640a75b7c60072cb414babaf64ddf/href</a></iframe><p>Version 1.11.2 is the one I tested the code with, but you can check what is the latest version at <a href="https://mvnrepository.com/artifact/biz.paluch.logging/logstash-gelf">Maven central</a>.</p><p>Once we have the library, we can define the logging configuration files. For the sake of completeness, we’ll also show the development one:</p><h4>log4j2-spring.xml</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9eb98542b05e7882d39e0fd7ace34de/href">https://medium.com/media/d9eb98542b05e7882d39e0fd7ace34de/href</a></iframe><p>Of course this is a basic example and a real one will have more filters and the pattern might be different but you get the idea. Now let’s see the “production” one:</p><h4>log4j2-spring-prod.xml</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0ea1af290a6fd782952ef02dd8668d2/href">https://medium.com/media/a0ea1af290a6fd782952ef02dd8668d2/href</a></iframe><p>In this file we are, in fact, defining two appenders: one sends the logs directly to the <a href="https://www.elastic.co/products">Elastic Stack</a> and the other one is a typical file appender that rolls the files quite aggressively. Why? Because if the <a href="https://www.elastic.co/products">Elastic Stack</a> fails for some reason, we can still access the logs, stored in the files, for some time, before they are overwritten.</p><p>The settings for how long you want to keep the “backup” files depend on the situation and the application and is something to agree with the production guys. In any case, the interesting bit is the Gelf appender. With that one, we are sending the logs directly to the <a href="https://www.elastic.co/products">Elastic Stack</a> and defining the fields we want to send. The appender has some default fields that are sent if you don’t specify anything, check the documentation for details, but I always build on top of that. In this case I’m sending:</p><p>· <strong>Timestamp</strong>: essential</p><p>· <strong>Log level</strong>: essential</p><p>· <strong>Simple class name</strong> producing the log: I prefer it over the lengthy fully qualified name</p><p>· <strong>Class name</strong>: I send it, just in case, but I’ve never used it so I have it filtered out in <a href="https://www.elastic.co/products/logstash">Logstash</a>.</p><p>· <strong>Hostname </strong>and <strong>simple hostname</strong>: The same as with class name, simple name is usually good enough and is shorter.</p><p>· <strong>Application name</strong> so I can filter easily and also so I can have different settings in <a href="https://www.elastic.co/products">Elastic Stack</a> depending on the application</p><p>· Thanks to <strong>includeFullMdc=”true”</strong>, all the fields added to Log4J Mapped Diagnostic Context (MDC) will be added as fields to the log. This feature is very useful as, for example, it means that the token-per-request ID described in the entry “<a href="https://medium.com/@d.lopez.j/spring-boot-setting-a-unique-id-per-request-dd648efef2b">Spring Boot: Setting a unique ID per request</a>” is added automatically, isn’t it cool?</p><h3>Configuration and environment variables needed</h3><p>If you check the production file, you’ll see that there <em>baseDir</em>, the directory where the log files are stored is set to the logs directory at the home of the user running the application ($${env:HOME}/logs). Change that if you want to store the logs elsewhere.</p><p>Also, the address of the machine where <a href="https://www.elastic.co/products/logstash">Logstash</a> is defined is passed through an environment variable <em>LOGSTASH_PROXY </em>because we want to be able to change the <a href="https://www.elastic.co/products/logstash">Logstash</a> server on different environments and we don’t want to redeploy all the applications when the <a href="https://www.elastic.co/products/logstash">Logstash</a> server address changes, but it is up to you.</p><p>The <em>applicationName </em>variable is something that I have to unfortunately write explicitely in the configuration file, because Log4j2 is configured before Spring Boot has finished starting and I have not found a way to get Log4j2 to use a JVM property. If someone can find a better way to do it, I’m all ears.</p><h3>Logstash configuration</h3><p>In order to be able to accept requests from the library, you have to define a <a href="https://www.elastic.co/products/logstash">Logstash</a> pipeline with a configuration similar to this one:</p><h4>gelf-pipeline.conf</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/110db1182bd17bb5e19d5a590e98e834/href">https://medium.com/media/110db1182bd17bb5e19d5a590e98e834/href</a></iframe><p>We are using TCP instead of UDP because this way we can load-balance the <a href="https://www.elastic.co/products/logstash">Logstash</a> automatically with <a href="https://github.com/fabiolb/fabio">Fabio</a> and it does not support UDP yet, but if you don’t have that restriction, UDP is fine.</p><p>After that, we are removing some of the fields that we never use (source_host, className, facility), so they don’t consume space in the indexes, and then set the application name just in case it is not being sent, because we need it in the next step.</p><p>Finally, we define the index based on the application name and the date. Why? Because ElasticSearch index management, usually through the <a href="https://github.com/elastic/curator">curator utility</a>, is based in patterns against the names, and this way we can, for example, keep the logs of one application for 30 days and the logs of another application for just a week. <a href="https://www.elastic.co/products">Elastic Stack</a> introduced some index lifecyle management options in 6.6, but I still find it easier to manage them through the curator.</p><p>As the comments in the configuration file tell you, if you uncomment the stdout output, you will be able to see in the console where you launched <a href="https://www.elastic.co/products/logstash">Logstash</a> what it is received and then sent to elastic (or better yet, comment the elasticsearch section until you are comfortable with what you are seeing). That’s pretty useful if you want to test if it really works by installing <a href="https://www.elastic.co/products/logstash">Logstash</a> locally and sending the logs there so you can see what gets there in the console.</p><h3>Extra bonus</h3><p>As mentioned earlier, with the configuration we have shown the Gelf library sends all the MDC fields to be indexed, and that’s something you can take advantage of. For example, we are using it to add some extra fields like “operation called”, “parameters”, “Authenticated principal”, “client ip” through some AOP magic (see <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop">Aspect Oriented Programming with Spring</a> for reference). But basically, the idea is to have some code like this one to add extra fields automatically:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/817cce57a2947646c20cbb53e6d7d40a/href">https://medium.com/media/817cce57a2947646c20cbb53e6d7d40a/href</a></iframe><p>We use this technique just inside Aspects, not to clutter the code, to add some common fields, but it is still possible to parse the message string in <a href="https://www.elastic.co/products/logstash">Logstash</a> and extract the fields there using the typical grok filter ( see the <a href="https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html">Grok filter plugin</a> for reference ).</p><p>You can see here a sample log message, as it is displayed in <a href="https://www.elastic.co/products/kibana">Kibana</a> when looking at the details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*IUDEigJlBhf7kD0ss3V0cA.png" /><figcaption>Sample log message details as seen in Kibana</figcaption></figure><h3>Conclusion</h3><p>With these settings, one should be able to develop applications that, when deployed, send the logs automatically to the <a href="https://www.elastic.co/products">Elastic Stack</a> without wasting much space due to old log files and with messages that are easier to index and filter. Don’t forget that what I have shown is one way of doing it, the one that serves us well, so there are lots of things that can be customized to suit a different set of requirements. In any case, remember not to log everything but just what is necessary, especially in production ;).</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1809e81c6a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real life Java: From numbers to localized text ordinals using ICU4J]]></title>
            <link>https://medium.com/@d.lopez.j/real-life-java-from-numbers-to-localized-text-ordinals-using-icu4j-f8146d64b0fd?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8146d64b0fd</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 06:31:00 GMT</pubDate>
            <atom:updated>2018-07-17T06:31:00.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NPh0febkoDRDVGZR" /><figcaption>Photo by <a href="https://unsplash.com/@lemonvlad?utm_source=medium&amp;utm_medium=referral">Vladislav Klapin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I had to build a Java application that reads a series of data and puts “human readable” labels on it. Some of the texts the application has to generate use ordinals like “This is the <strong><em>first</em> </strong>report…” and they have to be displayed in three different languages, so instead of using a non-scalable solution (if/else, switch), I decided to generate the messages from the numeric data using something more flexible. A web search turned up <a href="http://icu-project.org/apiref/icu4j/">ICU4J </a>(from the project International Components for Unicode) as a common solution, so I decided to give it a go.</p><p>The technical documentation is quite complete, but I found the samples and usability of the library a bit lacking, especially in the localization aspect, so I decided to show my results and contribute a bit back.</p><p>If you want to convert numbers into their text ordinals counterparts in Java, the first step would be to include the <a href="http://icu-project.org/apiref/icu4j/">ICU4J </a>library in your project, for example using.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e9c7a41e1445b52f06d43092b733411/href">https://medium.com/media/1e9c7a41e1445b52f06d43092b733411/href</a></iframe><p>Once we have done that, there are several ways you can display a message with <a href="http://icu-project.org/apiref/icu4j/">ICU4J</a>, but when you are dealing with ordinals, you have to become familiar with the <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html">RuleBasedNumberFormat</a> concept. A <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html">RuleBasedNumberFormat</a> uses a given locale and a format specification (duration, numbering, ordinal or spellout) to format numbers using a specified rule. For example, 1 in English as a spelled out ordinal is “first”, as a spelled out cardinal is “one”, as duration “with words” is “1 second”. In our case, we want the spelled out ordinal (“<em>%spellout-ordinal</em>” rule), so we can test it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6e23e92756df55a3a04861e5cf1bc38/href">https://medium.com/media/d6e23e92756df55a3a04861e5cf1bc38/href</a></iframe><p>So far, so good, but how about doing the same with other languages, like Spanish? Well, if we try we’ll get a runtime error because with the Spanish locale we don’t get the same rules as with the English one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/467eebd2385d64abfb4ca6a9d26002f2/href">https://medium.com/media/467eebd2385d64abfb4ca6a9d26002f2/href</a></iframe><p>So, how do you find out what rules are in there for a given locale? Well, you can open the jar files and browse some binary files, as I did first :O, or you can use the API and find it the easy way, with this code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61269c676e5b46e5018624b4f12c3acc/href">https://medium.com/media/61269c676e5b46e5018624b4f12c3acc/href</a></iframe><p>After executing this code, we can see the problem: Spanish has genders so we cannot use the same rule for masculine and feminine nouns. On top of that, the masculine form is different when you use it as a noun or an adjective. In our sample sentence, “This is the <strong><em>first</em> </strong>report…”, the noun, report, in Spanish is masculine and the ordinal is used as an adjective, so we’ll need to use the rule “%spellout-ordinal-masculine-adjective”. Let’s try again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c362bd0c6591f1f88107900c4ceaa4a/href">https://medium.com/media/4c362bd0c6591f1f88107900c4ceaa4a/href</a></iframe><p>Great, that works. But the code is kind of clumsy and we would have to change the rule depending on the context… there must be an easy way, right? Well, I was about to try to extend the <a href="https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html">MessageFormat</a> class to handle this use case more easily when I realized IC4J already does that, and their class is named… <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/MessageFormat.html">MessageFormat</a>, oh yeah.</p><p>In this case, when we create the <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/MessageFormat.html">MessageFormat</a> instance, we have to choose which locale will be used along with it, and then we can provide the rule as part of the patterns for the parameters. For example, we can create two different <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/MessageFormat.html">MessageFormat</a> instances with the messages in English and Spanish, and tell them, in the patterns, to use the appropriate rule in each case. After that, a call to MessageFormat.format, passing the number as a parameter, will return the correct text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/341e4d08b421b0e7cc3e6a69d90d686e/href">https://medium.com/media/341e4d08b421b0e7cc3e6a69d90d686e/href</a></iframe><p>Let’s test if we can adapt the messages easily. In some contexts, we could translate the English word “report” for the Spanish word “memoria” instead of “informe”. “Memoria” is feminine, so we just have to change the rule specified in the pattern and…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ca3f902e2628aac7ec0c845dcbfb82/href">https://medium.com/media/46ca3f902e2628aac7ec0c845dcbfb82/href</a></iframe><p>Voilà!</p><p>With that logic in place, it is fairly easy to create files that contain the MessageFormat text for each locale and from that, render the messages correctly.</p><p>There are plenty of other things you can do with the library, like creating your own definitions if your locale is not supported by default etc., so keep playing with the library if you are interested.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8146d64b0fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real life Java: Aggregating nested collection with streams]]></title>
            <link>https://medium.com/@d.lopez.j/real-life-java-aggregating-nested-collection-with-streams-afe442ab9d7?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/afe442ab9d7</guid>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 19:10:44 GMT</pubDate>
            <atom:updated>2018-06-08T19:10:44.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the times I had used the “relatively new” streams in Java, it was for straight-forward tasks with operations on one stream. I sometimes use more sophisticated collectors, like <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-">Collectors.toMap</a>, but recently I had to use more complicated stuff to solve a real problem and I thought it might interesting writing about it, as the examples one usually reads about are synthetic and lack the focus of solving a real problem.</p><p>In this case, my problem was gathering some data from some <a href="https://www.atlassian.com/software/jira">Jira</a> reports and producing some statistics. The part about gathering the data I did simply by exporting some Jira filters into Excel files and reading them using the <a href="https://poi.apache.org/">Apache POI library</a> (also using streams). I was just interested in some of the data (Issues, components, versions and time reported by users) so I created two simple classes to hold the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5cb428159d0c259fddd40c8b417c85d/href">https://medium.com/media/a5cb428159d0c259fddd40c8b417c85d/href</a></iframe><p>Basically, an issue holds the component and version attributes and a list of reports that include the username and the time reported in that task. In this case, I weren’t interested in the dates of the reports, as they had already been filtered at the Jira level.</p><p>First, I read the data from several excel files, one with the issues definition and others with the time reports for a given dates interval and end up with a “<em>List&lt;Issue&gt; </em>nonEmptyIssues” structure where we have the issues that have some useful reports.</p><p>Once we have the data read, the questions to answer were:</p><p>· <strong>How much time was reported by each user?</strong></p><p>· <strong>How much time was reported for each component?</strong></p><p>· <strong>How much time was reported for each version?</strong></p><p>The <strong>user report</strong> is the simplest, as the user attribute is at the report level: I just had to convert the stream of issues into a stream of reports and then aggregate the time for each report, for each user. In “stream-speak”, that means flattening the stream, grouping by user and then reducing each list of “reports by user”. The final code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeba6ad95e7f417c98711d32ea9ea9df/href">https://medium.com/media/aeba6ad95e7f417c98711d32ea9ea9df/href</a></iframe><p>The <strong>component and version reports</strong> are a bit more complicated, as they are attributes at the <em>Issue</em> level, but we want to aggregate the time at the <em>Report</em> level. So, in this case, we have to group first and then for the values of the grouping (a list of issues), transform them into a stream of issues and then aggregate them. Fortunately, there is a Collectors.groupingBy function that allows you to operate further on the values associated to each key. The final code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8b358d45ecd655873f529aad33922a/href">https://medium.com/media/9c8b358d45ecd655873f529aad33922a/href</a></iframe><p>Unfortunately, the Collector that we need to convert the collection of issues into a stream of reports (<a href="https://docs.oracle.com/javase/9/docs/api/java/util/stream/Collectors.html#flatMapping-java.util.function.Function-java.util.stream.Collector-">Collectors.flatMapping</a>) was not present in Java until version 9, but a bit of <a href="https://stackoverflow.com/questions/41878646/flat-mapping-collector-for-property-of-a-class-using-groupingby">StackOverflow</a> and <a href="https://stackoverflow.com/questions/41878646/flat-mapping-collector-for-property-of-a-class-using-groupingby">s</a>ome smart extension and voilà, you can backport it to Java 8:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7a682086e07225da628b3cb7ce9743/href">https://medium.com/media/fb7a682086e07225da628b3cb7ce9743/href</a></iframe><p>And that’s it, you can execute these pieces of code in order to get aggregated stats for each user, component and version, and the code is much simpler than what is used to be. These are some of the type of things that make streams really shine.</p><p>Happy coding!</p><p>PS: As a side note, if you encapsulate some functions properly, reading the Excel sheets can look also quite elegant:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79bac0e931ef66cd20243edf973b73f1/href">https://medium.com/media/79bac0e931ef66cd20243edf973b73f1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afe442ab9d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpringBoot, Maven, Jenkins & Git: How to identify your release automagically]]></title>
            <link>https://medium.com/@d.lopez.j/springboot-maven-jenkins-git-how-to-identify-your-release-automagically-13261ece13f?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/13261ece13f</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 18:01:37 GMT</pubDate>
            <atom:updated>2018-09-29T16:07:03.921Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the issues that usually comes up when you have an application up &amp; running is finding out what’s deployed in the different servers so you can know if what you committed in the source code repository is deployed in those releases or not.</p><p>That thing that sounds so trivial becomes not that easy when you add automatic deployment, branches and everything that allows you to be “agile”, so you need to add some automatic mechanisms to your release and deployment process in order to make it easy again.</p><p>As a brief summary, these are the things we want to facilitate:</p><ul><li>Given a release, we want to know what is included in that release.</li><li>Given a deployed application, we want to know which release is deployed.</li><li>Having a look at the source code repository, we want to know if a given commit is included in a release</li></ul><h3><strong>First step, identifying what’s in a deployed </strong><a href="https://projects.spring.io/spring-boot/"><strong>Spring Boot</strong></a><strong> application</strong></h3><p>One of the easiest ways is to include the <a href="https://github.com/ktoso/maven-git-commit-id-plugin">maven git commit id plugin</a> , something you can do easily, just by adding this, for example, to your pom.xml file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88832d886ce45569c0af6e00bce51dd6/href">https://medium.com/media/88832d886ce45569c0af6e00bce51dd6/href</a></iframe><p>After that, enable the <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-application-info">Spring Boot info actuator</a> by adding the actuator dependency</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7650209f40e8ebdf3d1c44c787397f55/href">https://medium.com/media/7650209f40e8ebdf3d1c44c787397f55/href</a></iframe><p>After that and after creating a release, you should be able to identify what’s included in the deployed release by looking at your.app.com/info (or whatever custom path you configured your actuator to answer at).</p><p>You can get more information about the whole process at the following Baeldung tutorials: <a href="http://www.baeldung.com/spring-git-information">Injecting Git Information Into Spring</a> and <a href="http://www.baeldung.com/spring-boot-actuators">Spring Boot Actuator</a>.</p><h3><strong>Second step, using Maven plugins in Jenkins to set a specific version and tag it in the source code repository</strong></h3><p>Now that we know we can get the release information from the deployed application, what we need now is to add the information that we want in the release. In order to do that, we will use various Maven plugins: <a href="https://www.mojohaus.org/build-helper-maven-plugin/">Build Helper</a>, <a href="https://www.mojohaus.org/versions-maven-plugin/">Versions</a> and the <a href="https://maven.apache.org/scm/maven-scm-plugin/">Maven SCM Plugin</a>. With those plugins, we can read the current version of the project using “<em>build-helper:parse-version</em>”, use the properties configured by the plugin to set a new version with “<em>versions:set -DnewVersion=\${parsedVersion.majorVersion}.\${parsedVersion.minorVersion}.\${parsedVersion.incrementalVersion}-BUILD-${BUILD_NUMBER} versions:commit</em>”.</p><p>After setting the new version (note that if the project is a –SNAPSHOT version, it removes the suffix), we will also use “<em>mvn –Dusername=Jenkins scm:tag</em>” to tag automatically the release in the source repository.</p><p>Remember that In order to be able to perform the scm commands, you have to set up the scm section of your pom correctly, include the Maven scm plugin, and define a user with the proper permissions in your settings.xml file.</p><p>For example, you could have something like that in your pom.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbe960d06c76de30be51572b2dbd4fa/href">https://medium.com/media/3cbe960d06c76de30be51572b2dbd4fa/href</a></iframe><p>And something like this in your settings.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20dea5188bd3ff2ea2edab7ea932d918/href">https://medium.com/media/20dea5188bd3ff2ea2edab7ea932d918/href</a></iframe><p>Check other options at the instructions about <a href="https://maven.apache.org/scm/maven-scm-plugin/examples/bootstrapping-with-pom.html">Bootstrapping a Project Using a POM</a> of the <a href="https://maven.apache.org/scm/maven-scm-plugin/">Maven SCM Plugin</a>.</p><p>All in all, one can add something like the following snippets to your project <a href="https://jenkins.io/doc/book/pipeline/jenkinsfile/">Jenkinsfile</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b04f285a858cb94db5c3dd138cb01af9/href">https://medium.com/media/b04f285a858cb94db5c3dd138cb01af9/href</a></iframe><p>In them, we define a parameter (see <a href="https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters">Handling parameters</a> so we can toggle the feature on/off and then a <a href="https://jenkins.io/doc/pipeline/steps/pipeline-stage-step/">Stage</a> with some steps that that set the proper version, deploy the release to the artifacts repository and then tags the release with the build number at the source code repository.</p><p>Et voilà, when we execute the Pipeline and set the UPLOAD_TO_REPOSITORY variable set to true:</p><ul><li>The artifact uploaded to the repository will include the Jenkins build number.</li><li>When the artifact is deployed, it will show at the info endpoint the last commit information and the build number from the Jenkins execution that generated it.</li><li>The source code repository will have a tag with the version number included in the artifact at the point where it was created.</li></ul><p>With that information, it is very easy to find out what is deployed and given that the info endpoint response type is JSON, it would be also very easy to integrate that information in other tools, like a screen where the versions deployed in the different servers are shown, a checker that verifies that all the servers in a balanced cluster are running the same version, etc.</p><p>And that’s all for today, happy coding.</p><p>D.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13261ece13f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick tip: Elasticsearch + Consul + health check + basic authentication]]></title>
            <link>https://medium.com/@d.lopez.j/quick-tip-elasticsearch-consul-health-check-basic-authentication-eb445cfbebda?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb445cfbebda</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[consul]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 17:33:40 GMT</pubDate>
            <atom:updated>2018-04-10T17:33:40.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I’ve been installing the “<a href="https://www.elastic.co/products">Elastic Stack</a>”, previously known as ELK, and one of the steps took me a while to figure it out, due to outdated documentation and missing pieces in the examples for the specific syntax that you need to get right, so here it comes:</p><p>Imagine you have already gone through the <a href="https://www.elastic.co/start">Elastic Stack quick start</a> and you have it secured with basic authentication, either directly through the configuration or through the recommended <a href="https://www.elastic.co/products/x-pack">X-Pack plugin</a>.</p><p>Imagine as well that you have a <a href="https://www.consul.io/">Consul</a> cluster where you register your services so you can do some monitoring and load-balancing (I’m using <a href="https://fabiolb.net/">Fabio</a> for that and I’m truly happy with it).</p><p>Now you want to register your <a href="https://www.elastic.co/products/elasticsearch">Elasticsearch</a> service in your consul cluster, in order to do so, you will probably want to register the <a href="https://www.elastic.co/products/elasticsearch">Elasticsearch</a> application <a href="https://www.consul.io/docs/agent/services.html">as a service</a> with a configuration file, in the consul.d directory, like this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c10aac77bf295291161ab4220bc91ee/href">https://medium.com/media/2c10aac77bf295291161ab4220bc91ee/href</a></iframe><p>So simple right? But then you want more, so you decide to add a check so you can detect when the node is offline, so you go and add the check section to the configuration, like this (note that the check uses a simple HTTP check against the port because we don’t want to check the cluster health to decide about this specific node’s health):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1179aa30f98d4b526609683b3a563da8/href">https://medium.com/media/1179aa30f98d4b526609683b3a563da8/href</a></iframe><p>And kaboum! Consul says your node is always offline. Why? Because the Elasticsearch service is protected and the check is returning a “401 Unauthorized” response. So how do you add the proper credentials for the check? Well, there are many issues open in Consul about how to add headers to the HTTP checks (see for example <a href="https://github.com/hashicorp/consul/issues/1896">#1896</a>, <a href="https://github.com/hashicorp/consul/issues/1184">#1184</a> and <a href="https://github.com/hashicorp/consul/pull/3107">#3107</a>) , but after quite a bit of trial &amp; error, this is the syntax that works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67977d6e49e3ca3c6629a734704184b9/href">https://medium.com/media/67977d6e49e3ca3c6629a734704184b9/href</a></iframe><p>Note that “<em>T2hZZWFoOllvdXRob3VnaHR0aGF0d2FzbXlwYXNzd29yZD8=</em>” are the combined credentials (username:password) encoded using Base64. You can get your own version using any program that is able to produce those headers.</p><p>Note also that the credentials can be easily decoded (they are simply encoded, not encrypted) so make sure the file is well protected. Creating a user in Elasticsearch with just the most basic permissions to check the node status and nothing else, and using that would also be worth considering.</p><p>In any case, update the Consul service configuration , reload Consul and the check should work fine and your Elasticsearch node should be green in your Consul console.</p><p>That was all for today. It took me a while to put figure it out, so I thought I could save someone else, or even a future me ;), the trouble.</p><p>Happy deploying!</p><p>D.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb445cfbebda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot: Setting a unique ID per request]]></title>
            <link>https://medium.com/@d.lopez.j/spring-boot-setting-a-unique-id-per-request-dd648efef2b?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd648efef2b</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 11:11:56 GMT</pubDate>
            <atom:updated>2019-08-02T08:10:50.393Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://projects.spring.io/spring-boot/">Spring Boot</a> web applications, like many others unless you go for the mono-threaded option (yuck!) serve requests concurrently. That brings many advantages, but one of the drawbacks that come with it is that it makes harder to trace what each request is doing, as it is doing it while other requests are doing other, often similar, things. That hurts logging information badly, as the messages generated for one request can easily be intermingled with other messages generated for other requests.</p><p>To alleviate this issue, the first thing we are going to do is to use a common technique that both <a href="https://logback.qos.ch/">Logback </a>and <a href="https://logging.apache.org/log4j/2.0/">Log4j2</a> support: <a href="http://www.baeldung.com/mdc-in-log4j-2-logback">setting a key through the Mapped Diagnostic Context (MDC)</a>. As Logback mentions: “The MDC manages contextual information on a per thread basis” so once you have set the key in a thread, all the log requests performed from that thread will use that context. It is important to remark the “on a per thread basis” because the calls you perform in a different thread won’t be using that context, hence they won’t have the same key.</p><p>Setting it an MDC key is as easy as typing</p><p><em>MDC.put(“key“, “value”);</em></p><p>And once you have the key defined in the logging context, you can define your log formatter so it uses that key and prints it in each line. (No worries, I’ll show you how to do that in a minute.)</p><p>But let’s dig a bit further. Wouldn’t it be nice that if clients sending requests would be able to tell you “the request that failed had the key xxxxx”. You would then be able to filter your logs with that key and go straight to the lines that you need to check. Cool, huh? That works not only for clients but for proxies, gateways, interceptors and other mechanisms that you might be using to analyze your responses. For that, what we’ll do is add an HTTP header to the response with the ID we used for all the processes producing that response.</p><p>Finally, let’s go the extra mile. Sometimes, if you are using proxy-gateway services or your application is one service called by other services, the request itself might already have and ID assigned. That ID, sometimes called correlation ID, serves the purpose of identifying the various requests performed at the various services to serve one final client request. A common mechanism to provide that ID in the world of web applications is through an http header, so what we’ll do is check if there is a header providing the correlation ID, and if that’s the case, use it instead of generating a new ID.</p><p>Ok, now let’s do that in Spring Boot: We’ll need a configuration class that creates a FilterRegistrationBean with our servlet. We’ll also use Spring Boot’s great configuration capabilities and let the user configure the names of the headers involved and the key of the MDC, while providing some defaults. In the end, the configuration class might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31750a13bc8e1d64863aac98bfa17e78/href">https://medium.com/media/31750a13bc8e1d64863aac98bfa17e78/href</a></iframe><p>We can then create the filter itself. We need to verify if we received a correlation ID in the request header, if specified, or else create a new ID. Set the ID with the right key at the MDC and add the response header, if necessary, and make sure we are cleaning up the MDC key correctly once the request is done.</p><p>All in all, that’s how the filter might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc3e1c9080a560c6d496bef7df58bce0/href">https://medium.com/media/dc3e1c9080a560c6d496bef7df58bce0/href</a></iframe><p>You can then configure your logs with a pattern like this one(in this example using Log4j2) where we add the MDC key (<em>Slf4jMDCFilter.UUID</em> in this case)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*zQL4kkZT1qNQR7JXMiOTiA.png" /><figcaption>Log4j2 pattern</figcaption></figure><p>And your log messages will look something like these, where the UUID for the request is the second field after the date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*CnHU89EosiJoIdkoR2XOwQ.png" /><figcaption>Log messages with a unique ID added</figcaption></figure><p>Now imagine you launch a battery of tests against your service using <a href="https://www.getpostman.com/docs/postman/collection_runs/starting_a_collection_run">Postman collection runner</a>, for example. If you wanted to identify which log lines correspond to each request, you would just need to check the headers of the response and look for the one including the ID (<em>Response_Token</em> in this case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*n9Iys1RgbuMXDG3v_Cm_5Q.png" /></figure><p>and with that ID you can browse the logs and identify exactly which are the log messages that correspond exactly to that request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*PWPbub-cvt4UqK1swk0ECA.png" /><figcaption>Log lines identified by the corresponding ID</figcaption></figure><p>The request header can also be pretty useful if you are doing some test requests and you don’t want a unique ID per request but a way to distinguish the log messages from your requests from the other log messages.</p><p>For example, you could configure a request header like this (remember that by default we set no request header):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*TdzPX_8J0rDyzx-1Wcc3dg.png" /><figcaption>Setting a request header to check for a correlation ID</figcaption></figure><p>set the request header like this in Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*1sVjR-vshuQqiX1Q8dR2uA.png" /><figcaption>Setting the ID in a request header</figcaption></figure><p>and your log messages would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*CHIZOBt98QDbgcsiYh7x8w.png" /><figcaption>Setting a fixed correlation ID for testing</figcaption></figure><p>The ID is also a perfect candidate to parse in centralised logging platforms (<a href="https://www.elastic.co/elk-stack">Elastic Stack,</a> <a href="https://www.graylog.org/">Graylog</a>…) so you can filter log messages directly for that field.</p><p>Just a friendly reminder: if you launch an asynchronous call from your code serving a request, the log messages produced from the code executed asynchronously won’t have the same ID so you will “lose” them unless you do something. The best solution I have found so far to that is to pass the value explicitely to the asynchronous code and do there the same thing the filter does: Set the ID at MDC, perform the task, clear the MDC.</p><p>You can find a complete working implemention of the code demonstrated in this entry here:</p><p>The filter configuration: <a href="https://github.com/Verdoso/GreenSummer/blob/master/summer-core/src/main/java/org/greeneyed/summer/config/Slf4jMDCFilterConfiguration.java">Slf4jMDCFilterConfiguration</a><br>The filter: <a href="https://github.com/Verdoso/GreenSummer/blob/master/summer-core/src/main/java/org/greeneyed/summer/filter/Slf4jMDCFilter.java">Slf4jMDCFilter</a></p><p>Happy coding and happy logging as well!</p><p>D.</p><p>Edit: If you need to go full “enterprisey” with correlation IDs and distributed tracing, I would recommend having a look at <a href="https://cloud.spring.io/spring-cloud-sleuth/">Spring Cloud Sleuth</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd648efef2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Multiple TTL Caches in Spring Boot dinamically]]></title>
            <link>https://medium.com/@d.lopez.j/configuring-multiple-ttl-caches-in-spring-boot-dinamically-75f4aa6809f3?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f4aa6809f3</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Mon, 16 Oct 2017 08:52:32 GMT</pubDate>
            <atom:updated>2017-10-16T08:52:32.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I started using Spring caching in my Spring Boot applications and I came across a very nice entry in Daniel Olszewski’s blog (<a href="http://dolszewski.com/spring/multiple-ttl-caches-in-spring-boot/">MULTIPLE TTL CACHES IN SPRING BOOT</a>) that indeed explains how to set up multiple caches in Spring Boot with a specified TTL (Time To Live) setting and is really worth reading it as it even explains how to test the functionality. So, if you have not read it already, I invite you to do go ahead and do it now, as I’ll build on top of that. Don’t worry, I’ll wait for you :X</p><p>When I was applying his advice in my code, I noticed that what I really wanted to do was externalize my cache settings so I could change them depending on the environment (for example, to disable long term caching in development). I also shared the article with some friends and they asked me if was applying the same settings to all the different caches or using the same settings as the blog entry does.</p><p>As I told them the blog entry is just the beginning and you should build on top of that, as I did, but I decided to share the step forward that I did to make things clearer.</p><p>Once you have your custom cache manager, it might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8665a166cfae20b926e4cccc10d1274b/href">https://medium.com/media/8665a166cfae20b926e4cccc10d1274b/href</a></iframe><p>Now, what we need to do is externalize the settings of the caches… but what if we want to introduce a new cache later on, will we need to come back to this class to build manually a new CaffeineCache and add it to the manager? That does not sound right, huh? I don’t like it either so let’s make it dynamic.</p><p>First, we’ll set up the configuration class to be filled up with external properties and make room for the caching properties in our configuration namespace by setting up a prefix. This is done with the following annotation (use whatever prefix you like):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8237aecb57c715b106d7877c31a1692a/href">https://medium.com/media/8237aecb57c715b106d7877c31a1692a/href</a></iframe><p>Then, we want to specify various settings for each cache, so let’s create a class to hold those values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af616f37f76ab1e5f8a99ee66db1923f/href">https://medium.com/media/af616f37f76ab1e5f8a99ee66db1923f/href</a></iframe><p>I know, I know, I’m “cheating” by using <a href="https://projectlombok.org/">Lombok</a> to avoid having to write the boilerplate code but such is life for us lazy programmers. And also… where’s the cache name? Fear not, it comes next.</p><p>We want to be able to add new caches settings dynamically without having to add more members to the CacheConfiguration class, so let’s use a dynamic structure and while we are at it, we need a name per configuration. This smells like a Map, so let’s add it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034945e3e4cf5dfb066d46097d7abce2/href">https://medium.com/media/034945e3e4cf5dfb066d46097d7abce2/href</a></iframe><p>And we now need just to modify slightly the CacheManager code so it uses the Map to create the List of caches dynamically. We can even make use of Java 8 streams to do it in one woosh.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1964bb1d3c062954a6f831a50b27d83b/href">https://medium.com/media/1964bb1d3c062954a6f831a50b27d83b/href</a></iframe><p>Note that if you wanted to add more configuration capabilities to the class, you would just need to change the <em>CacheSpec </em>class and then the internals of the <em>buildCache(…) </em>method so it takes those new values into account. As you can see in the <em>CacheSpec </em>class, you can have defaults in case no value is specified in the properties for certain attributes.</p><p>With these changes, in order to configure the same caches as previously, you just need to configure some properties like this: (for example in application.yml or an externalized per environment configuration file)</p><pre>caching:<br>  specs:<br>    xCache:<br>      timeout: 10  <br>    yCache:<br>      timeout: 60<br>      max: 500</pre><p>And if you want to add a new cache, you dont’a have to touch the CacheManager class, you just add a new section in the properties and that’s it:</p><pre>caching:<br>  specs:<br>    xCache:<br>      timeout: 10  <br>    yCache:<br>      timeout: 60<br>      max: 500<br>    aNewCache:<br>      timeout: 5<br>      max: 10</pre><p>All in all, the resulting CacheConfiguration class might look like this (thanks to Lombok)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5fdee4742c93e6dca54b3a9ee65f6a1/href">https://medium.com/media/c5fdee4742c93e6dca54b3a9ee65f6a1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f4aa6809f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[X-Factor Apps using the Spring Boot ecosystem, an overview]]></title>
            <link>https://medium.com/@d.lopez.j/x-factor-apps-using-the-spring-boot-ecosystem-an-overview-d16718a55e52?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16718a55e52</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Sun, 08 Oct 2017 18:50:52 GMT</pubDate>
            <atom:updated>2017-10-08T18:50:52.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>Nowadays, there are tons of literature and virtual ink written about how to develop for the cloud and make your applications Internet-scale. But how about those of us where the scale of our problems do not fit such model? Well, even if you are not developing for the cloud and you don’t need to go full scale with the <a href="https://12factor.net/">Twelve-Factor App</a> recommendations, there are still many benefits that can still be enjoyed by sticking to the main principles behind them. They are based on good practices to facilitate management &amp; deployment of applications, a requirement if you have to develop software as a service, but they still contain sound advice that can be applied in any circumstance. Quoting those basic principles, an app should:</p><p>1. Use declarative formats for setup automation, to minimize time and cost for new developers joining the project;</p><p>2. Have a clean contract with the underlying operating system, offering maximum portability between execution environments;</p><p>3. Be suitable for deployment on modern cloud platforms, obviating the need for servers and systems administration;</p><p>4. Minimize divergence between development and production, enabling continuous deployment for maximum agility;</p><p>5. Be able to scale up without significant changes to tooling, architecture, or development practices.</p><p>In this entry, I’ll outline a set of development practices, using <a href="https://projects.spring.io/spring-boot/">Spring Boot</a> &amp; co, to get you closer to these goals.</p><h3>Basic steps</h3><p>We are discussing here the development of Spring Boot applications, so you might want to start by using Spring Boot to <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-running-your-application.html">develop a packaged application</a> that requires no external container to be run. That provides the benefit of requiring no external servlet container setup &amp; configuration, which is usually a hassle when creating new environments from scratch for new team members or new deployment environments.</p><p>On top of that, in order to minimize hardcoded configurations, that would cause issues when deploying the packaged application in different environments, you could then <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html">externalize the configuration</a> values of your application and then move a step further and <a href="https://spring.io/guides/gs/centralized-configuration/">centralize it</a>, using a <a href="https://cloud.spring.io/spring-cloud-config/">Spring Cloud Config</a> Server. If the properties you want to externalize contain sensitive data, like database connection strings or passwords, don’t forget that you can <a href="https://cloud.spring.io/spring-cloud-config/single/spring-cloud-config.html#_encryption_and_decryption">encrypt the sensitive values</a> in the properties so you don’t have to expose them in plain text in your centralized configuration</p><p>With the above steps, you have mainly covered principles 1 and 4: The packaged app can be built, packaged and deployed automatically, from declarative files, and you can use the same artifact in all environments thanks to having the environment-specific properties externalized in a centralized server. That alone, is a big move forward compared to the once very common, and still present: “<em>These are the instructions to set up the application in your environment and these are the properties or files you have to write so the app runs (different for each environment)</em>”.</p><h3>Becoming a shepherd</h3><p>Now that you can run the application more easily in different environments, it is far easier to set up new servers, so you feel the need to start <a href="http://cloudscaling.com/blog/cloud-computing/the-history-of-pets-vs-cattle/">treating the servers more like cattle rather than like pets</a>. That is, you want to be able to spawn new servers with the new app without having to worry about the specific details of the servers, like IPs, ports, names. But that poses new challenges: How are clients going to call an app if they don’t know the IP of the server where it is deployed? Well, one solution is using a balancer with a well-known name, at least known to the clients, that redirects the traffic to the appropriate server(s). But that simply pushes the problem one layer because, now how does the balancer know the IP of the servers where the app is deployed?</p><p>Previously, the answer to this was “someone configures the balancer with the addresses of the servers where the app is deployed”. But now we want cattle, not pets, hence no fixed servers where the application is deployed. What can we do now? The answer is using a discovery service where apps register upon startup. This kind of services can be used to keep a list of apps/servers that the balancer can query to configure itself. For example, one can use <a href="https://www.consul.io/">HashiCorp Consul</a> and <a href="https://cloud.spring.io/spring-cloud-consul/">Spring Cloud Consul</a> so the Spring Boot applications register automatically when they start. Moreover, the URL of the discovery service can be an externalized property so the app can register itself in a different server depending on the environment (through spring active profiles and a different url in the externalized properties).</p><p>Once you have your apps registered in Consul, you can use <a href="https://github.com/hashicorp/consul-template">Consul Template</a> to query the active apps and the data of the servers hosting each of them and then <a href="https://www.hashicorp.com/blog/introducing-consul-template/">update automatically the configuration of your balancer</a>(be it Apache, Ngingx,HAProxy or others).</p><p>If you play your cards appropriately, you can configure it so when you start an instance of an app named myApp in the environment myEnv, you can then access it behind the name myApp.myEnv.myservices.mydomain.com. Moreover, if you start more than one server in the same environment, the balancer will distribute the traffic among them. Cool, huh?</p><h3>The toppings</h3><p>Don’t forget that once your servers are no longer pets, you’ll need to centralize their logs, as otherwise accessing them or even just keeping them might be a headache. You could use for that a logging platform like <a href="https://www.graylog.org/">GrayLog</a> or <a href="https://www.elastic.co/webinars/introduction-elk-stack">Elastic Stack</a> (ELK) or one of the various Logging-As-A-Service cloud based providers, depending on your needs and budget.</p><p>While you are at it, you can add some metrics &amp; monitoring to your servers/services with something like <a href="http://graphiteapp.org/">Graphite</a> or one of the various monitoring-as-a-service offerings, cloud based or on premise.</p><p>As you can see, just to test most of these things one would need to install many products in various servers, so it then becomes a good idea to start experimenting with containers so you can do it more easily. There are docker images of pretty much all of the services I linked above and you can easily <a href="https://spring.io/guides/gs/spring-boot-docker/">create your own docker files to deploy your Spring Boot applications</a>, so you don’t need a whole datacenter to test all the different pieces working together.</p><p>And that’s it, for now. I know this is just an outline and I did not provide much detail into how to actually implement any of those steps in a real application, but that would require not just one entry but a full series of entries. I always prefer to start by setting the end goal clearly, so all the intermediate pieces make sense and you just don’t follow one technique after another wondering “why am I doing this?”. So now that the destination is clear, I might add more entries describing some of the steps in more detail.</p><p>I hope you enjoyed it, happy coding!</p><p>D.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16718a55e52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot, MyBatis, multiple datasources and multiple mappers, all together holding hands]]></title>
            <link>https://medium.com/@d.lopez.j/spring-boot-mybatis-multiple-datasources-and-multiple-mappers-all-together-holding-hands-be74673c6a9f?source=rss-92b74318ee92------2</link>
            <guid isPermaLink="false">https://medium.com/p/be74673c6a9f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Daniel López]]></dc:creator>
            <pubDate>Tue, 23 May 2017 20:40:44 GMT</pubDate>
            <atom:updated>2018-02-06T21:32:26.672Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the issues with Spring Boot that I have come across a couple of times and that are usually a bit painful to solve is how to configure multiple datasources and mappers with MyBatis. I have always had to browse the web, check different sources and try different examples while fighting unclear error messages until I get it right. And then the next time configuration has changed in some subtle way either in MyBatis or Spring Boot and it’s all over again. Duh! So, now that I found another working solution, I wanted to share it in case it can help other developers going through the same pain. In this case, I’ll show how it’s done using a pure Java configuration approach instead of XML.</p><p>First, make sure you include the dependencies for the datasource implementation, in my case HikaryCP, and mybatis-spring-boot-starter. As I use HikaryCP instead of the default Tomcat datasource and I’m using Jetty instead of Tomcat, I have to exclude the Tomcat dependencies from mybatis-spring-boot-starter. Hence:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1ccc202d0935895af5a7abeda0a7c9/href">https://medium.com/media/7e1ccc202d0935895af5a7abeda0a7c9/href</a></iframe><p>In order to use more than one datasource you cannot relay on Spring Boot’s datasource autoconfiguration, but you still can set them up very easily using <a href="http://twitter.com/ConfigurationPropert">@ConfigurationPropert</a>ies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9b698da46070735afcd6efe9c3fcf9/href">https://medium.com/media/2d9b698da46070735afcd6efe9c3fcf9/href</a></iframe><p>Note that the <a href="http://twitter.com/Primary">@Primary</a> annotation is specified so the elements that require the default datasource do not complain about having more than one bean to choose from.</p><p>You can then set up both datasources like this in your application.yml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9451516d694d986594b2abbab4b0d1d/href">https://medium.com/media/b9451516d694d986594b2abbab4b0d1d/href</a></iframe><p>Now here it comes the tricky part, you have to configure more than one session with MyBatis and also configure the different mappers so each one use the right MyBatis session. This is the part that I have had to change a couple of times, depending on the Spring Boot and Mybatis versions, as there are different ways one can configure a Mapper in MyBatis and depending on the order you set up things, you will get all your mappers to use the primary datasource no matter what. You can see that the trick is that, in order to create each SqlSessionFactoryBean, we autowire each datasource specifying the name, and then we add each Mapper class directly to each SqlSessionFactory. We then create a MapperFactory for each Mapper using the right SqlSessionFactory, again specified by name. In my case, each Mapper interface has its corresponding .xml mapper file in resources but I suppouse annotation based mappers will work as well. Specifying the mapper twice seems like overkill, but you can try yourself what happens if you don’t do it*.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b898821cc011a08774f6bd8c416fa5ba/href">https://medium.com/media/b898821cc011a08774f6bd8c416fa5ba/href</a></iframe><p>After all of this, simply autowire the mapper class on your components and each one should connect to a different database.</p><p>To reiterate, *this works now using Spring Boot version 1.5.3 and MyBatis Spring Boot starter version 1.3.0. I hope it works for you as well, but if it does not, I would recommend trying to configure the Mappers differently like creating the Mapper beans directly, or using MapperScannerConfigurer beans (this one used to work for me, but I could not get it to work with the aforementioned versions).</p><p>At least, I hope it gave you some hints about where to start tweaking.<br>Happy coding!<br>D.</p><p>Edit February 2018: Added a project to Github demonstrating the technique: <a href="https://github.com/Verdoso/multi-mybatis-demo">https://github.com/Verdoso/multi-mybatis-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be74673c6a9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>