<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://digitalyogi.tech/feed.xml" rel="self" type="application/atom+xml" /><link href="https://digitalyogi.tech/" rel="alternate" type="text/html" /><updated>2026-11-19T18:41:57+00:00</updated><id>https://digitalyogi.tech/feed.xml</id><title type="html">DigitalYogi</title><subtitle>Simple, short tutorials in Java, Spring Boot, microservices and AI. Courses on DigitalYogi Learn and practice in KB.</subtitle><entry><title type="html">Kafka Stream with Custom Objects</title><link href="https://digitalyogi.tech/2020/03/10/spring-kafka-stream-with-custom-object/" rel="alternate" type="text/html" title="Kafka Stream with Custom Objects" /><published>2020-03-10T08:01:11+00:00</published><updated>2020-03-10T08:01:11+00:00</updated><id>https://digitalyogi.tech/2020/03/10/spring-kafka-stream-with-custom-object</id><content type="html" xml:base="https://digitalyogi.tech/2020/03/10/spring-kafka-stream-with-custom-object/"><![CDATA[<p>Kafka is most sought after event system today. In this series we will look at Kafka event messaging and streaming.</p>

<p>Github Repository link : https://github.com/CODINGSAINT/kafka-stream-spring</p>

<h5 id="what-will-we-be-creating">What will we be creating</h5>

<p>We will create a streaming application using Spring and kafka streams.
 We will have a continuously coming stream of famous quotes which will be continously produced at <code class="language-plaintext highlighter-rouge">quote</code> topic.  Every quote can be tagged with multiple categories i.e. <code class="language-plaintext highlighter-rouge">business,education,faith,famous-quotes,friendship,future,happiness,inspirational,life,love,nature,politics,proverb,religion,science,success,technology</code> .
 We will have topics related to each of the category. Once a quote comes we will be streaming them to respective category. To keep things simple for demo we have one listener listening to all of the topics
 We have taken quotes from <a href="https://github.com/lukePeavey/quotable/blob/master/data/sample/quotes.json">https://github.com/lukePeavey/quotable/blob/master/data/sample/quotes.json</a></p>

<p>These quotes will be streamed and will be sent to respective topic based on their category.
Listener will keep track of all the quotes which are streamed to these topics.</p>

<p>.</p>

<h3 id="installing-kafka">Installing kafka</h3>

<h4 id="download">Download</h4>

<p>To start kafka we require zookeeper , on kafka website we have different versions you can get the latest stable vesion from <a href="https://kafka.apache.org/downloads">Kafka download page</a> Say you have downloaded  <a href="http://mirrors.estointernet.in/apache/kafka/2.4.0/kafka_2.11-2.4.0.tgz"><strong>kafka_2.11-2.4.0.tgz</strong></a></p>

<p><code class="language-plaintext highlighter-rouge">wget http://mirrors.estointernet.in/apache/kafka/2.4.0/kafka_2.11-2.4.0.tgz</code></p>
<h4 id="unzip">Unzip</h4>
<p>Use below command to unzip the downloaded file <code class="language-plaintext highlighter-rouge">tar xzf kafka_2.11-2.4.0.tgz</code>
 ### Move to user directory Move content to user directory  <br />
<code class="language-plaintext highlighter-rouge">mv kafka_2.11-2.4.0/* /usr/local/kafka</code>
 ### Run Zookeeper
  Go to kafka directory and run  <br />
<code class="language-plaintext highlighter-rouge">cd /usr/local/kafka bin/zookeeper-server-start.sh config/zookeeper.properties</code> ### Run Kafka Server Use below command to run kafka server  <br />
<code class="language-plaintext highlighter-rouge">bin/kafka-server-start.sh config/server.properties</code> You will see logs confirming the kafka is up an running.</p>
<h4 id="test-kafka-installation">Test kafka installation</h4>
<p>##### Create a topic
  <code class="language-plaintext highlighter-rouge">   
 bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic kafka-test-topic    
</code></p>
<h5 id="verify-if-topic-got-created">Verify if topic got created</h5>

<p>bin/kafka-topics.sh –list –zookeeper localhost:2181 kafka-test-topic
 ##### Send messages to topic  <br />
Use below command to activate message terminal to kafka-test-topic. Below command will activate message sending to a topic , key in some interesting messages. Lets call it producer window</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic kafka-test-topic &gt;Welcome to Kafka
</code></pre></div></div>

<h5 id="consume-the-topic-open-another-terminal-to-consume-messages">Consume the topic Open another terminal to consume messages</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic kafka-test-topic --from-beginning    
</code></pre></div></div>

<p>Now whatever you key in to producer window will be consumed to consumer window</p>
<h5 id="other-ways-to-install-kafka">Other ways to install kafka</h5>
<p>There could be many other ways to install and run like using apt installer on Ubuntu , using a docker image etc. The above one is a generic setup .</p>
<h4 id="create-topics-for-for-app">Create Topics for for app</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic quotes  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic business  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic education  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic faith  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic famous-quotes  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic famous-quotes  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic friendship  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic future  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic happiness  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic inspirational  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic life  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic love  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic nature  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic politics  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic proverb  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic religion  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic science  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic success  
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic technology  
</code></pre></div></div>

<h4 id="creating-spring-boot-kafka-stream-project">Creating Spring Boot Kafka Stream project</h4>
<p>We will create project using https://start.spring.io .
Go to website and dependencies</p>

<p><img src="https://lh3.googleusercontent.com/_X8RJU5IQE1LUUONCukFpCfnANN6HmH3gsVnzirWd74nmWCNluCtMx66uekRE9I1cdYU28jgDjXdbtBNLCOfUMHdxjlZLoIa6gHn5d2pMDjqRJPN9ep4TK9bHdoFaO53M-X5VffpbYz6u1GXh2sLiAmkzAvXvIfs7-to1buqdwascl3WNQzkZ023ygtUVM6avXqr_hXJM9REiOteI-RYIFN-e4XVT9ghfqJBfrEGv7KtARU7NH_EVt2-Lrb8JzeLRGn_2wyaySSC-Anbv11PhW34obCiUE_ws90pCq48v9N6N0upNnYU_PEtW193dXJX3cZLVjmfMrpr9yc8YT_0x6HqNK6qJfoylhoc91hwgJqeecoDCHNRLI2C2mAVOZpunkAJQO_JcibsCLkUlMoahWF41TrJE3j6DPsd-yOHesel-dK_Ngc2Xt5IZu8coWWdZM_BGfWTxMm5e8MIZrDq74AJOEvzFhDeByFH4cOOdqkSooi1-Jqgh_fIumaags3NMNYjtTKAEeRjFVr_Gaa6l37qr8Iaepm8rIRfVlBz3A-HXqOa5KCJ5JAtf8cqc8yOgQlkYC6arT4GsmUsSjOjlxp5e86k65B1z1kDK79Ct4jQBj5DdPNiuL5HnxLZ0EIkGSwqK5EEPEob8ObLeH0noyiBd_5reWwqFMqCPdTX_MVu2DJLXsoha8bpkLqTOxoYsWLmTA3gy80kFV6CcB-9S-uWuabrvL1HK-wIJSUDzipkrgTh=w1190-h669-no" alt="Spring Boot Kafka Stream dependencies" /></p>

<p>Download the project and open in your favourite IDE and open it.
Now we have Kafka installed up and running , as a First step we should be creating Quote bean which will flow the quotes from producer to consumer.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@Getter
@Setter
@ToString
public class Quote {
private String content;
private Set&lt;String&gt; tags;
private String author;
}
</code></pre></div></div>

<p>Let’s add required configurations for  Kafka. This includes Serializer and Deserializer
for Quotes.We have configurations for Spring Kafka template , producer and consumer.
Serialization and Deserialiation for key and value objects(POJO) have been mentioned seperately.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spring:
  kafka:
    listener:
      missing-topics-fatal: false
    client-id : quotes-app
    bootstrap-server:
      - localhost:9091
      - localhost:9001
      - localhost:9092
    template:
      default-topic: quotes
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: com.codingsaint.learning.kafkastreamspring.QuoteSerializer
    consumer:
      properties:
        partition:
          assignment:
            strategy: org.apache.kafka.clients.consumer.RoundRobinAssignor
      group-id: random-consumer
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: com.codingsaint.learning.kafkastreamspring.QuoteDeserializer
---
kafka:
  topic:
    input: quotes
    output: business,education,faith,famous-quotes,friendship,future,happiness,inspirational,life,love,nature,politics,proverb,religion,science,success,technology
</code></pre></div></div>

<p>We will create  QuoteSerializer , QuoteDeserializer and QuoteSerde which will have both serializer and deserializer
.We are using simple ObjectMapper to serialize and deserialize</p>

<h5 id="quoteserializer">QuoteSerializer</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public class QuoteSerializer implements Serializer&lt;Quote&gt; {

    @Override
    public byte[] serialize(String s, Quote quote) {
        byte[] retVal = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            retVal = objectMapper.writeValueAsString(quote).getBytes();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retVal;
    }
}
</code></pre></div></div>

<h5 id="quotedeserializer">QuoteDeserializer</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public class QuoteDeserializer implements Deserializer&lt;Quote&gt; {

    @Override
    public Quote deserialize(String s, byte[] bytes) {
        ObjectMapper mapper = new ObjectMapper();
        Quote quote = null;
        try {
            quote = mapper.readValue(bytes, Quote.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return quote;
    }

}
</code></pre></div></div>

<h5 id="quoteserde">QuoteSerde</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public class QuoteSerde implements Serde&lt;Quote&gt; {
    public QuoteSerde() {
    }

    @Override
    public Serializer&lt;Quote&gt; serializer() {
        return new QuoteSerializer();
    }

    @Override
    public Deserializer&lt;Quote&gt; deserializer() {
        return new QuoteDeserializer();
    }
}
</code></pre></div></div>

<p>Now Let us see the AppConfig class for configuring Producer and Consumer configurations.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@Configuration
@EnableKafka
@EnableKafkaStreams
public class AppConfig {
    private static final Logger LOGGER= LoggerFactory.getLogger(AppConfig.class);

    @Value("${kafka.topic.input}")
    private String inputTopic;

    @Value("#{'${kafka.topic.output}'.split(',')}")
    private List&lt;String&gt; allTopics;


    @Autowired
    private KafkaProperties kafkaProperties;

    /**
     * Configurations for KafkaStreams
     * @param kafkaProperties Will take defaults from application YAML or Properties file with spring.kafka
     * @return kafkaConfiguration
     */
    @Bean(name= KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
    public KafkaStreamsConfiguration kafkaConfiguration(final KafkaProperties kafkaProperties){
        Map&lt;String, Object&gt; config = new HashMap&lt;&gt;();
        config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
        config.put(StreamsConfig.APPLICATION_ID_CONFIG, kafkaProperties.getClientId());
        config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, QuoteSerde.class.getName() );
        config.put(StreamsConfig.DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG, LogAndContinueExceptionHandler.class);
        return new KafkaStreamsConfiguration(config);
    }

    /**
     * The Stream which delegates each incoming topic to respective destination topic
     * @param kStreamsBuilder
     * @return
     */
    @Bean
    public KStream&lt;String,Quote&gt; kStream(StreamsBuilder kStreamsBuilder){
        KStream&lt;String,Quote&gt; stream=kStreamsBuilder.stream(inputTopic);
        for(String topic:allTopics){
            stream.filter((s, quote) -&gt; quote.getTags().contains(topic)).to(topic);
        }
        return stream;

    }

    /**
     * Kafka ConsumerFactory configurations
     * @return
     */
    @Bean
    public ConsumerFactory&lt;String, Quote&gt; consumerFactory() {
        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();
        props.put(
                ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                kafkaProperties.getBootstrapServers());
        props.put(
                ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                StringDeserializer.class);
        props.put(
                ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                BytesDeserializer.class);
        return new DefaultKafkaConsumerFactory&lt;&gt;(props);
    }

    /**
     * Required Configuration for POJO to JSON
     * @return ConcurrentKafkaListenerContainerFactory
     */
    @Bean
    public ConcurrentKafkaListenerContainerFactory&lt;String, Quote&gt;
    kafkaListenerContainerFactory() {

        ConcurrentKafkaListenerContainerFactory&lt;String, Quote&gt; factory =
                new ConcurrentKafkaListenerContainerFactory&lt;&gt;();
        factory.setConsumerFactory(consumerFactory());
        factory.setMessageConverter(new StringJsonMessageConverter());
        return factory;
    }
}
</code></pre></div></div>

<ul>
  <li>Since we have injected default KafkaProperties will have required bindings from application.yml .</li>
  <li>Beans for default Kafka Stream ,consumer factory and <code class="language-plaintext highlighter-rouge">ConcurrentKafkaListenerContainerFactory</code> is created where <code class="language-plaintext highlighter-rouge">ConcurrentKafkaListenerContainerFactory</code> bean help us to convert incoming message from String to Json using <code class="language-plaintext highlighter-rouge">StringJsonMessageConverter</code></li>
  <li>KStream bean helps to create a stream on input topic (quotes) and filter based on tags. For each tag we already have created topics.</li>
</ul>

<p>Now Let us look at Listener configuration which will listen all the topics</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@Component
public class TopicConsumers {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicConsumers.class);

    @Value("#{'${kafka.topic.output}'.split(',')}")
    private List&lt;String&gt; allTopics;

    /**
     * For simplicity we are listening all topics at one listener
     */

    @KafkaListener(id = "allTopics", topics = "#{'${kafka.topic.output}'.split(',')}",
            containerFactory = "kafkaListenerContainerFactory")
    public void consume(@Payload Quote quote,
                        @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
                        @Header(KafkaHeaders.RECEIVED_TOPIC) String incomingTopic,
                        @Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts
    ) {
        LOGGER.info("Incoming quote {}-&gt; {}", incomingTopic, quote);
    }
}
</code></pre></div></div>

<ul>
  <li>For simplicity we are listening all of these topics at one Listener</li>
</ul>

<p>Once we run the application we will see logs confirming publishing of quotes with different tags and streams sending them to their respective category. Listener will listen incoming quotes.</p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Spring" /><category term="Kafka" /><category term="Kafka Stream" /><category term="Java" /><category term="Reactive" /><category term="RxJava" /><category term="rxjava2" /><summary type="html"><![CDATA[Kafka is most sought after event system today. In this series we will look at Kafka event messaging and streaming.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/assets/images/Stream.jpg" /><media:content medium="image" url="https://digitalyogi.tech/assets/images/Stream.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Quarkus IO</title><link href="https://digitalyogi.tech/quarkus/java/2020/02/17/QuarkusIO-Introduction.html" rel="alternate" type="text/html" title="Quarkus IO" /><published>2020-02-17T15:09:11+00:00</published><updated>2020-02-17T15:09:11+00:00</updated><id>https://digitalyogi.tech/quarkus/java/2020/02/17/QuarkusIO-Introduction</id><content type="html" xml:base="https://digitalyogi.tech/quarkus/java/2020/02/17/QuarkusIO-Introduction.html"><![CDATA[<p>Quarkus IO is a microservices based java framework. According to QuarkusIO website , Quarkus is “<em>A Kubernetes Native Java stack tailored for OpenJDK HotSpot &amp; GraalVM, crafted from the best of breed Java libraries and standards</em>”. This course will talks about creating microservices based on Quarkus. We will be going through</p>

<ol>
  <li>Installing required software for understanding full features of Quarkus</li>
  <li>Building Todo and User Microservices using Quarkus</li>
  <li>Building superfast native images</li>
  <li>Writing test cases</li>
  <li>Using Hibernate and Mongodb database as backend</li>
  <li>Creating microservices architecture using Fallbacks and distributed logginh</li>
  <li>deploying them in cloud</li>
</ol>

<h1 id="installing-software">Installing Software</h1>

<p>In this section we will look at installing software required for this course. This is a prerequisite if you want to follow along this course. We will be installing . We will be installing on Linux based system but you can install on your desired operation system</p>

<ol>
  <li>JDK 1.8+</li>
  <li>Maven 3.6.X</li>
  <li>GraalVM</li>
  <li>Docker</li>
</ol>

<h2 id="jdk">JDK</h2>

<p>To install JDK go to official website and download the latest version for your operating system.On a linux laptop with Ubuntu you can follow the steps as well</p>

<ol>
  <li>Open terminal</li>
  <li>
    <p>write following commands</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>        sudo add-apt-repository ppa:openjdk-r/ppa
        sudo apt update
        sudo apt install open-jdk-8-jdk
        export JAVA_HOME=/usr/lib/jvm/java-8-openjdk
        export PATH=$PATH:$JAVA_HOME/bin
</code></pre></div>    </div>
  </li>
</ol>

<p>Check the installed version</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>java -version
</code></pre></div></div>

<h2 id="maven-36x">Maven 3.6.X</h2>

<p>Maven is a build tool it will help us to create builds effectively. To install maven visit maven website and download latest maven. Unzip it and add to path. JAVA_HOME must be set to use maven</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>unzip apache-maven-3.6.3-bin.zip
            export PATH=/opt/apache-maven-3.6.3/bin:$PATH
</code></pre></div></div>

<h2 id="graalvm">GraalVM</h2>

<p>GraalVM is a virtual machine by oracle which enables user to create native images. Native images are faster and has lower memory footprint. GraamVM enable local executables and the binary created by it is independent of JVM it runs faster. It must be noticed that while creating native builds GraalVM do analyse all the classes your code will use at its entire life cycle and the compiles to byte code , the entire process is a bit slow. Run below commands to install GraalVM on linux (ubuntu)</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            sudo apt-get install build-essential libz-dev zlib1g-dev
</code></pre></div></div>

<p>You can install GraamVM community edition or can download enterprise edition from oracle website. If you have a enterprise edition tar file downloaded</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            tar -xvf graalvm-ee-java11-linux-amd64-19.3.1.tar.gz
            export GRAALVM_HOME=/home/coding/Documents/Softwares/graalvm-ee-java11-19.3.1/
</code></pre></div></div>

<p>If you have enterprise edition installed download native jar and run following command</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            ${GRAALVM_HOME}/bin/gu install native-image --filr native-image-installable-svm-svmee-java11-linux-amd64-19.3.1.jar
</code></pre></div></div>

<h2 id="docker">Docker</h2>

<p>To install docker at Ubuntu we can use following commands</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         sudo apt install apt-transport-https ca-certificates curl software-properties-common
         curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
         sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic test"
         sudo apt update
         sudo apt install docker-ce
</code></pre></div></div>

<p>For detailed documentation of installation on any platform https://docs.docker.com/</p>

<h1 id="creating-user-microservices">Creating User Microservices</h1>

<p>In this section we will create our first microservice. We will create user-service which will help us to perform crud operations on user. User service will have mogodb as back end . We will create it using maven command ,Alternatively we can also use generator site i.e <a href="https://code.quarkus.io">https://code.quarkus.io</a></p>

<h2 id="creating-user-service-using-maven">Creating user-service using maven</h2>

<p>Open terminal and type following command.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>		mvn io.quarkus:quarkus-maven-plugin:1.2.0.Final:create \
            -DprojectGroupId=com.codingsaint.learning.quarkus \
            -DprojectArtifactId=user-service \
            -DclassName="com.codingsaint.learning.quarkus.UserResource" \
            -Dpath="/user"
</code></pre></div></div>

<blockquote>
  <p>While the above command will only a bare project which you can run using simple maven command. We will be adding the dependencies later , just to understand how can we use quarkus maven extension to add dependencies ,Obviously both steps can be combined together.</p>
</blockquote>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         cd user-service
         mvn quarkus:dev
</code></pre></div></div>

<h2 id="running-application-in-dev-mode">Running application in dev mode</h2>

<p>The command to run in dev mode is</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>         mvn quarkus:dev
</code></pre></div></div>

<p>This will start the server in dev mode.In dev mode if you edit the code and do a change it will stop quarkus (not JVM), recompile and start quarkus . This works as live reload and is very helpful in dev mode</p>

<h2 id="building-native-image">building native image</h2>

<p>Quarkus comes with integrated support for building native images , you can build bare metal or docker based images.To create a image run the below command</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mvn package -Pnative
</code></pre></div></div>

<p>It must be noted that this is a maven profile for building native images and to support this GraalVM must be installed with native jar as mentioned above.   To build native for docker image add</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-Dnative-image.docker-build=true
</code></pre></div></div>

<h2 id="adding-dependencies">Adding dependencies</h2>

<p>We will be using below command to add dependecies</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mvn quarkus:add-extension -Dextensions=hibernate-validator,mongodb-panache,resteasy-jsonb
</code></pre></div></div>

<p>It must be noted that we could have added extensions while creating the project itself adding -D extension , this is just to show , how to add dependencies using maven. You can find list of all the available dependencies at <a href="https://quarkus.io/extensions/">https://quarkus.io/extensions/</a></p>

<h2 id="creating-user-entity">Creating User entity</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>package com.codingsaint.learning.quarkus;

import io.quarkus.mongodb.panache.MongoEntity;
import io.quarkus.mongodb.panache.PanacheMongoEntity;
import org.bson.codecs.pojo.annotations.BsonId;
import org.bson.codecs.pojo.annotations.BsonProperty;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;

@MongoEntity
public class User extends PanacheMongoEntity {

    private String userId;

    @NotNull(message = "First Name is required")
    private String firstName;

    private String lastName;

    @BsonProperty("dob")
    @NotNull(message = "Date of Birth is required")
    private LocalDate dateOfBirth;

    @NotNull(message = "Email is required")
    private String email;

    private Boolean active;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public static User findByUserId(String userId) {
        return find("userId", userId).firstResult();
    }
}
</code></pre></div></div>

<p>Adding UserResource</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                package com.codingsaint.learning.quarkus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.UUID;

@Path("/users")
public class UserResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);

    /**
     * Get all of the users
     *
     * @return Response&gt; users
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response users() {
        return Response.ok(User.listAll()).build();
    }

    /**
     * Create the user
     *
     * @param user
     * @return
     */
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response users(final @Valid User user) {
        user.setUserId(UUID.randomUUID().toString());
        user.setActive(true); 
        User.persist(user);
        return Response.ok().build();
    }

    /**
     * Update the user
     *
     * @param user
     * @return
     */
    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response update(final @Valid User user) {
        user.update();
        return Response.ok(user).build();
    }

    /**
     * retrieve user based on userId
     *
     * @param userId
     * @return Response
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("id/{id}")
    public Response getUserByUserId(@PathParam("id") String userId) {
        User user = User.findByUserId(userId);
        LOGGER.info(" finding user based on userId {}", userId);
        return Response.ok(user).build();
    }

    /**
     * delete user based on userId
     * @param userId
     * @return
     */
    @DELETE
    @Path("id/{id}")
    public Response deleteUser(@PathParam("id") String userId) {
        LOGGER.info(" delete user based on userId {}", userId);
        User.delete("userId",userId);
        return Response.noContent().build();
    }

}
</code></pre></div></div>

<h2 id="adding-application-properties">Adding application properties</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            quarkus.mongodb.connection-string = mongodb://localhost:27017
            quarkus.mongodb.database=todo-users
</code></pre></div></div>

<h2 id="running-the-server">Running the server</h2>

<p>Run the server using below command</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            mvn quarkus:dev
</code></pre></div></div>

<h2 id="add-a-user">Add a user</h2>

<p>Add following curl command or use postman or other software to do a post</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl -X POST \
            http://localhost:8080/user \
            -H 'Content-Type: application/json' \
            -d '{
            "firstName":"Kumar",
            "lastName":"Pallav",
            "dateOfBirth":"1987-08-05",
            "email":"codingsaint@gmail.com"
</code></pre></div></div>

<p>}’</p>

<h2 id="retrieve-all-users">Retrieve all users</h2>

<p>Use a get request http://localhost:8080/user/all or do a curl as below</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            curl -X GET \
            http://localhost:8080/user/all \
</code></pre></div></div>

<p>You will get a response like</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>            [{

            "id": "5e430af58cd12948d22faa9a",

            "active": true,

            "dateOfBirth": "1987-08-05",

            "email": "codingsaint@gmail.com",

            "firstName": "Kumar",

            "lastName": "Pallav",

            "userId": "10905021-e7c5-43e2-a29e-8a42f69d4fb2"

            }]
</code></pre></div></div>]]></content><author><name></name></author><category term="quarkus" /><category term="java" /><summary type="html"><![CDATA[Quarkus IO is a microservices based java framework. According to QuarkusIO website , Quarkus is “A Kubernetes Native Java stack tailored for OpenJDK HotSpot &amp; GraalVM, crafted from the best of breed Java libraries and standards”. This course will talks about creating microservices based on Quarkus. We will be going through]]></summary></entry><entry><title type="html">Observable using timer</title><link href="https://digitalyogi.tech/2020/01/23/observable-using-timer/" rel="alternate" type="text/html" title="Observable using timer" /><published>2020-01-23T08:01:11+00:00</published><updated>2020-01-23T08:01:11+00:00</updated><id>https://digitalyogi.tech/2020/01/23/observable-using-timer</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/23/observable-using-timer/"><![CDATA[<p>Observable with timer will delay the publishing the event to the the time specified. It can be used if you want the Observable to delay the publishing of source events for some time.<br />
It will publish a Single element after the time specified.</p>

<script src="https://gist.github.com/0517f3bea2da62caffef6bb4600b8d2b.js"> </script>

<p>Below logs will show that event is published after specified time of 5 seconds.</p>

<pre>23-01-20 13:29:49 [main] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onSubscribe
23-01-20 13:29:54 [RxComputationThreadPool-1] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onNext -&gt; 0
23-01-20 13:29:54 [RxComputationThreadPool-1] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onComplete</pre>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Java" /><category term="Reactive" /><category term="RxJava" /><category term="rxjava2" /><summary type="html"><![CDATA[Observable with timer will delay the publishing the event to the the time specified. It can be used if you want the Observable to delay the publishing of source events for some time. It will publish a Single element after the time specified.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" /><media:content medium="image" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Observable using interval</title><link href="https://digitalyogi.tech/2020/01/23/observable-using-interval/" rel="alternate" type="text/html" title="Observable using interval" /><published>2020-01-23T07:51:58+00:00</published><updated>2020-01-23T07:51:58+00:00</updated><id>https://digitalyogi.tech/2020/01/23/observable-using-interval</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/23/observable-using-interval/"><![CDATA[<p>Interval are timed observables. They tell to perform an event at regular basis. Intervals will help to perform a task regularly.</p>

<p>Below code is a way to create a Timed interval example.</p>

<script src="https://gist.github.com/ba2f2fd9d301642ec7e8c87ba8e7e89f.js"> </script>

<p>The demo Interval will keep getting invoked at regular interval of a second. We have added a sleep that that we can see the events getting logged.</p>

<p>Since it is observed computation thread so sleep will help us in seeing the logs.</p>

<pre>23-01-20 13:17:53 [main] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onSubscribe
23-01-20 13:17:54 [RxComputationThreadPool-2] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onNext -&gt; 0
23-01-20 13:17:55 [RxComputationThreadPool-2] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onNext -&gt; 1
23-01-20 13:17:56 [RxComputationThreadPool-2] [INFO ] [c.c.l.rxjava.observers.DemoObserver]- onNext -&gt; 2</pre>

<p> </p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Reactive" /><category term="RxJava" /><category term="rxjava2" /><summary type="html"><![CDATA[Interval are timed observables. They tell to perform an event at regular basis. Intervals will help to perform a task regularly.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" /><media:content medium="image" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Observable using defer</title><link href="https://digitalyogi.tech/2020/01/22/observable-using-defer/" rel="alternate" type="text/html" title="Observable using defer" /><published>2020-01-22T15:36:50+00:00</published><updated>2020-01-22T15:36:50+00:00</updated><id>https://digitalyogi.tech/2020/01/22/observable-using-defer</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/22/observable-using-defer/"><![CDATA[<p>Observable normally gets created once the code executes, Observable using defer , defers the creation of Observable. It waits till a subscription is done.</p>

<p>Below are main property of Observable using defer.</p>

<ol>
  <li><span style="font-weight: 400;">Creates new observable every time on subscription</span></li>
  <li><span style="font-weight: 400;">No Observable is created  until subscription</span></li>
</ol>

<p>Below is the code showing Observable using defer</p>

<script src="https://gist.github.com/ee75cc833bbd4072d421fa53f91b31ea.js"> </script>

<p>Here intentionally we are subscribing 2 times to show that each time Observable is created. You can also see that defer is taking <em>fromIterable</em> to create the observable. This will stop creating defer until we subscribe. Once subscribed <em>Observable.fromInterable</em> code will be invoked</p>]]></content><author><name>Kumar Pallav</name></author><category term="Spring" /><category term="Java" /><category term="Reactive" /><category term="RxJava" /><summary type="html"><![CDATA[Observable normally gets created once the code executes, Observable using defer , defers the creation of Observable. It waits till a subscription is done.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" /><media:content medium="image" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Observable using create</title><link href="https://digitalyogi.tech/2020/01/18/observable-using-create/" rel="alternate" type="text/html" title="Observable using create" /><published>2020-01-17T19:01:40+00:00</published><updated>2020-01-17T19:01:40+00:00</updated><id>https://digitalyogi.tech/2020/01/18/observable-using-create</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/18/observable-using-create/"><![CDATA[<p>create is an important method to create Observable. Below are few points which make Observable using create interesting</p>

<li style="font-weight: 400;">
  <span style="font-weight: 400;">Creates from scratch</span>
</li>
<li style="font-weight: 400;">
  <span style="font-weight: 400;">observer methods are programmatically written</span>
</li>
<li style="font-weight: 400;">
  <span style="font-weight: 400;">emitter method is provided for interfaces to use</span>
</li>

<p>Below is the code which can help you to understand creating Observable using create method.</p>

<script src="https://gist.github.com/97f69898c3d3dcf6e1cf1669ebb1bdee.js"> </script>

<p>Here we are trying to create Observable using create method where we get 15 different shapes. The create method provides a subscribe method where we are iterating each elements from list and emitting one by one. The emitted events are listened on DemoSubscriber.</p>

<p>For RxUtil.java class and DemoSubscriber and for full code you can refer git library : <a href="https://github.com/CODINGSAINT/rxJava-tutorial" rel="nofollow">https://github.com/CODINGSAINT/rxJava-tutorial</a></p>

<p>Now once you run it you will get following output</p>

<div class="gist-oembed" data-gist="7b3541ea2b1831d78921819e9d521339.json" data-ts="8">
</div>

<p> </p>

<p> </p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Reactive" /><category term="RxJava" /><summary type="html"><![CDATA[create is an important method to create Observable. Below are few points which make Observable using create interesting]]></summary></entry><entry><title type="html">Creating Observable RxJava</title><link href="https://digitalyogi.tech/2020/01/09/creating-observable-rxjava/" rel="alternate" type="text/html" title="Creating Observable RxJava" /><published>2020-01-09T02:20:25+00:00</published><updated>2020-01-09T02:20:25+00:00</updated><id>https://digitalyogi.tech/2020/01/09/creating-observable-rxjava</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/09/creating-observable-rxjava/"><![CDATA[<p>Observable being the most important block of reactive programming , it is important to understand different methods of creating Observable.</p>

<p>Observable can be created be created by following methods.</p>

<ol>
  <li>just</li>
  <li>create</li>
  <li>defer</li>
  <li>range</li>
  <li>interval</li>
  <li>repeat</li>
  <li>timer</li>
  <li>from</li>
</ol>

<li style="list-style-type: none;">
  <ul>
    <li>
      fromCallable
    </li>
    <li>
      fromIterable
    </li>
    <li>
      fromArray
    </li>
    <li>
      fromPublisher
    </li>
  </ul>
</li>

<p>Observables emits events on which Observer subscribes too. So let us start by creating a DemoObserver which will be subscribing to our Observables.</p>

<script src="https://gist.github.com/05daebcdb02f09ed0be22814e095f02d.js"> </script>

<p>The above DemoObserver will be subscribing to our Observable. This will let the code be more clear and understandable. The DemoObservable is simple and logs events as subscription , errors and completion. It also adds logs each element the observable emits with onNext method.</p>

<p>Let’s look at the methods of creating an Observable.</p>

<h3 id="just">just</h3>

<p>just is used to create Observable with maximum of 10 elements.  It comes handy when we have events limited to maximum of 10 events.</p>

<script src="https://gist.github.com/27ce3572b4607e19f54c1547981ca061.js"> </script>

<p>The above code will create an Observable with list of alphabets from a to j . Below is the logs which will be published.</p>

<pre>08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onSubscribe
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; a
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; b
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; c
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; d
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; e
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; f
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; g
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; h
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; i
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onNext -&gt; j
08-01-20 12:51:37 [main] [INFO ] [c.c.l.rxjava.observable.CsObservable]- onComplete</pre>

<p> </p>

<p>The above log confirms onSubscribe , followed by onNext with elements from “a” to “j” and completed by an onComplete.</p>

<p> </p>

<p>The  above code can also be written using our own DemoObserver in a simple and cleaner way.</p>

<pre>Observable.just("a","b","c","d","e","f","g","h","i","j")
        .subscribe(new DemoObserver());</pre>

<p>For further example we’ll be using our DemoObserver for readability.</p>

<p>In next post we will see creating observables with other methods.</p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Reactive" /><category term="RxJava" /><summary type="html"><![CDATA[Observable being the most important block of reactive programming , it is important to understand different methods of creating Observable.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" /><media:content medium="image" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Building blocks of Reactive Systems</title><link href="https://digitalyogi.tech/2020/01/03/building-blocks-of-reactive-systems/" rel="alternate" type="text/html" title="Building blocks of Reactive Systems" /><published>2020-01-03T09:52:12+00:00</published><updated>2020-01-03T09:52:12+00:00</updated><id>https://digitalyogi.tech/2020/01/03/building-blocks-of-reactive-systems</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/03/building-blocks-of-reactive-systems/"><![CDATA[<p>Reactive Systems consists of 2 major components.</p>

<ol>
  <li>Observable</li>
  <li>Observer</li>
</ol>

<h3 id="observable">Observable</h3>

<p>Think of an example of watching movie , The movie is being played and it keeps emitting events in form of stream of screens and voice. Here in this example , we can say that Movie is an Observable type.</p>

<p>Similarly if you log in to twitter it has streams of incoming tweets. In Facebook it is stream of posts.</p>

<p>If we take a more traditional approach of programming for streaming events , we will be choking our systems. The traditional mode of approach will also result in losing states of data or else it will be too overwhelming for it to keep all the state and work on it.</p>

<p>Let’s think an example of a shopping cart. If you add an item or update its quantity , each of your action is an event. In traditional approach you don’t track all the events but the final value of cart. If we keep the states of all of the events in real time using traditional approach with database at backend , we will be making lot of database related operations which will lead to memory and performance issues.</p>

<p>###<img class="alignnone size-full wp-image-611" src="https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_building_blocks.png?resize=750%2C431&#038;ssl=1" alt="reactive_building_blocks.png" width="750" height="431" srcset="https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_building_blocks.png?w=898&amp;ssl=1 898w, https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_building_blocks.png?resize=300%2C172&amp;ssl=1 300w, https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_building_blocks.png?resize=768%2C441&amp;ssl=1 768w, https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_building_blocks.png?resize=600%2C345&amp;ssl=1 600w" sizes="(max-width: 750px) 100vw, 750px" data-recalc-dims="1" /> Observer</p>

<p>Observer is one who observe observable. If you are watching movie you are the observer. In order to observer we have same basic rules, which in reactive methodology are translated as methods.</p>

<p>To watch movie , we need ticket i.e. subscription (onSubscribe) , as the move starts we observer streams of events (onNext ) , once movie compleats (onCompleate) we know the movies is finished we stop observing it or if there is an error (onError) viz. power failure, we still stop observing.</p>

<p>Similarly while designing reactive streams and systems we keep in mind of reactive manifesto . By adhering those principals above methods help us to keep things simple yet effective.</p>

<p>In next section we will see how to create Observable and observer.</p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Reactive" /><category term="RxJava" /><summary type="html"><![CDATA[Reactive Systems consists of 2 major components.]]></summary></entry><entry><title type="html">Reactive Manifesto</title><link href="https://digitalyogi.tech/2020/01/03/reactive-manifesto/" rel="alternate" type="text/html" title="Reactive Manifesto" /><published>2020-01-03T07:35:39+00:00</published><updated>2020-01-03T07:35:39+00:00</updated><id>https://digitalyogi.tech/2020/01/03/reactive-manifesto</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/03/reactive-manifesto/"><![CDATA[<p>In 2013, a group of software developers drafted and published a set of principles for reactive paradigm. The group was led by Joan Boaner.</p>

<p>These set of rules defines core principles of Reactive Programming.  Let us look at these principals.</p>

<ol>
  <li>Responsive</li>
  <li>Resilient</li>
  <li>Elastic</li>
  <li>Message Driven</li>
</ol>

<p><img class="alignnone size-full wp-image-602" src="https://i2.wp.com/codingsaint.com/wp-content/uploads/2020/01/Reactive_Manifesto.png?resize=750%2C422&#038;ssl=1" alt="Reactive_Manifesto" width="750" height="422" srcset="https://i2.wp.com/codingsaint.com/wp-content/uploads/2020/01/Reactive_Manifesto.png?w=960&amp;ssl=1 960w, https://i2.wp.com/codingsaint.com/wp-content/uploads/2020/01/Reactive_Manifesto.png?resize=300%2C169&amp;ssl=1 300w, https://i2.wp.com/codingsaint.com/wp-content/uploads/2020/01/Reactive_Manifesto.png?resize=768%2C432&amp;ssl=1 768w, https://i2.wp.com/codingsaint.com/wp-content/uploads/2020/01/Reactive_Manifesto.png?resize=600%2C338&amp;ssl=1 600w" sizes="(max-width: 750px) 100vw, 750px" data-recalc-dims="1" /></p>

<h3 id="responsive">Responsive</h3>

<p>The system should react in timely manner if possible. System should be robust enough to respond within given time frame. It helps in dealing with failures early. Responsiveness also ensures you have a time limit to respond. If the time limit is breached, it is treated as a failure. In case of failure, system must respond timely and effectively.</p>

<h3 id="resilient">Resilient</h3>

<p>System should be effective to handle failures. Reactive system knows how to respond in case of errors. This is achieved by replication, isolation, containment and delegation. This makes system to recover in cases of failures without putting entire system at halt.</p>

<h3 id="elastic">Elastic</h3>

<p>System should scale with load. If the load increases or decreases system must scale accordingly. This means reactive systems are designed without having bottlenecks. It should replicate or eliminate instances based on need.</p>

<h3 id="message-driven">Message Driven</h3>

<p>Reactive systems are message driven. They work on publish and subscribe methods. System responds to events as an when it comes. The asynchronous processing enables handling larger load effectively.</p>

<p> </p>

<p>In Next section we will look at Components of Reactive Systems and further we will start coding in reactive manner using RxJava.</p>

<p> </p>]]></content><author><name>Kumar Pallav</name></author><category term="Spring" /><category term="Reactive" /><category term="RxJava" /><summary type="html"><![CDATA[In 2013, a group of software developers drafted and published a set of principles for reactive paradigm. The group was led by Joan Boaner.]]></summary></entry><entry><title type="html">RxJava – Reactive Revolutions</title><link href="https://digitalyogi.tech/2020/01/02/rxjava-reactive-programming/" rel="alternate" type="text/html" title="RxJava – Reactive Revolutions" /><published>2020-01-02T11:01:53+00:00</published><updated>2020-01-02T11:01:53+00:00</updated><id>https://digitalyogi.tech/2020/01/02/rxjava-reactive-programming</id><content type="html" xml:base="https://digitalyogi.tech/2020/01/02/rxjava-reactive-programming/"><![CDATA[<p>Reactive is not new in Software Engineering. Within few years, we have seen increase in reactive solutions at a large scale. Let us look what reactive programming actually means.</p>

<p>Reactive programming is a paradigm which enables to program for streams of data in non blocking  (<em>asynchronous</em>) manner. It makes the solutions such that the <em>system</em> reacts to the stream of events.</p>

<p>Reactive programming paradigm is similar on principal with Observable and Observer pattern. Observable being the emitter of events and observer observing on the emitted events with knowledge of steps to be taken with incoming data.</p>

<p>In real world example, let’s consider a newspaper or a Netflix show. Here the newspaper or the Netflix show is what you have subscribed too, so it is observable. It emits stream of events in form of news or show content. In order to receive receive newspaper everyday or new shows from Netflix ,the first step is too subscribe. Once subscribed whenever observer emits events (a newspaper publishing the news daily or an episode  on Netflix) you receive it. On every new events published from publisher ,i.e. the daily newspaper or the Netflix show,  you are free to act upon as a observer. In case your subscription is expired (which you can think as an exception) you should be taking an action based on your interest. Once Netflix show is finished , or you have read the newspaper and no longer wants it , it can be notification of events being completed or being unsubscribed.</p>

<p>Similarly, in software world we can program based on events to make more robust solution which can scale better.</p>

<p>The evolution of computers have had been focused on processing speed. As we have increased number of cores , we can work on multiple processes together. We have added more cores but if we keep our programming model as single threaded application, we will never be utilising processor to its full capacity. When the load will grow up , we will be scaling by adding more CPUs ,yet all the CPU will be fractionally utilised. This will increase cost while we if we had coded effectively utilising all the available cores we could have saved lot of money easily.</p>

<p>Consider we have a Order from a normal e-commerce website, where we need to call different services like cart service, user service and product services. We aggregate all these 3 calls to send back the response to our user.</p>

<p><img class="alignnone size-full wp-image-598" src="https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_benefits.png?resize=575%2C333&#038;ssl=1" alt="reactive_benefits" width="575" height="333" srcset="https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_benefits.png?w=575&amp;ssl=1 575w, https://i0.wp.com/codingsaint.com/wp-content/uploads/2020/01/reactive_benefits.png?resize=300%2C174&amp;ssl=1 300w" sizes="(max-width: 575px) 100vw, 575px" data-recalc-dims="1" /></p>

<p>The throughput of such a call will be time taken by cart service (x), product service (y) and user service(z) along with time taken in network calls .</p>

<p><em>Total time taken = Network Time + (x)+(y)+z()</em></p>

<p>If we execute these network calls in parallel and know when all of the calls return responses , we aggregate their responses and send a aggregated response , we can save time. In this case time taken will be</p>

<p><em>Total time taken =Network time+ Max(x,y,z)</em></p>

<p>This will save our time and response could be much faster. We can achieve it by already present Future and callbacks, then why do we need to look at reactive paradigm. With increase in network calls and callback function , slowly it will lead to complex structure and it will become <em>callback hell</em>.</p>

<p>Reactive paradigm works with all these functionality and yet keeps things simple. We will explore it  in this series on Reactive Programming with Java.</p>

<p>In next section we will look at founding principal of reactive programming which is <em>Reactive Manifesto</em>.</p>

<p> </p>

<p> </p>

<p> </p>

<p> </p>]]></content><author><name>Kumar Pallav</name></author><category term="Java" /><category term="Java" /><category term="RxJava" /><summary type="html"><![CDATA[Reactive is not new in Software Engineering. Within few years, we have seen increase in reactive solutions at a large scale. Let us look what reactive programming actually means.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" /><media:content medium="image" url="https://digitalyogi.tech/wp-content/uploads/2020/01/RxJava.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>