<?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 Batuhan Orhon on Medium]]></title>
        <description><![CDATA[Stories by Batuhan Orhon on Medium]]></description>
        <link>https://medium.com/@batuhanorhon?source=rss-5c76bc2fd50f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ej9afh1VZ5v3moxBNnb5Cg.jpeg</url>
            <title>Stories by Batuhan Orhon on Medium</title>
            <link>https://medium.com/@batuhanorhon?source=rss-5c76bc2fd50f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@batuhanorhon/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[Efficient Data Streaming: Implementing Kafka Connect and Debezium with Docker]]></title>
            <link>https://batuhanorhon.medium.com/efficient-data-streaming-implementing-kafka-connect-and-debezium-with-docker-f5a5d24f5aca?source=rss-5c76bc2fd50f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a5d24f5aca</guid>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Batuhan Orhon]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 11:46:04 GMT</pubDate>
            <atom:updated>2023-12-28T11:46:04.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*jqDUV-X5YRXTaTK1LVV4nQ.png" /></figure><h3>Introduction</h3><p>Hello everyone. In this article, I will demonstrate how to run Kafka Connect with a Debezium connector using Docker and implement a change data capture (CDC) configuration on a database. As its name makes clear, change data capture is the process of capturing the changes on a database. I am going to use DebeziumMySqlConnector to connect to a MySQL server. We will also discuss advantages of Kafka, Kafka Connect, and advantages of implementing custom consumer-producer services over Kafka Connect.</p><h3>Docker Version</h3><p>We will use docker to run our services. So please make sure you have docker installed if you are going to run it yourself. The versions I use throughout this article are:</p><ul><li><strong>Docker: </strong>24.0.7</li><li><strong>Docker-compose:</strong> 1.25.0</li></ul><h3>Apache Kafka</h3><p>First of all, let’s talk briefly about Apache Kafka. Kafka is a distributed messaging technology that has become incredibly popular in a short time thanks to its robust features. Here are some aspects that make Kafka a preferable messaging tool for software systems.</p><h4>Speed</h4><p>Kafka boasts high throughput for both publishing and subscribing to messages, making it suitable for handling real-time data feeds. Kafka handles data as byte arrays, and expects producers and consumers to handle the serialization and de-serialization processes. That way, it stores and serves data in a faster way.</p><h4>Distributed Architecture</h4><p>Kafka runs in a cluster on one or more servers, offering fault tolerance and high availability.</p><h4>Scalability</h4><p>It can scale out without downtime. You can easily add more brokers to the cluster to accommodate more data and more consumers.</p><p>Kafka has many more to offer. For more detail, please check the <a href="https://kafka.apache.org/documentation/#gettingStarted">Apache Kafka Documentation</a>.</p><h3>Components of Apache Kafka</h3><p>Here, I will shortly explain the components of Kafka which I am going to use and talk about in this article. If you are already familiar with Kafka, you can pass this part.</p><h4>Brokers</h4><p>Brokers are the Kafka servers that store data and serve clients. Typically multiple brokers run in a distributed manner for speed and reliability.</p><h4>Zookeeper</h4><p>Zookeeper is a centralized service for maintaining configuration information and synchronizing brokers.</p><h4>Topics</h4><p>Logical channels to which producers send messages and from which consumers read messages.</p><h4>Producers</h4><p>Producers are the applications or systems that publish (write) events or data records to Kafka topics.</p><h4>Consumers</h4><p>Consumers are the applications or systems that subscribe to (read) and process these records from Kafka topics.</p><h4>Kafka Connect</h4><p>Kafka Connect is a tool for <strong>scalably</strong> and <strong>reliably</strong> streaming data between Apache Kafka and other data systems.</p><h3>Let’s Start the Kafka Server!</h3><p>I want to show you how easy it is to run a zookeeper and a broker. I will use docker-compose in this article to run the zookeeper, broker, connector, and MySQL server since it makes it so easy to run all of them at the same time and integrated with each other.</p><p>First let’s create a docker-compose.yml to run only a zookeeper and a broker:</p><pre>version: &#39;3&#39;<br><br>services:<br>  zookeeper:<br>    image: zookeeper:latest<br>    container_name: container_zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>      - &quot;2888:2888&quot;<br>      - &quot;3888:3888&quot;<br><br>  kafka:<br>    image: debezium/kafka:latest<br>    container_name: container_broker<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      - ZOOKEEPER_CONNECT=zookeeper:2181<br>    depends_on:<br>      - zookeeper</pre><p>Now just move the docker-compose.yml file to your working directory and run:</p><pre>docker-compose up -d</pre><p>Then check the status of your docker containers with:</p><pre>docker ps</pre><p>Output should be something like that:</p><pre>CONTAINER ID   IMAGE                COMMAND                  CREATED         STATUS         PORTS                                                                                                                                       NAMES<br>3b70a576fb3a   debezium/kafka:latest   &quot;/docker-entrypoint.…&quot;   4 seconds ago   Up 2 seconds   8778/tcp, 9779/tcp, 0.0.0.0:9092-&gt;9092/tcp, :::9092-&gt;9092/tcp                                                                            container_broker<br>ba912d15f4d4   zookeeper:latest     &quot;/docker-entrypoint.…&quot;   6 seconds ago   Up 4 seconds   0.0.0.0:2181-&gt;2181/tcp, :::2181-&gt;2181/tcp, 0.0.0.0:2888-&gt;2888/tcp, :::2888-&gt;2888/tcp, 0.0.0.0:3888-&gt;3888/tcp, :::3888-&gt;3888/tcp, 8080/tcp   container_zookeeper</pre><p>So, our zookeeper and broker instances are up and running. Now, let’s produce some data and consume it using shell scripts inside our broker container.</p><p>Run the command below:</p><pre>docker inspect container_broker</pre><p>Take the ip address of the container from the output of the command above since we are going to use it. That value will change everytime you restart your container.</p><p>Then run:</p><pre>docker exec -it container_broker bash</pre><p>In the kafka bash run these commands with your own broker’s ip address:</p><pre>bin/kafka-topics.sh --create --topic test-topic --bootstrap-server your-broker-ip:9092 --partitions 1 --replication-factor 1<br>bin/kafka-console-producer.sh --broker-list your-broker-ip:9092 --topic test-topic</pre><p>Now you are inside the producer. Type these:</p><pre>Hello<br>World<br>!</pre><p>Now open another terminal window and run these (with your own broker ip):</p><pre>docker exec -it container_broker bash<br>bin/kafka-console-consumer.sh --bootstrap-server your-broker-ip:9092 --topic test-topic --from-beginning</pre><p>Here is my output :</p><pre>Hello<br>World<br>!</pre><p>Well, we have just produced some data and consumed it using kafka shell scripts. If you keep producing, the consumer will keep printing them out.It was simple wasn’t it? It is also quite easy to implement consumer- producer services using Spring-Kafka. Have a look at <a href="https://www.baeldung.com/spring-kafka">this link</a> to learn how to do it.</p><h3>Kafka Connect</h3><p>Now, I want to talk about Kafka Connect and show you how to use Debezium Connector to create a data flow from MySQL database to Kafka in real-time. However, Kafka Connect is a versatile tool that is not limited to just database monitoring. It can be used for a variety of purposes, enhancing the Kafka ecosystem’s capabilities. Here are some examples of how Kafka Connect can be utilized beyond just Change Data Capture (CDC) from databases:</p><ul><li><strong>Data Import/Export:</strong> It enables the import of data from external systems into Kafka and the export of data from Kafka to other systems. If you need to design an event-driven architecture, Kafka Connect helps you to integrate other components of your system with Kafka.</li><li><strong>Transformation:</strong> Using Single Message Transformation features of Kafka Connect, you can build data pipelines to not only transfer but transform your data in real-time.</li><li><strong>Log Aggregation:</strong> Kafka Connect can collect logs from various services and systems, centralizing them into Kafka topics. It might be useful to build a centralized log system and analyzing logs.</li><li><strong>Backup and Replication:</strong> Kafka Connect can be configured to back up data from Kafka topics to secondary storage systems or replicate data between Kafka clusters.</li><li><strong>Integrity Validation: </strong>Kafka Connect may also be used to maintain the integrity and consistency of the data through its journey.</li></ul><p>There are more use cases for Kafka Connect. At its simplest, it is used to connect Kafka with different components by using custom or third-party connector plugins.</p><h3>Running a Debezium MySQL Connector To Monitor a MySQL Database</h3><p>I uploaded all configuration files <a href="https://github.com/BatuhanOrhon/DebiziumMySqlConnector">here</a> on Github. You can create your own files with me by following the next steps or just clone the repository.</p><p>Now let’s close the docker containers we ran before:</p><pre>docker-compose down</pre><p>Running Mysql and Kafka Connect is a bit more complex compared to the previous example. But it is still easy. Let’s update our docker-compose.yml file as below:</p><pre>version: &#39;3&#39;<br><br>services:<br>  zookeeper:<br>    image: zookeeper:latest<br>    container_name: container_zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>      - &quot;2888:2888&quot;<br>      - &quot;3888:3888&quot;<br><br>  kafka:<br>    image: debezium/kafka:latest<br>    container_name: container_broker<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      - ZOOKEEPER_CONNECT=zookeeper:2181<br>    depends_on:<br>      - zookeeper<br><br>  mysql:<br>    image: mysql:latest<br>    container_name: container_mysql<br>    build: .<br>    ports:<br>      - &quot;3306:3306&quot;<br>    environment:<br>      MYSQL_ROOT_PASSWORD: password<br>      MYSQL_USER: debezium<br>      MYSQL_PASSWORD: dbz<br>      MYSQL_DATABASE: testdb<br><br>  connect:<br>    image: debezium/connect:latest<br>    container_name: container_kafka_connect<br>    ports:<br>      - &quot;8083:8083&quot;<br>    environment:<br>      GROUP_ID: 1<br>      CONFIG_STORAGE_TOPIC: kafka_connect_configs<br>      OFFSET_STORAGE_TOPIC: kafka_connect_offsets<br>      STATUS_STORAGE_TOPIC: kafka_connect_statuses<br>      BOOTSTRAP_SERVERS: kafka:9092<br>      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter<br>      CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter<br>      CONNECT_KEY_CONVERTER_SCHEMAS_ENABLE: &quot;false&quot;<br>      CONNECT_VALUE_CONVERTER_SCHEMAS_ENABLE: &quot;false&quot;<br>    depends_on:<br>      - zookeeper<br>      - kafka<br>      - mysql</pre><p>We need a mysql.cnf file to make the mysql server provide necessary logs for Debezium connector to monitor database. So, please create a file named mysql.cnf and write the content below into it:</p><pre>[mysqld]<br>skip-host-cache<br>skip-name-resolve<br><br>user=mysql<br>symbolic-links=0<br><br>server-id = 223344<br>log_bin = mysql-bin<br>expire_logs_days=1<br>binlog_format = row</pre><p>Additionally, we need a Dockerfile to mount that mysql.cnf file to the mysql image. We could do that in yml but we need to update the file access rules since mysql ignores a cnf file accessible by everyone in its latest versions. Note that, this is a detail. Thus, create a file named Dockerfile and add the below content into it:</p><pre>FROM mysql:latest<br>COPY mysql.cnf /etc/mysql/conf.d/mysql.cnf<br>RUN chmod 600 /etc/mysql/conf.d/mysql.cnf</pre><p>Lastly, we need a debezium-config.json file to add a Debezium MySql Connector to our Kafka Connect server. We will be there soon, for now just create a file named debezium-config.json and add the below content into it:</p><pre>{<br>  &quot;name&quot;: &quot;mysql-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.mysql.MySqlConnector&quot;,<br>    &quot;tasks.max&quot;: &quot;1&quot;,<br>    &quot;database.hostname&quot;: &quot;mysql&quot;,<br>    &quot;database.port&quot;: &quot;3306&quot;,<br>    &quot;database.user&quot;: &quot;debezium&quot;,<br>    &quot;database.password&quot;: &quot;dbz&quot;,<br>    &quot;database.server.id&quot;: &quot;223344&quot;,<br>    &quot;database.server.name&quot;: &quot;testdb&quot;,<br>    &quot;topic.prefix&quot;: &quot;fullfillment&quot; ,<br>    &quot;database.include.list&quot;: &quot;testdb&quot;,<br>    &quot;database.history.kafka.bootstrap.servers&quot;: &quot;kafka:9092&quot;,<br>    &quot;database.history.kafka.topic&quot;: &quot;schema-changes&quot;,<br>    &quot;database.allowPublicKeyRetrieval&quot;: &quot;true&quot;<br>  }<br>}</pre><p>Well, now we are ready to start our containers once again.</p><pre>docker-compose up -d</pre><p>As a last step, we need to give permissions to our debezium db user, create a table and insert data into it in MySql container. Let’s connect to it using the command below. Note that MySql may take some time to initialize if you see an error like “ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’” wait for a while and try again.</p><pre>docker exec -it container_mysql mysql -h localhost -u root -p testdb</pre><p>Our root password is: “password”.</p><p>Run the below commands to get our db ready for our connector to monitor:</p><pre>create table test_table (id int not null auto_increment primary key, name varchar(20) not null, surname varchar(20) not null);<br>insert into test_table (name, surname) values (&quot;Tom&quot;, &quot;Bombadil&quot;), (&quot;Anakin&quot;, &quot;Skywalker&quot;);<br>GRANT ALL PRIVILEGES ON *.* TO &#39;debezium&#39;@&#39;%&#39;;<br>FLUSH PRIVILEGES;<br>exit<br></pre><p>As next step, we need to send a curl request to the Kafka Connect server to start a connector with the configuration file debezium-config.json we created above:</p><pre>curl -i -X POST -H &quot;Accept:application/json&quot; -H &quot;Content-Type:application/json&quot; localhost:8083/connectors --data @debezium-config.json</pre><p><strong>Note</strong>: Kafka Connect offers configuration options, status check, and more using http requests. Have a look at them on <a href="https://docs.confluent.io/platform/current/connect/references/restapi.html">Kafka Connect Rest Interface</a> documents.</p><p>Now let’s connect to our broker container once again. Before that don’t forget to get the ip address of the service as we did before with <strong>docker inspect.</strong></p><pre>docker inspect container_broker</pre><pre>docker exec -it container_broker bash</pre><p>To see the topics added by connector, use:</p><pre>bin/kafka-topics.sh --list --bootstrap-server your-broker-ip:9092</pre><p>The output will be:</p><pre>__consumer_offsets<br>kafka_connect_configs<br>kafka_connect_offsets<br>kafka_connect_statuses<br>schema-changes<br>testdb<br>testdb.testdb.test_table</pre><p>I won’t go into detail of the meanings of these topics. The topic testdb.testdb.test_table is the one that connector produces the monitoring data of the table to. Let’s consume that data to see what it looks like:</p><pre>bin/kafka-console-consumer.sh --bootstrap-server your-broker-ip:9092 --topic testdb.testdb.test_table --from-beginning</pre><p>The output is:</p><pre>{<br>  &quot;before&quot;: null,<br>  &quot;after&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Tom&quot;,<br>    &quot;surname&quot;: &quot;Bombadil&quot;<br>  },<br>  &quot;source&quot;: {<br>    &quot;version&quot;: &quot;1.0.3.Final&quot;,<br>    &quot;connector&quot;: &quot;mysql&quot;,<br>    &quot;name&quot;: &quot;testdb&quot;,<br>    &quot;ts_ms&quot;: 0,<br>    &quot;snapshot&quot;: &quot;true&quot;,<br>    &quot;db&quot;: &quot;testdb&quot;,<br>    &quot;table&quot;: &quot;test_table&quot;,<br>    &quot;server_id&quot;: 0,<br>    &quot;gtid&quot;: null,<br>    &quot;file&quot;: &quot;binlog.000002&quot;,<br>    &quot;pos&quot;: 1411,<br>    &quot;row&quot;: 0,<br>    &quot;thread&quot;: null,<br>    &quot;query&quot;: null<br>  },<br>  &quot;op&quot;: &quot;c&quot;,<br>  &quot;ts_ms&quot;: 1703690764612<br>}<br>{<br>  &quot;before&quot;: null,<br>  &quot;after&quot;: {<br>    &quot;id&quot;: 2,<br>    &quot;name&quot;: &quot;Anakin&quot;,<br>    &quot;surname&quot;: &quot;Skywalker&quot;<br>  },<br>  &quot;source&quot;: {<br>    &quot;version&quot;: &quot;1.0.3.Final&quot;,<br>    &quot;connector&quot;: &quot;mysql&quot;,<br>    &quot;name&quot;: &quot;testdb&quot;,<br>    &quot;ts_ms&quot;: 0,<br>    &quot;snapshot&quot;: &quot;last&quot;,<br>    &quot;db&quot;: &quot;testdb&quot;,<br>    &quot;table&quot;: &quot;test_table&quot;,<br>    &quot;server_id&quot;: 0,<br>    &quot;gtid&quot;: null,<br>    &quot;file&quot;: &quot;binlog.000002&quot;,<br>    &quot;pos&quot;: 1411,<br>    &quot;row&quot;: 0,<br>    &quot;thread&quot;: null,<br>    &quot;query&quot;: null<br>  },<br>  &quot;op&quot;: &quot;c&quot;,<br>  &quot;ts_ms&quot;: 1703690764612<br>}</pre><p>As seen, previous entities (null) and newly inserted entities are shown with some other information. If we had deleted rows, updated rows, etc. they would also be seen in the output. So, that is it! We have imported a table change to our kafka topic. Creating a data flow that consumes data from a Kafka Topic and writes into database could be easily done by simple changes in our configuration.</p><h3>Kafka Connect vs. Custom Consumer Producer Implementation</h3><p>Note that, anything done using Kafka Connect can also be done using custom consumers and producers. Kafka Connect offers us out-of-the-box plugins in <a href="https://www.confluent.io/hub">confluent hub</a>. It also has java libraries, so you can build your own connectors, or connector plugins.</p><h4>Advantages of Kafka Connect</h4><p><strong>Ease of Use: </strong>Kafka Connect abstracts much of the boilerplate code required for data integration, allowing you to define connectors with simple configuration files. This reduces the complexity and time needed to start moving data.</p><p><strong>Reliability: </strong>Worker nodes run connectors, and both worker nodes and connectors operate in a distributed manner to ensure fault tolerance. This setup enables Kafka Connect to maintain high performance and reliability, even in the event of failures.</p><p><strong>Modularity: </strong>Its pluggable architecture means you can easily add new connectors as your needs evolve. There’s a large community of connectors available, and you can also develop custom connectors for specific systems or requirements.</p><p><strong>Scalability: </strong>It can easily scale out to handle increasing data loads by adding more worker nodes. Connectors can also scale independently of each other.</p><h4>Advantages of Custom Consumer Producer Implementation</h4><p><strong>Flexibility</strong>: Kafka Connectors can be configured and custom connectors can be implemented. However, at its simplest, all the process is either producing or consuming something from Kafka. So, you can do anything a connector does using custom services. And, if you are implementing your own services, you have complete control.</p><p><strong>Performance</strong>: Flexibility brings performance since you can fine-tune your application’s performance for your specific use cases.</p><p><strong>Learning Curve</strong>: If you are not familiar with Kafka Connect, learning how to properly configure and use it may take some time.</p><p><strong>Not Relying On Third-Party Plugins</strong>: One of the biggest advantages of Kafka Connect is community support and plugins. However, these plugins may not fulfill your performance, resource usage, or security needs, and your project would depend on the bugs and updates of those plugins.</p><h3>Conclusion</h3><p>In this article, I tried to explore the advantages and features of Kafka and Kafka Connect. Kafka Connect, with its scalable and distributed nature, is a powerful tool seamlessly integrated within the Apache Kafka Ecosystem. So, it certainly worth to give a try to Kafka Connect. On the other hand, custom consumer and producer applications can be easily implemented and integrated with Kafka. Choosing between those two approaches depends on your specific needs. Thanks for reading so far. Hope to see you in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a5d24f5aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Batch Essentials: A Comprehensive Guide to Building and Integrating Batch Applications]]></title>
            <link>https://batuhanorhon.medium.com/spring-batch-essentials-a-comprehensive-guide-to-building-and-integrating-batch-applications-bbc5c575a018?source=rss-5c76bc2fd50f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc5c575a018</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-batch]]></category>
            <dc:creator><![CDATA[Batuhan Orhon]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 14:48:11 GMT</pubDate>
            <atom:updated>2023-12-14T14:48:11.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*G9ExnsfRspjHPUVu.png" /></figure><h3>What is Spring Batch? Exploring Its Core Features</h3><p>Spring Batch is a module of Spring Framework, designed to offer Java developers efficient data processing solutions. I won’t go into much detail about the technical capabilities of Spring Batch but try to mention its key features and implement a simple batch application to show how easy it is to start with.</p><p>Key features include:</p><ul><li><strong>Batch Processing Models</strong>: Spring Batch provides a robust and user-friendly design for developing batch applications. This design is not only easy to use but also highly reliable. As you delve deeper into Spring Batch, you’ll encounter concepts such as chunk-oriented processing, steps, jobs, flows, job repositories, and listeners. These elements are straightforward to learn and offer significant assistance to developers.</li><li><strong>Integration with Spring Framework:</strong> As a submodule of the Spring Framework, Spring Batch seamlessly integrates with it. This integration means that if you are already familiar with the Spring Framework and develop software using it, integrating batch applications into your web applications and learning Spring Batch from scratch should be a straightforward process.</li><li><strong>Efficiency and Performance: </strong>Spring Batch is optimized for processing large data sets, ensuring high performance in handling substantial volumes of data. Furthermore, it offers a range of scaling options to facilitate parallel processing of your data, enhancing efficiency in complex data operations.</li><li><strong>Customizability</strong>: Spring Batch provides extensive customization options for most of its components, allowing you to build highly flexible batch applications tailored to your specific use cases. This adaptability ensures that Spring Batch can meet diverse and unique requirements in various application scenarios.</li></ul><h3><strong>Why/When to use Spring Batch?</strong></h3><p>There are many alternatives to Spring Batch such as Apache Hadoop, Quartz, AWS Batch, etc. Spring Batch is good if you find the following considerations suitable for your case:</p><ul><li><strong>Familiarity with Spring Framework</strong>: If you are new to Spring Ecosystem, Spring Batch’s learning curve may be steep for you. However, if you are familiar with Spring, that case becomes an advantage.</li><li><strong>Use Cases and Scale</strong>: Spring Batch is often the preferred choice for processing small to medium-sized data sets. While it offers adequate scalability options, it may not be the optimal solution for the largest data sets, where other batch processing tools are specifically designed to excel. Additionally, for both performance and reliability, distributed batch processing solutions, with their stateful design, can often provide superior outcomes.</li><li><strong>Flexible Processing Patterns:</strong> The flexible and customizable nature of Spring Batch supports a wide range of processing patterns, from simple data migration to complex business logic. This flexibility makes it a versatile tool for various batch processing scenarios, not limited to specific types of tasks or industries.</li></ul><h3>Before We Start</h3><ul><li>I am going to implement a sample Spring Batch application step by step. You may follow the instructions to implement your own application with me, or find the final version of the application in <a href="https://github.com/BatuhanOrhon/SpringBatchDemoApp">this link</a>.</li><li>Before we dive in, if you’re new to Spring Batch, I highly recommend checking out <a href="https://docs.spring.io/spring-batch/reference/spring-batch-intro.html">this documentation</a> to acquaint yourself with some of the technical details (No need for a deep dive). This will make the learning process smoother and more enjoyable for you.</li></ul><h3>Starting with Spring Batch: A Step-by-Step Implementation Guide</h3><h4>Spring Initializr</h4><p>Let’s start with creating a project from this spring initializr <a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.2.0&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.demo&amp;artifactId=spring.batch.sample.app&amp;name=spring-batch-sample-app&amp;description=Demo%20project%20for%20Spring%20Batch&amp;packageName=com.demo.spring.batch.sample.app&amp;dependencies=batch">link</a>.</p><h4>Dependencies</h4><p>After generating the project using the Initializr, we need to add below h2 in-memory database dependency to give Spring Batch a <strong>job repository</strong>. Spring Batch forces us to use a job repository to save metadata of running jobs and steps into it. You can find detailed information about the job repositories in Spring Batch documents I have mentioned above.</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>      &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>      &lt;scope&gt;runtime&lt;/scope&gt;<br> &lt;/dependency&gt;</pre><h4>Code</h4><p>Chunk-oriented processing is a design to process data by partitions called chunks. It uses readers, processors, and writers to configure a step. Now, let’s create empty versions of these classes:</p><pre>package com.demo.springbatchsampleapp.batch;<br><br>import org.springframework.batch.item.ItemReader;<br>import org.springframework.batch.item.NonTransientResourceException;<br>import org.springframework.batch.item.ParseException;<br>import org.springframework.batch.item.UnexpectedInputException;<br><br>public class CustomItemReader implements ItemReader&lt;String&gt; {<br><br> @Override<br> public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {<br>  // TODO Auto-generated method stub<br>  return null;<br> }<br>}</pre><pre>package com.demo.springbatchsampleapp.batch;<br><br>import org.springframework.batch.item.ItemProcessor;<br><br>public class CustomItemProcessor implements ItemProcessor&lt;String, String&gt; {<br><br> @Override<br> public String process(String item) throws Exception {<br>  // TODO Auto-generated method stub<br>  return null;<br> }<br><br>}</pre><pre>package com.demo.springbatchsampleapp.batch;<br><br>import org.springframework.batch.item.Chunk;<br>import org.springframework.batch.item.ItemWriter;<br><br>public class CustomItemWriter implements ItemWriter&lt;String&gt; {<br><br> @Override<br> public void write(Chunk&lt;? extends String&gt; chunk) throws Exception {<br>  // TODO Auto-generated method stub<br><br> }<br><br>}</pre><p>Now, let’s create a configuration class to create necessary beans for job and step configurations.</p><pre>package com.demo.springbatchsampleapp.batch.conf;<br><br>import org.springframework.batch.core.Job;<br>import org.springframework.batch.core.Step;<br>import org.springframework.batch.core.job.builder.JobBuilder;<br>import org.springframework.batch.core.repository.JobRepository;<br>import org.springframework.batch.core.step.builder.StepBuilder;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.transaction.PlatformTransactionManager;<br><br>import com.demo.springbatchsampleapp.batch.CustomItemProcessor;<br>import com.demo.springbatchsampleapp.batch.CustomItemReader;<br>import com.demo.springbatchsampleapp.batch.CustomItemWriter;<br><br>@Configuration<br><br>public class BatchConfig {<br><br> @Bean<br> public CustomItemReader reader() {<br>  return new CustomItemReader();<br> }<br><br> @Bean<br> public CustomItemProcessor processor() {<br>  return new CustomItemProcessor();<br> }<br><br> @Bean<br> public CustomItemWriter writer() {<br>  return new CustomItemWriter();<br> }<br><br> @Bean<br> public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {<br>  return new StepBuilder(&quot;step1&quot;, jobRepository).&lt;String, String&gt;chunk(0, transactionManager).reader(reader())<br>    .processor(processor()).writer(writer()).build();<br> }<br><br> @Bean<br> public Job demoJob(JobRepository jobRepository) {<br>  return new JobBuilder(&quot;demoJob&quot;, jobRepository).flow(step1(null, null)).end().build();<br> }<br>}</pre><p>After these steps, if we run the application, an empty job will be run and complete as shown in the logs below:</p><pre>2023-12-12T17:35:25.121+03:00  INFO 15392 --- [           main] c.d.s.SpringBatchSampleAppApplication    : Starting SpringBatchSampleAppApplication using Java 17.0.2 with PID 15392 (C:\projects\spring-batch-sample-app\target\classes started by batuo in C:\projects\spring-batch-sample-app)<br>2023-12-12T17:35:25.123+03:00  INFO 15392 --- [           main] c.d.s.SpringBatchSampleAppApplication    : No active profile set, falling back to 1 default profile: &quot;default&quot;<br>2023-12-12T17:35:25.599+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari&#39; of type [org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.633+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties&#39; of type [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.634+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$PooledDataSourceConfiguration&#39; of type [org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$PooledDataSourceConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.635+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;jdbcConnectionDetails&#39; of type [org.springframework.boot.autoconfigure.jdbc.PropertiesJdbcConnectionDetails] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.689+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;dataSource&#39; of type [com.zaxxer.hikari.HikariDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.693+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$JdbcTransactionManagerConfiguration&#39; of type [org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$JdbcTransactionManagerConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.697+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizationAutoConfiguration&#39; of type [org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.702+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;transactionExecutionListeners&#39; of type [org.springframework.boot.autoconfigure.transaction.ExecutionListenersTransactionManagerCustomizer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.705+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;spring.transaction-org.springframework.boot.autoconfigure.transaction.TransactionProperties&#39; of type [org.springframework.boot.autoconfigure.transaction.TransactionProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.706+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;platformTransactionManagerCustomizers&#39; of type [org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.711+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;transactionManager&#39; of type [org.springframework.jdbc.support.JdbcTransactionManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.713+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;spring.batch-org.springframework.boot.autoconfigure.batch.BatchProperties&#39; of type [org.springframework.boot.autoconfigure.batch.BatchProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.<br>2023-12-12T17:35:25.719+03:00  WARN 15392 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean &#39;org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration$SpringBootBatchConfiguration&#39; of type [org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration$SpringBootBatchConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). The currently created BeanPostProcessor [jobRegistryBeanPostProcessor] is declared through a non-static factory method on that class; consider declaring it as static instead.<br>2023-12-12T17:35:25.743+03:00  INFO 15392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...<br>2023-12-12T17:35:25.900+03:00  INFO 15392 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:f944b20b-4f15-4b85-9491-2d23133ce134 user=SA<br>2023-12-12T17:35:25.901+03:00  INFO 15392 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.<br>2023-12-12T17:35:26.013+03:00  INFO 15392 --- [           main] o.s.b.c.step.builder.SimpleStepBuilder   : Setting commit interval to default value (1)<br>2023-12-12T17:35:26.137+03:00  INFO 15392 --- [           main] c.d.s.SpringBatchSampleAppApplication    : Started SpringBatchSampleAppApplication in 1.308 seconds (process running for 1.557)<br>2023-12-12T17:35:26.139+03:00  INFO 15392 --- [           main] o.s.b.a.b.JobLauncherApplicationRunner   : Running default command line with: []<br>2023-12-12T17:35:26.170+03:00  INFO 15392 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=demoJob]] launched with the following parameters: [{}]<br>2023-12-12T17:35:26.194+03:00  INFO 15392 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]<br>2023-12-12T17:35:26.206+03:00  INFO 15392 --- [           main] o.s.batch.core.step.AbstractStep         : Step: [step1] executed in 12ms<br>2023-12-12T17:35:26.214+03:00  INFO 15392 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=demoJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 28ms<br>2023-12-12T17:35:26.218+03:00  INFO 15392 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...<br>2023-12-12T17:35:26.220+03:00  INFO 15392 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.</pre><p>Well, this was our first empty batch application. Now, let’s modify our reader, processor, and writer classes to do simple operations on some list of strings.</p><p>I don’t want to add so many code blocks. Here is <a href="https://github.com/BatuhanOrhon/SpringBatchDemoApp/commit/0ed06cda804b496aadd40f8685cd0e6b5b89fe50">the commit to create a simple not empty job</a>. With given changes, reader will read a list and return elements one by one to the processor. Then processor will return the uppercase version of the string to the writer and all of them will print the item they got. So the logs of the batch job will be something like that:</p><pre>2023-12-13T11:23:47.521+03:00  INFO 9252 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=demoJob]] launched with the following parameters: [{}]<br>2023-12-13T11:23:47.544+03:00  INFO 9252 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]<br>2023-12-13T11:23:47.551+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word1<br>2023-12-13T11:23:47.553+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word1<br>2023-12-13T11:23:47.554+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD1<br>2023-12-13T11:23:47.555+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word2<br>2023-12-13T11:23:47.555+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word2<br>2023-12-13T11:23:47.555+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD2<br>2023-12-13T11:23:47.556+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word3<br>2023-12-13T11:23:47.556+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word3<br>2023-12-13T11:23:47.556+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD3<br>2023-12-13T11:23:47.557+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word4<br>2023-12-13T11:23:47.557+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word4<br>2023-12-13T11:23:47.557+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD4<br>2023-12-13T11:23:47.558+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word5<br>2023-12-13T11:23:47.558+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word5<br>2023-12-13T11:23:47.558+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD5<br>2023-12-13T11:23:47.559+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemReader             : Reading the next item from the list which is: word6<br>2023-12-13T11:23:47.559+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemProcessor          : Processing the item: word6<br>2023-12-13T11:23:47.559+03:00  INFO 9252 --- [           main] c.d.s.batch.CustomItemWriter             : Writing the item: WORD6<br>2023-12-13T11:23:47.562+03:00  INFO 9252 --- [           main] o.s.batch.core.step.AbstractStep         : Step: [step1] executed in 18ms<br>2023-12-13T11:23:47.568+03:00  INFO 9252 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=demoJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 34ms</pre><p>A little note, if you change the chunk size in the BatchConfiguration.java class, the job will process the input list not one by one but in parts. Give it a try.</p><h3>Running Your Spring Batch Application</h3><p>There are several ways to run a batch application. There is no correct way of doing so. You should choose the best approach based on your needs. Let’s examine some of them.</p><h4>Spring Scheduler</h4><p>We may simply use a “@Scheduled” annotation provided by Spring Framework to run jobs periodically at given specific time and dates. Using this approach is so easy. However, you should handle cases such as exceptions, notifications, running chained jobs, etc. yourself. In some businesses an unnoticed failed job may be a big problem. Check <a href="https://spring.io/guides/gs/scheduling-tasks/">this document</a> to learn more about Spring’s scheduler.</p><h4><strong>Using a Job Scheduling Tool</strong></h4><p>A job scheduling tool such as UC4 may also be used to schedule jobs. Such tools offer solutions for batch-specific problems I mentioned before. Yet, in that case you need to learn how to use such products too. Most of the big tech firms use such softwares to run and manage their batch applications.</p><h3>Integrating Spring Batch: Enhancing Your Web Applications</h3><p>Well, now that we know how to implement and run a job using Spring Batch, we should decide how we should deploy and run batch applications in a software environment.</p><p>At the company I work for, we usually develop web services using Spring Boot. However, any company that wants to process high volumes of data, might need to develop batch applications. Batches are essential to process large amounts of data on a scheduled basis (weekly, daily, etc.). Thus, my company also works with batch applications.</p><p>In the above sections, we analyzed the technical advantages of Spring Batch. Now, let’s investigate the problem of deploying batch applications from the perspective of a dev-ops engineer. As I mentioned, we mainly develop web services with Spring Boot, and our batch applications are related to those services. When a developer opens the repository of a web application, wouldn’t it be a good idea to also show him the related batch projects and their source codes, or maybe use common classes to keep web and batch applications integrated? Well, it depends :). Yet, in some cases, we decided that would be a pretty beneficial approach.</p><p>Have you ever heard of Maven archetypes? Here, <a href="https://maven.apache.org/guides/introduction/introduction-to-archetypes.html">check it.</a> We will use a custom archetype.</p><p><a href="https://github.com/BatuhanOrhon/Multi-Module-Sample-App">In this project</a>, I created a simple multi-module app to show you how to integrate a batch application with a web application. The idea is using a common parent pom, and using modules such as common-lib together. There are advantages and disadvantages of that approach.</p><h4>Advantages</h4><ul><li>Related Web and Batch applications are managed together, and changes in the common logic will reflect on both applications.</li><li>Batch and Web jars will be installed separately, they can be used on the same or different servers when needed.</li><li>Spring’s dependency injections may be used in common-lib classes.</li><li>Developers who are new to the project will see the whole logic when they investigate through the repository.</li><li>Using the same classes in different applications forces a solid software architecture.</li><li>You will have to keep maintaining and updating your batch services to keep them integrated with web applications. Note that most of the batch jobs don’t get renewed for years.</li></ul><h4>Disadvantages</h4><ul><li>This approach is not a good fit in a micro-service architecture since it violates some of its basic principles such as loose coupling.</li><li>Installing and running several jars from the same project and deploying them to different servers would require some extra work, if you don’t have such a design ready in your company.</li><li>Testing becomes more important in such a scenario. Because, when common-lib is changed both applications would be installed again and one may make sure changes for a service don’t corrupt the other. Better testing may also be considered as an advantage :).</li><li>Using the same classes in different applications brings the need for a more complex software architecture.</li></ul><h3>Conclusion</h3><p>Batch applications are essential for companies that process large amounts of data. Spring Batch is a good alternative as a batch processing framework. Solutions for deploying and running batch applications are at least as important as implementing them. Thank you for staying with me so far. Hope to see you in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc5c575a018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Spring Boot Actuator and Prometheus in Enhancing Service Monitoring]]></title>
            <link>https://batuhanorhon.medium.com/spring-boot-actuator-and-prometheus-with-an-example-application-90c88f7cc923?source=rss-5c76bc2fd50f------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c88f7cc923</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[spring-boot-actuator]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Batuhan Orhon]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 17:18:57 GMT</pubDate>
            <atom:updated>2023-11-07T17:22:10.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVbLYNWRyI1UUY36cnqQtg.png" /></figure><h4>What is Spring Boot Actuator &amp; Prometheus?</h4><p>Spring Boot Actuator is a powerful sub-module of Spring Boot designed for monitoring and managing your application. Let’s explore it alongside Prometheus, a monitoring solution that integrates smoothly with Spring Boot Actuator.</p><h4>Spring Initializr</h4><p>If you’re ready to dive into the practical aspects, you can initiate your project with Spring Initializr. For our example, we’ll use Java 17, Maven, and Eclipse. The Spring Boot version will be 3.1.3, with dependencies including Spring Web, Prometheus, and Actuator. You can generate a template for your project at Spring Initializr:</p><p><a href="https://start.spring.io/#!type=maven-project&amp;language=java&amp;platformVersion=3.1.3&amp;packaging=jar&amp;jvmVersion=17&amp;groupId=com.actuator.example&amp;artifactId=actuator-demo-app&amp;name=actuator-demo-app&amp;description=Demo%20project%20for%20Spring%20Boot&amp;packageName=com.actuator.example.actuator-demo-app&amp;dependencies=actuator,prometheus,web">Spring Initializr</a></p><h4>Github</h4><p>For those who would rather skip the setup process, the complete project is available on GitHub for cloning <a href="https://github.com/BatuhanOrhon/actuator-demo-app">here</a>.</p><h4>Starting the Application</h4><p>Now if you run the application in your IDE and send a get request to <a href="http://localhost:8080/actuator"><strong>localhost:8080/actuator</strong></a> you will see that Spring has already started the actuator and is providing health indicators via its endpoints.</p><p>Below is the response:</p><pre>{<br>    &quot;_links&quot;: {<br>        &quot;self&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;health-path&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/health/{*path}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;health&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/health&quot;,<br>            &quot;templated&quot;: false<br>        }<br>    }<br>}</pre><p>/actuator shows all open actuator endpoints including itself. There are several default actuator endpoints and they can be exposed by adding the configuration below in your application.properties file:</p><pre>management.endpoints.web.exposure.include= *</pre><p>Now, you’ll get a comprehensive list of endpoints when you make the same request:</p><pre>{<br>    &quot;_links&quot;: {<br>        &quot;self&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;beans&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/beans&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;caches-cache&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/caches/{cache}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;caches&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/caches&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;health&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/health&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;health-path&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/health/{*path}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;info&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/info&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;conditions&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/conditions&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;configprops&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/configprops&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;configprops-prefix&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/configprops/{prefix}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;env&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/env&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;env-toMatch&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/env/{toMatch}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;loggers&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/loggers&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;loggers-name&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/loggers/{name}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;heapdump&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/heapdump&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;threaddump&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/threaddump&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;prometheus&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/prometheus&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;metrics&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/metrics&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;metrics-requiredMetricName&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/metrics/{requiredMetricName}&quot;,<br>            &quot;templated&quot;: true<br>        },<br>        &quot;scheduledtasks&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/scheduledtasks&quot;,<br>            &quot;templated&quot;: false<br>        },<br>        &quot;mappings&quot;: {<br>            &quot;href&quot;: &quot;http://localhost:8080/actuator/mappings&quot;,<br>            &quot;templated&quot;: false<br>        }<br>    }<br>}</pre><p>As you can see, the actuator provides numerous endpoints right out of the box. Reviewing each individually would be quite time-consuming, so I’ll focus on examining and configuring the actuator/health endpoint, which is crucial for determining the health status of the application.</p><p>Here is the response of <strong>actuator/health</strong> endpoint:</p><pre>{<br>    &quot;status&quot;: &quot;UP&quot;<br>}</pre><p>That response indicates that our application is healthy. The health endpoint determines the operational status of an application using various health indicators. Spring Boot Actuator offers several built-in indicators, and we also have the ability to define custom health indicators. These custom indicators can be used in conjunction with those provided by the Actuator. Next, I will demonstrate how to create a custom health indicator. But before that, let’s configure the health endpoint to display detailed health indicators along with the overall status.</p><p>Let’s open the application.properties file and add the following property:</p><pre>management.endpoint.health.show-details = &quot;always&quot;</pre><p>Now if we restart the application and send the get request to <a href="http://localhost:8080/actuator">localhost:8080/actuator</a> again, we will see the response below:</p><pre>{<br>    &quot;status&quot;: &quot;UP&quot;,<br>    &quot;components&quot;: {<br>        &quot;diskSpace&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;,<br>            &quot;details&quot;: {<br>                &quot;total&quot;: 499460935680,<br>                &quot;free&quot;: 30051192832,<br>                &quot;threshold&quot;: 10485760,<br>                &quot;path&quot;: &quot;C:\\projects\\actuator-demo-app\\.&quot;,<br>                &quot;exists&quot;: true<br>            }<br>        },<br>        &quot;ping&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;<br>        }<br>    }<br>}</pre><p>Perhaps now the function of health indicators becomes more apparent. In the given response, we observe two default health indicators provided by Spring Boot Actuator: one for ping and another for disk space. If either of these indicators were to report a status of ‘DOWN,’ then the overall health status of the application would similarly be marked as ‘DOWN’.</p><h4>Custom Health Indicators</h4><p>The Actuator sub-module comes equipped with a wealth of default health indicators, including ping, disk space, and database validation, the latter of which is automatically added to the health endpoint if a datasource is present. Nevertheless, there are scenarios where an application’s health may hinge on the status of an external service. For such instances, Spring Boot facilitates the straightforward creation of custom health indicators.</p><p>Here is an example custom health indicator class:</p><pre>import org.springframework.boot.actuate.health.Health;<br>import org.springframework.boot.actuate.health.HealthIndicator;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class CustomHealthIndicator implements HealthIndicator {<br><br> @Override<br> public Health health() {<br>  return Health.down().withDetail(&quot;External Service&quot;, &quot;DOWN&quot;).build();<br> }<br>}</pre><p>Now if we restart the application again and make sure CustomHealthIndicator component is running, then the response of actuator/health endpoint will become:</p><pre>{<br>    &quot;status&quot;: &quot;DOWN&quot;,<br>    &quot;components&quot;: {<br>        &quot;custom&quot;: {<br>            &quot;status&quot;: &quot;DOWN&quot;,<br>            &quot;details&quot;: {<br>                &quot;External Service&quot;: &quot;DOWN&quot;<br>            }<br>        },<br>        &quot;diskSpace&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;,<br>            &quot;details&quot;: {<br>                &quot;total&quot;: 499460935680,<br>                &quot;free&quot;: 32768573440,<br>                &quot;threshold&quot;: 10485760,<br>                &quot;path&quot;: &quot;C:\\projects\\actuator-demo-app\\.&quot;,<br>                &quot;exists&quot;: true<br>            }<br>        },<br>        &quot;ping&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;<br>        }<br>    }<br>}</pre><p>As demonstrated, we’ve successfully integrated a custom health indicator. Given that the status of this indicator is ‘DOWN’, it has caused the overall status to reflect the same, leading to our application being deemed unhealthy.</p><h4>Configuration Examples</h4><p>Endpoints exposed by actuator sub-module are easy to customize. Let me try to show some configurations to change endpoint behaviors.</p><p>With the below property, we can change the actuator prefix that we use to access endpoints from actuator/health to actuator_demo/health.</p><pre>management.endpoints.web.base-path = /actuator_demo</pre><p>Similarly, we can also change the name of the health endpoint to my_health by using the property below:</p><pre>management.endpoints.web.path_mapping.health = my_health</pre><p>We can create health indicator groups:</p><pre>management.endpoint.health.group.first_group.include = ping, diskSpace<br>management.endpoint.health.group.second_group.include = custom</pre><p>Here are the response values of <a href="http://localhost:8080/actuator/health/first_group">localhost:8080/actuator/health/first_group</a> and <a href="http://localhost:8080/actuator/health/second_group">localhost:8080/actuator/health/second_group</a> respectively:</p><pre>{<br>    &quot;status&quot;: &quot;UP&quot;,<br>    &quot;components&quot;: {<br>        &quot;diskSpace&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;,<br>            &quot;details&quot;: {<br>                &quot;total&quot;: 499460935680,<br>                &quot;free&quot;: 29814325248,<br>                &quot;threshold&quot;: 10485760,<br>                &quot;path&quot;: &quot;C:\\projects\\actuator-demo-app\\.&quot;,<br>                &quot;exists&quot;: true<br>            }<br>        },<br>        &quot;ping&quot;: {<br>            &quot;status&quot;: &quot;UP&quot;<br>        }<br>    }<br>}</pre><pre>{<br>    &quot;status&quot;: &quot;DOWN&quot;,<br>    &quot;components&quot;: {<br>        &quot;custom&quot;: {<br>            &quot;status&quot;: &quot;DOWN&quot;,<br>            &quot;details&quot;: {<br>                &quot;External Service&quot;: &quot;DOWN&quot;<br>            }<br>        }<br>    }<br>}</pre><p>So, the examples above are some configuration options. Yet, there are lots of other options to customize endpoints and actuator behavior. You may find them in Spring Boot Actuator documents.</p><h4>More Details About Spring Boot Actuator</h4><p>So far, we have discussed the actuator/health endpoint and health indicators, as well as their importance in monitoring an application. However, Spring Boot Actuator has much more to offer, and you can find detailed information in <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html"><strong>this document</strong></a>.</p><h4>Prometheus</h4><p>In this section, we will install and run a Prometheus server. Prometheus servers are used to collect metrics from applications and display them on their user interface. In the previous sections, we added the Prometheus dependency to our project while generating it using Spring Initializr.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>   &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br> &lt;/dependency&gt;</pre><p>When we add this dependency, Micrometer will generate some metric logs and feed them to Actuator. Then, Actuator will expose those logs at the /actuator/prometheus endpoint. Let&#39;s see the response from the Prometheus endpoint by sending a GET request to <a href="http://localhost:8080/actuator/prometheus">localhost:8080/actuator/prometheus</a> .</p><pre># HELP jvm_compilation_time_ms_total The approximate accumulated elapsed time spent in compilation<br># TYPE jvm_compilation_time_ms_total counter<br>jvm_compilation_time_ms_total{compiler=&quot;HotSpot 64-Bit Tiered Compilers&quot;,} 6763.0<br># HELP process_uptime_seconds The uptime of the Java virtual machine<br># TYPE process_uptime_seconds gauge<br>process_uptime_seconds 994.222<br># HELP jvm_threads_peak_threads The peak live thread count since the Java virtual machine started or peak was reset<br># TYPE jvm_threads_peak_threads gauge<br>jvm_threads_peak_threads 22.0<br># HELP executor_queued_tasks The approximate number of tasks that are queued for execution<br># TYPE executor_queued_tasks gauge<br>executor_queued_tasks{name=&quot;applicationTaskExecutor&quot;,} 0.0<br>.<br>.<br>.<br>.<br>.<br>.<br></pre><p>Since the response is quite long, I have included only part of it above. Basically, the response includes default application metric logs recorded by Micrometer, and Spring Boot. We can integrate our custom metrics within the code, but first, let’s start a Prometheus server and monitor our application.”</p><h4>How To Install And Run Prometheus</h4><p>To install and run Prometheus, I followed <a href="https://prometheus.io/docs/prometheus/latest/getting_started/">these</a> instructions up to title <strong>Getting Started</strong>. After that, I updated the prometheus.yml file inside the directory as below:</p><pre># my global config<br>global:<br>  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.<br>  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.<br>  # scrape_timeout is set to the global default (10s).<br><br># Alertmanager configuration<br>alerting:<br>  alertmanagers:<br>    - static_configs:<br>        - targets:<br>          # - alertmanager:9093<br><br># Load rules once and periodically evaluate them according to the global &#39;evaluation_interval&#39;.<br>rule_files:<br>  # - &quot;first_rules.yml&quot;<br>  # - &quot;second_rules.yml&quot;<br><br># A scrape configuration containing exactly one endpoint to scrape:<br># Here it&#39;s Prometheus itself.<br>scrape_configs:<br>  # The job name is added as a label `job=&lt;job_name&gt;` to any timeseries scraped from this config.<br>  - job_name: &quot;prometheus&quot;<br><br>    # metrics_path defaults to &#39;/metrics&#39;<br>    # scheme defaults to &#39;http&#39;.<br><br>    static_configs:<br>      - targets: [&quot;localhost:9090&quot;]<br><br>  - job_name: &quot;actuator-demo-app&quot;<br>    metrics_path: &quot;/actuator/prometheus&quot;<br>    # metrics_path defaults to &#39;/metrics&#39;<br>    # scheme defaults to &#39;http&#39;.<br>    scrape_interval: 30s<br>    static_configs:<br>      - targets: [&quot;localhost:8080&quot;]</pre><p>Now, let’s start the Prometheus server with the below command (inside the Prometheus folder we downloaded) and open <a href="http://localhost:9090/">localhost:9090</a> in our browser to have a look at its interface.</p><pre>prometheus --config.file=prometheus.yml</pre><figure><img alt="Prometheus UI" src="https://cdn-images-1.medium.com/max/1024/1*8LDF9GGxYD3M_7pvKldE_g.png" /><figcaption>Prometheus UI</figcaption></figure><p>Now, let’s open the graph view by clicking the graph button shown above. Then, type system_cpu_usage on the search bar and execute. Here is my output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NwsJuWlcCC8C8eTgITlew.png" /></figure><p>Excellent, we have now monitored our application’s metrics with remarkable speed. Beyond metrics like system_cpu_usage available at the actuator/prometheus endpoint, there&#39;s an even more significant aspect to consider: connecting to a Spring Datasource or exposing a REST service in your Spring Boot application automatically enriches the Prometheus endpoint with specific metrics for these operations. Let’s proceed by connecting to a database and implementing a REST service to observe the new metrics. First, we need to include these two dependencies in our pom.xml to establish a database connection:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>   &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Additionally, I’ve added Lombok dependency below to make my code cleaner with getter-setter annotations:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;scope&gt;provided&lt;/scope&gt;<br>  &lt;/dependency&gt;</pre><p>Lastly, I add h2 database configurations to my application.properties file:</p><pre>spring.datasource.url=jdbc:h2:mem:testdb<br>spring.datasource.driverClassName=org.h2.Driver<br>spring.datasource.username=sa<br>spring.datasource.password=password<br>spring.jpa.database-platform=org.hibernate.dialect.H2Dialect</pre><p>I won’t delve into the details of the code changes. In essence, I implemented three REST endpoints: /hello, which returns &#39;Hello world!&#39;; /createUser, which inserts an ActuatorUser entity into the H2 database; and /findUser, which retrieves ActuatorUser entities from the database by their ID. I integrated these endpoints into my application to demonstrate Prometheus&#39; automatic capture of REST endpoint and repository metrics.</p><p>If you’re interested in the specific code changes, you can refer to <a href="https://github.com/BatuhanOrhon/actuator-demo-app/pull/1/commits/60d7f6e1377e12eb66c5faa8fda39d0c755a5249"><strong>this</strong></a><strong> </strong>commit.</p><p>Now, I will call each endpoint several times, and then I will show some new metrics added to the Prometheus logs by Spring Boot.</p><p>In the image below you can see the count of the HTTP requests sent to our application. As you can see, each endpoint has its own metrics with details such as the status code, HTTP method, and even the exception class if there is any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4gJ4WQZGHg0xUueEjnqIQ.png" /></figure><p>As I said, repository metrics are also added to the logs automatically by Spring Data JPA. Here are the metrics of the repository invocations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QgIHtlZ1z6qUq56vtHALQ.png" /></figure><p>By using PromSQL, we can filter metrics and create custom visuals. Here is a simple example in which count of repository invocations that use the “findById” method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7osOF4_VrEoOFK9f9v5_Q.png" /></figure><p>PromSQL has many features and is easy to learn. For more detail about it you may check <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/">this</a> link.</p><h4>Business Case</h4><p>We have been exploring how to operate a Prometheus server and monitor metrics utilizing the capabilities of Spring Boot Actuator and Micrometer frameworks. Now, let’s delve into the impact these technologies have in a practical software environment.</p><p>The core purpose of integrating these frameworks is to enhance our service monitoring and enable informed actions based on application metrics. In my company, we recognized the need to establish actuator endpoints for detailed application monitoring, enables us to take both manual and automated actions based on real-time metrics. While we had robust monitoring systems in place, primarily leveraging API Gateway traffic logs and server pings for service availability, Spring Boot Actuator and Prometheus have taken us a step further. They empower us with the ability to harness application-generated metrics and create custom health indicators on the fly.</p><p>Consider a scenario where your company employs load balancer technologies to distribute service traffic. These technologies could be configured to cease routing requests to a service if certain metrics or health indicators fall outside acceptable ranges. For instance, traffic could be halted if the CPU usage of a service exceeds a predetermined threshold or if a service is unresponsive due to memory or disk space constraints. Load balancers typically possess filtering capabilities, and we’ve configured ours to stop directing traffic to servers whenever the load balancer’s health check endpoint returns a status other than “UP”.</p><p>Recall the configuration we implemented to establish health groups? Here is a reminder:</p><pre>management.endpoint.health.group.first_group.include = ping, diskSpace<br>management.endpoint.health.group.second_group.include = custom</pre><p>Now, let’s change group names to make them mean something:</p><pre>management.endpoint.health.group.loadbalancer.include = ping, diskSpace<br>management.endpoint.health.group.monitor.include = custom, db, kafka</pre><p>I have also added db and kafka health indicators which could be provided by frameworks or implemented manually, as demonstrated earlier.</p><p>You may wonder why we didn’t just combine all the checks into one health endpoint and use it for traffic management. In our scenario, we wanted to differentiate the endpoints. We believe that a load balancer should only cut off traffic to a web server if the server itself is unable to respond. If external services are down, the application should continue to serve and handle the situation independently. On the other hand, the monitoring endpoint is intended to verify the application’s ability to access external services and to alert the monitoring and development teams if there are connectivity issues. This is how we designed our system. Of course, as conditions change, there may be more effective ways to design such a system.</p><p>Integrating Prometheus with Grafana is quite straightforward. Although Prometheus offers a solid visual interface, it’s quite basic compared to Grafana. Grafana can be used to create more complex and informative visualizations from metrics gathered by Prometheus servers. Additionally, both Grafana and Prometheus come equipped with alert and notification features, which are user-friendly and simple to set up.</p><h4>Conclusion</h4><p>Today, we delved into the capabilities of Spring Boot Actuator and Prometheus, illustrating their practical applications through a real-world use case. For more detailed information, please visit the respective websites of these products:</p><ul><li><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html"></a></li><li><a href="https://prometheus.io/">Prometheus - Monitoring system &amp; time series database</a></li></ul><p>Thank you for staying with me so far. I look forward to connecting with you in a future article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c88f7cc923" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week6 — Artificial Pianist]]></title>
            <link>https://medium.com/bbm406-spring-2021-projects/week6-artificial-pianist-2a932493a860?source=rss-5c76bc2fd50f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a932493a860</guid>
            <dc:creator><![CDATA[Batuhan Orhon]]></dc:creator>
            <pubDate>Mon, 24 May 2021 05:33:10 GMT</pubDate>
            <atom:updated>2021-05-24T05:33:10.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Week 6 — Artificial Pianist</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ldU_BW8HqKfmZLrC.jpg" /></figure><h3>How to generate random music?</h3><p>After completing the training phase, we have got the trained model. We have generated different piano music by using the same trained model. In this title, we have explained how to produce varied music by using the same model. First of all, we have initialized the initial notes that are forty-nine empty notes following one random note. After that, we have calculated the probability of each following note by using these initial notes and trained model. By using this “NumPy.random” library, we have determined the next note by considering their weights. Next phase, we have taken again fifty note but we have updated the initial notes by removing the first element. Thereafter, we have applied the same operation until the maximum number of the notes of the piano music. Then, we have dropped the first fifty notes and the piano notes are ready for the creation of the “midi” file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*elSen3zbucs_ai_J.png" /><figcaption><a href="https://towardsdatascience.com/generate-piano-instrumental-music-by-using-deep-learning-80ac35cdbd2e">https://towardsdatascience.com/generate-piano-instrumental-music-by-using-deep-learning-80ac35cdbd2e</a></figcaption></figure><h3>Model Improvement</h3><p>In the last week, we mentioned that we are not so happy about the results of our first implementation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qnB4xmVBu4VzwRUr.jpg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F495958977706749101%2F&amp;psig=AOvVaw32Mu2EtzAVuF_d8gA2HKUV&amp;ust=1621883393399000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCNCPn9HA4PACFQAAAAAdAAAAABAE">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F495958977706749101%2F&amp;psig=AOvVaw32Mu2EtzAVuF_d8gA2HKUV&amp;ust=1621883393399000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCNCPn9HA4PACFQAAAAAdAAAAABAE</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1049890384%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Foezge-koekyay%2Fartificial-pianist-1&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-to6nKXCwa3AG8yEZ-QfnMAg-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f625486a02d01fc6cd203d4fe4981e2/href">https://medium.com/media/6f625486a02d01fc6cd203d4fe4981e2/href</a></iframe><p>After that, we decided to change some hyperparameters such as epoch, frequency, batch size of the same model. Again, we didn’t get theresults we want. Here is an example result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1054131463%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-1&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/590899b799d1c42789286680585f1725/href">https://medium.com/media/590899b799d1c42789286680585f1725/href</a></iframe><p>So, we decided to change our model, and implemented a similar model with transformers. While processing we also realized that if we train the model songs with similar styles, results get better. Here are some results :</p><p>Note: This one is my favorite…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1051962220%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-13&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b99b6ba1e1362fa88ad50171d8206b/href">https://medium.com/media/c5b99b6ba1e1362fa88ad50171d8206b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1051964269%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-24&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e5c69dc790029c136c2fc45f4555850/href">https://medium.com/media/2e5c69dc790029c136c2fc45f4555850/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1051963093%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-33&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf360106640eea8564c5fd1406cac92a/href">https://medium.com/media/cf360106640eea8564c5fd1406cac92a/href</a></iframe><p>At this point, our teaching assistant suggested us to use dropout layers between the transformers and that improved our results more than expected.</p><p>Here are some results of our last model:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1054168405%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-58&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7d2258803589373180a9c04756ae5c/href">https://medium.com/media/3d7d2258803589373180a9c04756ae5c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1054167454%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-55&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c1c14e68280b8fafe8c2802b5518a11/href">https://medium.com/media/9c1c14e68280b8fafe8c2802b5518a11/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1054170106%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-63&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a378d3f18b65fc0ba609d525d715efa/href">https://medium.com/media/4a378d3f18b65fc0ba609d525d715efa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1054169410%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fbatuhan-orhon%2Fone-note-53&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9239e85fae965e9544b7957f637c812/href">https://medium.com/media/a9239e85fae965e9544b7957f637c812/href</a></iframe><p>We hope you enjoyed :)</p><h3>Project Team</h3><p><a href="https://medium.com/u/5c76bc2fd50f">Batuhan Orhon</a></p><p><a href="https://medium.com/u/b1607eee975a">Batuhan Ayvaz</a></p><p><a href="https://medium.com/u/2b32193ac678">Özge Kökyay</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a932493a860" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bbm406-spring-2021-projects/week6-artificial-pianist-2a932493a860">Week6 — Artificial Pianist</a> was originally published in <a href="https://medium.com/bbm406-spring-2021-projects">BBM406 Spring 2021 Projects</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week 1 — Introducing Our Project : The Artificial Pianist]]></title>
            <link>https://batuhanorhon.medium.com/week-1-introducing-our-project-the-artificial-pianist-a5406940c6a?source=rss-5c76bc2fd50f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5406940c6a</guid>
            <dc:creator><![CDATA[Batuhan Orhon]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 15:09:10 GMT</pubDate>
            <atom:updated>2021-04-11T15:10:46.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Week 1 — Introducing Our Project : The Artificial Pianist</h3><h3>- Project Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CcUEnqb0ezBCLQOlEDrSZQ.jpeg" /><figcaption><a href="https://www.freepik.com/premium-vector/pianist-robot-hand-with-piano-key-from-pixel-background-concept-artificial-intelligence-music-compose_8501192.htm">https://www.freepik.com/premium-vector/pianist-robot-hand-with-piano-key-from-pixel-background-concept-artificial-intelligence-music-compose_8501192.htm</a></figcaption></figure><p>In this project, we are going to implement a deep learning model which trains some given midi files and creates its own song. Some authorities think that in the future most of the musicians are going to use that kind of AI tools to produce their art. AI Pianist is a deep learning project which processes given audio data and learns a model based on the data. After that, AI Pianist produces its own series of notes (new song). Another feature that makes AI pianist interesting is that, when it is given a part of a song, let’s say the first two minutes of a three minutes long song, it can complete the rest of the song by himself based on the model it learned.</p><h3>- Implementation Plan</h3><p>At the start, we need to decide how are we going to process audio. Midi files seem desirable to use in such a project. So, we found a midi file dataset “The Maestro”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dlyUZyEm1UKjGvCC.png" /><figcaption><a href="https://magenta.tensorflow.org/assets/magenta-logo-card.jpg">magenta-logo-card.jpg (1140×600) (tensorflow.org)</a></figcaption></figure><p>Check -&gt;<a href="https://magenta.tensorflow.org/datasets/maestro">The MAESTRO Dataset (tensorflow.org)</a></p><p>Pretty_midi library seems usable for the audio processing. Format of a midifile for the pretty_midi library is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*5BkNYEYv1HW2apmU.png" /><figcaption><a href="https://towardsdatascience.com/generate-piano-instrumental-music-by-using-deep-learning-80ac35cdbd2e">Generate Piano Instrumental Music by Using Deep Learning | by Haryo Akbarianto Wibowo | Towards Data Science</a></figcaption></figure><p>In pretty_midi library there are some specific functions for the piano instrument and they are also going to be useful in the next phases of the project.</p><h3>- Topics we are going to cover in next week</h3><ul><li>Technical details of preprocessing?(Data Structures, Data Framework, etc.)</li><li>Which deep learning model to choose for the base?</li><li>Which additional features we are going to implement?</li></ul><h3>Stay Tuned!</h3><p>Project Member</p><ul><li><a href="https://medium.com/u/b1607eee975a">Batuhan Ayvaz</a></li><li><a href="https://medium.com/u/2b32193ac678">/özge kökyay</a></li><li><a href="https://medium.com/u/5c76bc2fd50f">Batuhan Orhon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5406940c6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>