<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Akka - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Akka - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 20 May 2026 22:47:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/akka/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to make a simple application with Akka Cluster ]]>
                </title>
                <description>
                    <![CDATA[ By Luca Florio If you read my previous story about Scalachain, you probably noticed that it is far from being a distributed system. It lacks all the features to properly work with other nodes. Add to it that a blockchain composed by a single node is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-a-simple-application-with-akka-cluster-506e20a725cf/</link>
                <guid isPermaLink="false">66d45e4873634435aafcef86</guid>
                
                    <category>
                        <![CDATA[ Akka ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scala ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Feb 2019 21:08:29 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*kbflVM9_tfKyfVOR1ldKAw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Luca Florio</p>
<p>If you read my previous story about <a target="_blank" href="https://github.com/elleFlorio/scalachain">Scalachain</a>, you probably noticed that it is far from being a distributed system. It lacks all the features to properly work with other nodes. Add to it that a blockchain composed by a single node is useless. For this reason I decided it is time to work on the issue.</p>
<p>Since Scalachain is powered by Akka, why not take the chance to play with Akka Cluster? I created a <a target="_blank" href="https://github.com/elleFlorio/akka-cluster-playground">simple project</a> to tinker a bit with <a target="_blank" href="https://doc.akka.io/docs/akka/2.5/index-cluster.html">Akka Cluster</a>, and in this story I’m going to share my learnings. We are going to create a cluster of three nodes, using <a target="_blank" href="https://doc.akka.io/docs/akka/2.5/cluster-routing.html#weakly-up">Cluster Aware Routers</a> to balance the load among them. Everything will run in a Docker container, and we will use docker-compose for an easy deployment.</p>
<p>Ok, Let’s roll! ?</p>
<h4 id="heading-quick-introduction-to-akka-cluster">Quick introduction to Akka Cluster</h4>
<p>Akka Cluster provides great support to the creation of distributed applications. The best use case is when you have a node that you want to replicate N times in a distributed environment. This means that all the N nodes are peers running the same code. Akka Cluster gives you out-of-the-box the discovery of members in the same cluster. Using Cluster Aware Routers it is possible to balance the messages between actors in different nodes. It is also possible to choose the balancing policy, making load-balancing a piece of cake!</p>
<p>Actually you can chose between two types of routers:</p>
<p><strong>Group Router</strong> — The actors to send the messages to — called routees — are specified using their actor path. The routers share the routees created in the cluster. We will use a Group Router in this example.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*aRVBb-_v2dBpTV8m97Pd3w.png" alt="Image" width="541" height="491" loading="lazy">
<em>Group Router</em></p>
<p><strong>Pool Router</strong> — The routees are created and deployed by the router, so they are its children in the actor hierarchy. Routees are not shared between routers. This is ideal for a primary-replica scenario, where each router is the primary and its routees the replicas.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ofa_x3hkM_sMzH5Nzum_Gg.png" alt="Image" width="741" height="499" loading="lazy">
<em>Pool Router</em></p>
<p>This is just the tip of the iceberg, so I invite you to read the <a target="_blank" href="https://doc.akka.io/docs/akka/2.5/index-cluster.html">official documentation</a> for more insights.</p>
<h4 id="heading-a-cluster-for-mathematical-computations">A Cluster for mathematical computations</h4>
<p>Let’s picture a use-case scenario. Suppose to design a system to execute mathematical computations on request. The system is deployed online, so it needs a REST API to receive the computation requests. An internal processor handles these requests, executing the computation and returning the result.</p>
<p>Right now the processor can only compute the <a target="_blank" href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci number</a>. We decide to use a cluster of nodes to distribute the load among the nodes and improve performance. Akka Cluster will handle cluster dynamics and load-balancing between nodes. Ok, sounds good!</p>
<h4 id="heading-actor-hierarchy">Actor hierarchy</h4>
<p>First things first: we need to define our actor hierarchy. The system can be divided in three functional parts: the <strong>business logic</strong>, the <strong>cluster management</strong>, and the <strong>node</strong> itself. There is also the <strong>server</strong> but it is not an actor, and we will work on that later.</p>
<p><strong>Business logic</strong></p>
<p>The application should do mathematical computations. We can define a simple <code>Processor</code> actor to manage all the computational tasks. Every computation that we support can be implemented in a specific actor, that will be a child of the <code>Processor</code> one. In this way the application is modular and easier to extend and maintain. Right now the only child of <code>Processor</code> will be the <code>ProcessorFibonacci</code> actor. I suppose you can guess what its task is. This should be enough to start.</p>
<p><strong>Cluster management</strong></p>
<p>To manage the cluster we need a <code>ClusterManager</code>. Sounds simple, right? This actor handles everything related to the cluster, like returning its members when asked. It would be useful to log what happens inside the cluster, so we define a <code>ClusterListener</code> actor. This is a child of the <code>ClusterManager</code>, and subscribes to cluster events logging them.</p>
<p><strong>Node</strong></p>
<p>The <code>Node</code> actor is the root of our hierarchy. It is the entry point of our system that communicates with the API. The <code>Processor</code> and the <code>ClusterManager</code> are its children, along with the <code>ProcessorRouter</code> actor. This is the load balancer of the system, distributing the load among <code>Processor</code>s. We will configure it as a Cluster Aware Router, so every <code>ProcessorRouter</code> can send messages to <code>Processor</code>s on every node.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sblmA495LlrJLLBaIpbYYg.png" alt="Image" width="732" height="302" loading="lazy">
<em>Actor hierarchy</em></p>
<h4 id="heading-actor-implementation">Actor Implementation</h4>
<p>Time to implement our actors! Fist we implement the actors related to the business logic of the system. We move then on the actors for the cluster management and the root actor (<code>Node</code>) in the end.</p>
<p><strong>ProcessorFibonacci</strong></p>
<p>This actor executes the computation of the Fibonacci number. It receives a <code>Compute</code> message containing the number to compute and the reference of the actor to reply to. The reference is important, since there can be different requesting actors. Remember that we are working in a distributed environment!</p>
<p>Once the <code>Compute</code> message is received, the <code>fibonacci</code> function computes the result. We wrap it in a <code>ProcessorResponse</code> object to provide information on the node that executed the computation. This will be useful later to see the round-robin policy in action.</p>
<p>The result is then sent to the actor we should reply to. Easy-peasy.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">ProcessorFibonacci</span> </span>{
  <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">ProcessorFibonacciMessage</span></span>
  <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Compute</span>(<span class="hljs-params">n: <span class="hljs-type">Int</span>, replyTo: <span class="hljs-type">ActorRef</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">ProcessorFibonacciMessage</span></span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">props</span></span>(nodeId: <span class="hljs-type">String</span>) = <span class="hljs-type">Props</span>(<span class="hljs-keyword">new</span> <span class="hljs-type">ProcessorFibonacci</span>(nodeId))

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci</span></span>(x: <span class="hljs-type">Int</span>): <span class="hljs-type">BigInt</span> = {
    <span class="hljs-meta">@tailrec</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibHelper</span></span>(x: <span class="hljs-type">Int</span>, prev: <span class="hljs-type">BigInt</span> = <span class="hljs-number">0</span>, next: <span class="hljs-type">BigInt</span> = <span class="hljs-number">1</span>): <span class="hljs-type">BigInt</span> = x <span class="hljs-keyword">match</span> {
      <span class="hljs-keyword">case</span> <span class="hljs-number">0</span> =&gt; prev
      <span class="hljs-keyword">case</span> <span class="hljs-number">1</span> =&gt; next
      <span class="hljs-keyword">case</span> _ =&gt; fibHelper(x - <span class="hljs-number">1</span>, next, next + prev)
    }
    fibHelper(x)
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProcessorFibonacci</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{
  <span class="hljs-keyword">import</span> <span class="hljs-type">ProcessorFibonacci</span>._

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span></span>: <span class="hljs-type">Receive</span> = {
    <span class="hljs-keyword">case</span> <span class="hljs-type">Compute</span>(value, replyTo) =&gt; {
      replyTo ! <span class="hljs-type">ProcessorResponse</span>(nodeId, fibonacci(value))
    }
  }
}
</code></pre>
<p><strong>Processor</strong></p>
<p>The <code>Processor</code> actor manages the specific sub-processors, like the Fibonacci one. It should instantiate the sub-processors and forward the requests to them. Right now we only have one sub-processor, so the <code>Processor</code> receives one kind of message: <code>ComputeFibonacci</code>. This message contains the Fibonacci number to compute. Once received, the number to compute is sent to a <code>FibonacciProcessor</code>, along with the reference of the <code>sender()</code>.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Processor</span> </span>{

  <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">ProcessorMessage</span></span>

  <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ComputeFibonacci</span>(<span class="hljs-params">n: <span class="hljs-type">Int</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">ProcessorMessage</span></span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">props</span></span>(nodeId: <span class="hljs-type">String</span>) = <span class="hljs-type">Props</span>(<span class="hljs-keyword">new</span> <span class="hljs-type">Processor</span>(nodeId))
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Processor</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{
  <span class="hljs-keyword">import</span> <span class="hljs-type">Processor</span>._

  <span class="hljs-keyword">val</span> fibonacciProcessor: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">ProcessorFibonacci</span>.props(nodeId), <span class="hljs-string">"fibonacci"</span>)

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span></span>: <span class="hljs-type">Receive</span> = {
    <span class="hljs-keyword">case</span> <span class="hljs-type">ComputeFibonacci</span>(value) =&gt; {
      <span class="hljs-keyword">val</span> replyTo = sender()
      fibonacciProcessor ! <span class="hljs-type">Compute</span>(value, replyTo)
    }
  }
}
</code></pre>
<p><strong>ClusterListener</strong></p>
<p>We would like to log useful information about what happens in the cluster. This could help us to debug the system if we need to. This is the purpose of the <code>ClusterListener</code> actor. Before starting, it subscribes itself to the event messages of the cluster. The actor reacts to messages like <code>MemberUp</code>, <code>UnreachableMember</code>, or <code>MemberRemoved</code>, logging the corresponding event. When <code>ClusterListener</code> is stopped, it unsubscribes itself from the cluster events.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">ClusterListener</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">props</span></span>(nodeId: <span class="hljs-type">String</span>, cluster: <span class="hljs-type">Cluster</span>) = <span class="hljs-type">Props</span>(<span class="hljs-keyword">new</span> <span class="hljs-type">ClusterListener</span>(nodeId, cluster))
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClusterListener</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span>, cluster: <span class="hljs-type">Cluster</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> <span class="hljs-keyword">with</span> <span class="hljs-title">ActorLogging</span> </span>{

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">preStart</span></span>(): <span class="hljs-type">Unit</span> = {
    cluster.subscribe(self, initialStateMode = <span class="hljs-type">InitialStateAsEvents</span>,
      classOf[<span class="hljs-type">MemberEvent</span>], classOf[<span class="hljs-type">UnreachableMember</span>])
  }

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">postStop</span></span>(): <span class="hljs-type">Unit</span> = cluster.unsubscribe(self)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span> </span>= {
    <span class="hljs-keyword">case</span> <span class="hljs-type">MemberUp</span>(member) =&gt;
      log.info(<span class="hljs-string">"Node {} - Member is Up: {}"</span>, nodeId, member.address)
    <span class="hljs-keyword">case</span> <span class="hljs-type">UnreachableMember</span>(member) =&gt;
      log.info(<span class="hljs-string">s"Node {} - Member detected as unreachable: {}"</span>, nodeId, member)
    <span class="hljs-keyword">case</span> <span class="hljs-type">MemberRemoved</span>(member, previousStatus) =&gt;
      log.info(<span class="hljs-string">s"Node {} - Member is Removed: {} after {}"</span>,
        nodeId, member.address, previousStatus)
    <span class="hljs-keyword">case</span> _: <span class="hljs-type">MemberEvent</span> =&gt; <span class="hljs-comment">// ignore</span>
  }
}
</code></pre>
<p><strong>ClusterManager</strong></p>
<p>The actor responsible of the management of the cluster is <code>ClusterManager</code>. It creates the <code>ClusterListener</code> actor, and provides the list of cluster members upon request. It could be extended to add more functionalities, but right now this is enough.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">ClusterManager</span> </span>{

  <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">ClusterMessage</span></span>
  <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">GetMembers</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ClusterMessage</span></span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">props</span></span>(nodeId: <span class="hljs-type">String</span>) = <span class="hljs-type">Props</span>(<span class="hljs-keyword">new</span> <span class="hljs-type">ClusterManager</span>(nodeId))
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClusterManager</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> <span class="hljs-keyword">with</span> <span class="hljs-title">ActorLogging</span> </span>{

  <span class="hljs-keyword">val</span> cluster: <span class="hljs-type">Cluster</span> = <span class="hljs-type">Cluster</span>(context.system)
  <span class="hljs-keyword">val</span> listener: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">ClusterListener</span>.props(nodeId, cluster), <span class="hljs-string">"clusterListener"</span>)

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span></span>: <span class="hljs-type">Receive</span> = {
    <span class="hljs-keyword">case</span> <span class="hljs-type">GetMembers</span> =&gt; {
      sender() ! cluster.state.members.filter(_.status == <span class="hljs-type">MemberStatus</span>.up)
        .map(_.address.toString)
        .toList
    }
  }
}
</code></pre>
<p><strong>ProcessorRouter</strong></p>
<p>The load-balancing among processors is handled by the <code>ProcessorRouter</code>. It is created by the <code>Node</code> actor, but this time all the required information are provided in the configuration of the system.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{

  <span class="hljs-comment">//...</span>

  <span class="hljs-keyword">val</span> processorRouter: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">FromConfig</span>.props(<span class="hljs-type">Props</span>.empty), <span class="hljs-string">"processorRouter"</span>)

  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Let’s analyse the relevant part in the <code>application.conf</code> file.</p>
<pre><code>akka {
  actor {
    ...
    deployment {
      <span class="hljs-regexp">/node/</span>processorRouter {
        router = round-robin-group
        routees.paths = [<span class="hljs-string">"/user/node/processor"</span>]
        cluster {
          enabled = on
          allow-local-routees = on
        }
      }
    }
  }
  ...
}
</code></pre><p>The first thing is to specify the path to the router actor, that is <code>/node/processorRouter</code>. Inside that property we can configure the behaviour of the router:</p>
<ul>
<li><code>router</code>: this is the policy for the load balancing of messages. I chose the <code>round-robin-group</code>, but there are many others.</li>
<li><code>routees.paths</code>: these are the paths to the actors that will receive the messages handled by the router. We are saying: <em>“When you receive a message, look for the actors corresponding to these paths. Choose one according to the policy and forward the message to it.”</em> Since we are using Cluster Aware Routers, the routees can be on any node of the cluster.</li>
<li><code>cluster.enabled</code>: are we operating in a cluster? The answer is <code>on</code>, of course!</li>
<li><code>cluster.allow-local-routees</code>: here we are allowing the router to choose a routee in its node.</li>
</ul>
<p>Using this configuration we can create a router to load balance the work among our processors.</p>
<p><strong>Node</strong></p>
<p>The root of our actor hierarchy is the <code>Node</code>. It creates the children actors — <code>ClusterManager</code>, <code>Processor</code>, and <code>ProcessorRouter</code> — and forwards the messages to the right one. Nothing complex here.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Node</span> </span>{

  <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">NodeMessage</span></span>

  <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GetFibonacci</span>(<span class="hljs-params">n: <span class="hljs-type">Int</span></span>)</span>

  <span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">GetClusterMembers</span></span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">props</span></span>(nodeId: <span class="hljs-type">String</span>) = <span class="hljs-type">Props</span>(<span class="hljs-keyword">new</span> <span class="hljs-type">Node</span>(nodeId))
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>(<span class="hljs-params">nodeId: <span class="hljs-type">String</span></span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{

  <span class="hljs-keyword">val</span> processor: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">Processor</span>.props(nodeId), <span class="hljs-string">"processor"</span>)
  <span class="hljs-keyword">val</span> processorRouter: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">FromConfig</span>.props(<span class="hljs-type">Props</span>.empty), <span class="hljs-string">"processorRouter"</span>)
  <span class="hljs-keyword">val</span> clusterManager: <span class="hljs-type">ActorRef</span> = context.actorOf(<span class="hljs-type">ClusterManager</span>.props(nodeId), <span class="hljs-string">"clusterManager"</span>)

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span></span>: <span class="hljs-type">Receive</span> = {
    <span class="hljs-keyword">case</span> <span class="hljs-type">GetClusterMembers</span> =&gt; clusterManager forward <span class="hljs-type">GetMembers</span>
    <span class="hljs-keyword">case</span> <span class="hljs-type">GetFibonacci</span>(value) =&gt; processorRouter forward <span class="hljs-type">ComputeFibonacci</span>(value)
  }
}
</code></pre>
<h4 id="heading-server-and-api">Server and API</h4>
<p>Every node of our cluster runs a server able to receive requests. The <code>Server</code> creates our actor system and is configured through the <code>application.conf</code> file.</p>
<pre><code class="lang-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Server</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">App</span> <span class="hljs-keyword">with</span> <span class="hljs-title">NodeRoutes</span> </span>{

  <span class="hljs-keyword">implicit</span> <span class="hljs-keyword">val</span> system: <span class="hljs-type">ActorSystem</span> = <span class="hljs-type">ActorSystem</span>(<span class="hljs-string">"cluster-playground"</span>)
  <span class="hljs-keyword">implicit</span> <span class="hljs-keyword">val</span> materializer: <span class="hljs-type">ActorMaterializer</span> = <span class="hljs-type">ActorMaterializer</span>()

  <span class="hljs-keyword">val</span> config: <span class="hljs-type">Config</span> = <span class="hljs-type">ConfigFactory</span>.load()
  <span class="hljs-keyword">val</span> address = config.getString(<span class="hljs-string">"http.ip"</span>)
  <span class="hljs-keyword">val</span> port = config.getInt(<span class="hljs-string">"http.port"</span>)
  <span class="hljs-keyword">val</span> nodeId = config.getString(<span class="hljs-string">"clustering.ip"</span>)

  <span class="hljs-keyword">val</span> node: <span class="hljs-type">ActorRef</span> = system.actorOf(<span class="hljs-type">Node</span>.props(nodeId), <span class="hljs-string">"node"</span>)

  <span class="hljs-keyword">lazy</span> <span class="hljs-keyword">val</span> routes: <span class="hljs-type">Route</span> = healthRoute ~ statusRoutes ~ processRoutes

  <span class="hljs-type">Http</span>().bindAndHandle(routes, address, port)
  println(<span class="hljs-string">s"Node <span class="hljs-subst">$nodeId</span> is listening at http://<span class="hljs-subst">$address</span>:<span class="hljs-subst">$port</span>"</span>)

  <span class="hljs-type">Await</span>.result(system.whenTerminated, <span class="hljs-type">Duration</span>.<span class="hljs-type">Inf</span>)

}
</code></pre>
<p><a target="_blank" href="https://doc.akka.io/docs/akka-http/current/index.html">Akka HTTP</a> powers the server itself and the REST API, exposing three simple endpoints. These endpoints are defined in the <code>NodeRoutes</code> trait.</p>
<p>The first one is <code>/health</code>, to check the health of a node. It responds with a <code>200 OK</code> if the node is up and running</p>
<pre><code class="lang-scala"><span class="hljs-keyword">lazy</span> <span class="hljs-keyword">val</span> healthRoute: <span class="hljs-type">Route</span> = pathPrefix(<span class="hljs-string">"health"</span>) {
    concat(
      pathEnd {
        concat(
          get {
            complete(<span class="hljs-type">StatusCodes</span>.<span class="hljs-type">OK</span>)
          }
        )
      }
    )
  }
</code></pre>
<p>The <code>/status/members</code> endpoint responds with the current active members of the cluster.</p>
<pre><code class="lang-scala"><span class="hljs-keyword">lazy</span> <span class="hljs-keyword">val</span> statusRoutes: <span class="hljs-type">Route</span> = pathPrefix(<span class="hljs-string">"status"</span>) {
    concat(
      pathPrefix(<span class="hljs-string">"members"</span>) {
        concat(
          pathEnd {
            concat(
              get {
                <span class="hljs-keyword">val</span> membersFuture: <span class="hljs-type">Future</span>[<span class="hljs-type">List</span>[<span class="hljs-type">String</span>]] = (node ? <span class="hljs-type">GetClusterMembers</span>).mapTo[<span class="hljs-type">List</span>[<span class="hljs-type">String</span>]]
                onSuccess(membersFuture) { members =&gt;
                  complete(<span class="hljs-type">StatusCodes</span>.<span class="hljs-type">OK</span>, members)
                }
              }
            )
          }
        )
      }
    )
  }
</code></pre>
<p>The last (but not the least) is the <code>/process/fibonacci/n</code> endpoint, used to request the Fibonacci number of <code>n</code>.</p>
<pre><code class="lang-scala"><span class="hljs-keyword">lazy</span> <span class="hljs-keyword">val</span> processRoutes: <span class="hljs-type">Route</span> = pathPrefix(<span class="hljs-string">"process"</span>) {
    concat(
      pathPrefix(<span class="hljs-string">"fibonacci"</span>) {
        concat(
          path(<span class="hljs-type">IntNumber</span>) { n =&gt;
            pathEnd {
              concat(
                get {
                  <span class="hljs-keyword">val</span> processFuture: <span class="hljs-type">Future</span>[<span class="hljs-type">ProcessorResponse</span>] = (node ? <span class="hljs-type">GetFibonacci</span>(n)).mapTo[<span class="hljs-type">ProcessorResponse</span>]
                  onSuccess(processFuture) { response =&gt;
                    complete(<span class="hljs-type">StatusCodes</span>.<span class="hljs-type">OK</span>, response)
                  }
                }
              )
            }
          }
        )
      }
    )
  }
</code></pre>
<p>It responds with a <code>ProcessorResponse</code> containing the result, along with the id of the node where the computation took place.</p>
<h4 id="heading-cluster-configuration">Cluster Configuration</h4>
<p>Once we have all our actors, we need to configure the system to run as a cluster! The <code>application.conf</code> file is where the magic takes place. I’m going to split it in pieces to present it better, but you can find the complete file <a target="_blank" href="https://github.com/elleFlorio/akka-cluster-playground/blob/master/src/main/resources/application.conf">here</a>.</p>
<p>Let’s start defining some useful variables.</p>
<pre><code>clustering {
  ip = <span class="hljs-string">"127.0.0.1"</span>
  ip = ${?CLUSTER_IP}

  port = <span class="hljs-number">2552</span>
  port = ${?CLUSTER_PORT}

  seed-ip = <span class="hljs-string">"127.0.0.1"</span>
  seed-ip = ${?CLUSTER_SEED_IP}

  seed-port = <span class="hljs-number">2552</span>
  seed-port = ${?CLUSTER_SEED_PORT}

  cluster.name = <span class="hljs-string">"cluster-playground"</span>
}
</code></pre><p>Here we are simply defining the ip and port of the nodes and the seed, as well as the cluster name. We set a default value, then we override it if a new one is specified. The configuration of the cluster is the following.</p>
<pre><code>akka {
  actor {
    provider = <span class="hljs-string">"cluster"</span>
    ...
    <span class="hljs-comment">/* router configuration */</span>
    ...
  }
  remote {
    log-remote-lifecycle-events = on
    netty.tcp {
      hostname = ${clustering.ip}
      port = ${clustering.port}
    }
  }
  cluster {
    seed-nodes = [
      <span class="hljs-string">"akka.tcp://"</span>${clustering.cluster.name}<span class="hljs-string">"@"</span>${clustering.seed-ip}<span class="hljs-string">":"</span>${clustering.seed-port}
    ]
    auto-down-unreachable-after = <span class="hljs-number">10</span>s
  }
}
...
<span class="hljs-comment">/* server vars */</span>
...
<span class="hljs-comment">/* cluster vars */</span>
}
</code></pre><p>Akka Cluster is build on top of Akka Remoting, so we need to configure it properly. First of all, we specify that we are going to use Akka Cluster saying that <code>provider = "cluster"</code>. Then we bind <code>cluster.ip</code> and <code>cluster.port</code> to the <code>hostname</code> and <code>port</code> of the <code>netty</code> web framework.</p>
<p>The cluster requires some seed nodes as its entry points. We set them in the <code>seed-nodes</code> array, in the format <code>akka.tcp://"{clustering.cluster.name}"@"{clustering.seed-ip}":”${clustering.seed-port}”</code>. Right now we have one seed node, but we may add more later.</p>
<p>The <code>auto-down-unreachable-after</code> property sets a member as down after it is unreachable for a period of time. This should be used only during development, as explained in the <a target="_blank" href="https://doc.akka.io/docs/akka/2.5/cluster-usage.html#auto-downing-do-not-use-">official documentation</a>.</p>
<p>Ok, the cluster is configured, we can move to the next step: Dockerization and deployment!</p>
<h4 id="heading-dockerization-and-deployment">Dockerization and deployment</h4>
<p>To create the Docker container of our node we can use <a target="_blank" href="https://www.scala-sbt.org/sbt-native-packager">sbt-native-packager</a>. Its installation is easy: add <code>addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.15")</code> to the <code>plugin.sbt</code> file in the <code>project/</code> folder. This amazing tool has a plugin for the creation of Docker containers. it allows us to configure the properties of our Dockerfile in the <code>build.sbt</code> file.</p>
<pre><code><span class="hljs-comment">// other build.sbt properties</span>

enablePlugins(JavaAppPackaging)
enablePlugins(DockerPlugin)
enablePlugins(AshScriptPlugin)

mainClass <span class="hljs-keyword">in</span> Compile := Some(<span class="hljs-string">"com.elleflorio.cluster.playground.Server"</span>)
<span class="hljs-attr">dockerBaseImage</span> := <span class="hljs-string">"java:8-jre-alpine"</span>
version <span class="hljs-keyword">in</span> Docker := <span class="hljs-string">"latest"</span>
<span class="hljs-attr">dockerExposedPorts</span> := Seq(<span class="hljs-number">8000</span>)
<span class="hljs-attr">dockerRepository</span> := Some(<span class="hljs-string">"elleflorio"</span>)
</code></pre><p>Once we have setup the plugin, we can create the docker image running the command <code>sbt docker:publishLocal</code>. Run the command and taste the magic… ?</p>
<p>We have the Docker image of our node, now we need to deploy it and check that everything works fine. The easiest way is to create a <code>docker-compose</code> file that will spawn a seed and a couple of other nodes.</p>
<pre><code class="lang-yml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3.5'</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">cluster-network:</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">seed:</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">cluster-network</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">elleflorio/akka-cluster-playground</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">'2552:2552'</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">'8000:8000'</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">SERVER_IP:</span> <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span>
      <span class="hljs-attr">CLUSTER_IP:</span> <span class="hljs-string">seed</span>
      <span class="hljs-attr">CLUSTER_SEED_IP:</span> <span class="hljs-string">seed</span>

  <span class="hljs-attr">node1:</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">cluster-network</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">elleflorio/akka-cluster-playground</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">'8001:8000'</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">SERVER_IP:</span> <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span>
      <span class="hljs-attr">CLUSTER_IP:</span> <span class="hljs-string">node1</span>
      <span class="hljs-attr">CLUSTER_PORT:</span> <span class="hljs-number">1600</span>
      <span class="hljs-attr">CLUSTER_SEED_IP:</span> <span class="hljs-string">seed</span>
      <span class="hljs-attr">CLUSTER_SEED_PORT:</span> <span class="hljs-number">2552</span>

  <span class="hljs-attr">node2:</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">cluster-network</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">elleflorio/akka-cluster-playground</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">'8002:8000'</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">SERVER_IP:</span> <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span>
      <span class="hljs-attr">CLUSTER_IP:</span> <span class="hljs-string">node2</span>
      <span class="hljs-attr">CLUSTER_PORT:</span> <span class="hljs-number">1600</span>
      <span class="hljs-attr">CLUSTER_SEED_IP:</span> <span class="hljs-string">seed</span>
      <span class="hljs-attr">CLUSTER_SEED_PORT:</span> <span class="hljs-number">2552</span>
</code></pre>
<p>I won’t spend time going through it, since it is quite simple.</p>
<h4 id="heading-lets-run-it">Let’s run it!</h4>
<p>Time to test our work! Once we run the <code>docker-compose up</code> command, we will have a cluster of three nodes up and running. The <code>seed</code> will respond to requests at port <code>:8000</code>, while <code>node1</code> and <code>node2</code> at port <code>:8001</code> and <code>:8002</code>. Play a bit with the various endpoints. You will see that the requests for a Fibonacci number will be computed by a different node each time, following a round-robin policy. That’s good, we are proud of our work and can get out for a beer to celebrate! ?</p>
<h4 id="heading-conclusion">Conclusion</h4>
<p>We are done here! We learned a lot of things in these ten minutes:</p>
<ul>
<li>What Akka Cluster is and what can do for us.</li>
<li>How to create a distributed application with it.</li>
<li>How to configure a Group Router for load-balancing in the cluster.</li>
<li>How to Dockerize everything and deploy it using docker-compose.</li>
</ul>
<p>You can find the complete application in my <a target="_blank" href="https://github.com/elleFlorio/akka-cluster-playground">GitHub repo</a>. Feel free to contribute or play with it as you like! ?</p>
<p>See you! ?</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Akka HTTP routing ]]>
                </title>
                <description>
                    <![CDATA[ By Miguel Lopez Akka HTTP’s routing DSL might seem complicated at first, but once you get the hang of it you’ll see how powerful it is. In this tutorial we will focus on creating routes and their structure. We won’t cover parsing to and from JSON, we... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-akka-http-routing-697b00399cad/</link>
                <guid isPermaLink="false">66c3440e4f1fc448a3678f9b</guid>
                
                    <category>
                        <![CDATA[ Akka ]]>
                    </category>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scala ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 19 Dec 2018 19:17:41 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*SLnwW0f177L3NOX0V88Z0g.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Miguel Lopez</p>
<p>Akka HTTP’s routing DSL might seem complicated at first, but once you get the hang of it you’ll see how powerful it is.</p>
<p>In this tutorial we will focus on creating routes and their structure. We won’t cover parsing to and from JSON, we have <a target="_blank" href="https://www.codemunity.io/tutorials/akka-http-json-circe/">other tutorials</a> that cover that topic.</p>
<h3 id="heading-what-are-directives">What are directives?</h3>
<p>One of the first concepts we’ll find when learning server-side Akka HTTP (there’s a client-side library as well) is <em>directives</em>.</p>
<p>So, what are they?</p>
<p>You can think of them as building blocks, Lego pieces if you will, that you can use to construct your routes. They are composable, which means we can create directives on top of other directives.</p>
<p>If you want a more in-depth reading, feel free to check out <a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/index.html">Akka HTTP’s official documentation</a>.</p>
<p>Before moving on, let’s discuss what we’ll build.</p>
<h3 id="heading-blog-like-api">Blog-like API</h3>
<p>We’ll create a sample of a public facing API for a blog, where we will allow users to:</p>
<ul>
<li>query a list of tutorials</li>
<li>query a single tutorial by ID</li>
<li>query the list of comments in a tutorial</li>
<li>add comments to a tutorial</li>
</ul>
<p>The endpoints will be:</p>
<pre><code>- List all tutorials GET /tutorials
</code></pre><pre><code>- Create a tutorial GET /tutorials/:id
</code></pre><pre><code>- Get all comments <span class="hljs-keyword">in</span> a tutorial GET /tutorials/:id/comments
</code></pre><pre><code>- Add a comment to a tutorial POST /tutorials/:id/comments
</code></pre><p>We will only implement the endpoints, no logic in them. This way we’ll learn how to create this structure and the common pitfalls when starting with Akka HTTP.</p>
<h3 id="heading-project-setup">Project Setup</h3>
<p>We’ve created a <a target="_blank" href="https://github.com/Codemunity/akka-http-routing-primer">repo</a> for this tutorial, in it you’ll find a branch per each section that requires coding. Feel free to clone it and use it as a base project or even just change between branches to look at the differences.</p>
<p>Otherwise, create a new SBT project, and then add the dependencies in the <code>build.sbt</code> file:</p>
<pre><code>name := <span class="hljs-string">"akkahttp-routing-dsl"</span>
</code></pre><pre><code>version := <span class="hljs-string">"0.1"</span>
</code></pre><pre><code>scalaVersion := <span class="hljs-string">"2.12.7"</span>
</code></pre><pre><code>val akkaVersion = <span class="hljs-string">"2.5.17"</span> val akkaHttpVersion = <span class="hljs-string">"10.1.5"</span>
</code></pre><pre><code>libraryDependencies ++= Seq(   <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-actor"</span> % akkaVersion,   <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-testkit"</span> % akkaVersion % Test,  <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-stream"</span> % akkaVersion,   <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-stream-testkit"</span> % akkaVersion % Test,   <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-http"</span> % akkaHttpVersion,   <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-http-testkit"</span> % akkaHttpVersion % Test,      <span class="hljs-string">"org.scalatest"</span> %% <span class="hljs-string">"scalatest"</span> % <span class="hljs-string">"3.0.5"</span> % Test )
</code></pre><p>We added Akka HTTP and its dependencies, Akka Actor and Streams. And we will also use Scalatest for testing.</p>
<h3 id="heading-listing-all-the-tutorials">Listing all the tutorials</h3>
<p>We’ll take a TDD approach to build our directive hierarchy, creating the tests first to make sure when don’t break our routes when adding others. Taking this approach is quite helpful when starting with Akka HTTP.</p>
<p>Let’s start with our route to listing all the tutorials. Create a new file under <code>src/test/scala</code> (if the folders don't exist, create them) named <code>RouterSpec</code>:</p>
<pre><code><span class="hljs-keyword">import</span> akka.http.scaladsl.testkit.ScalatestRouteTest <span class="hljs-keyword">import</span> org.scalatest.{Matchers, WordSpec}
</code></pre><pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RouterSpec</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WordSpec</span> <span class="hljs-title">with</span> <span class="hljs-title">Matchers</span> <span class="hljs-title">with</span> <span class="hljs-title">ScalatestRouteTest</span> </span>{
</code></pre><pre><code>}
</code></pre><p><code>WordSpec</code> and <code>Matchers</code> are provided by Scalatest, and we'll use them to structure our tests and assertions. <code>ScalatestRouteTest</code> is a trait provided by Akka HTTP's test kit, it will allow us to test our routes in a convenient way. Let's see how we can accomplish that.</p>
<p>Because we’re using <a target="_blank" href="http://www.scalatest.org/at_a_glance/WordSpec">Scalatest’s WordSpec</a>, we’ll start by creating a scope for our <code>Router</code> object that we will create soon and the first test:</p>
<pre><code><span class="hljs-string">"A Router"</span> should {   <span class="hljs-string">"list all tutorials"</span> <span class="hljs-keyword">in</span> {   } }
</code></pre><p>Next, we want to make sure can send a GET request to the path <code>/tutorials</code> and get the response we expect, let's see how we can accomplish that:</p>
<pre><code>Get(<span class="hljs-string">"/tutorials"</span>) ~&gt; Router.route ~&gt; check {   status shouldBe StatusCodes.OK   responseAs[<span class="hljs-built_in">String</span>] shouldBe <span class="hljs-string">"all tutorials"</span> }
</code></pre><p>It won’t even compile because we haven’t created our <code>Router</code> object. Let's do that now.</p>
<p>Create a new Scala object under <code>src/main/scala</code> named <code>Router</code>. In it we will create a method that will return a <code>Route</code>:</p>
<pre><code><span class="hljs-keyword">import</span> akka.http.scaladsl.server.Route
</code></pre><pre><code>object Router {
</code></pre><pre><code>  def route: Route = ???
</code></pre><pre><code>}
</code></pre><p>Don’t worry too much about the <code>???</code>, it's just a placeholder to avoid compilation errors temporarily. However, if that code is executed, it'll throw a <code>NotImplementedError</code> as we'll see soon.</p>
<p>Now that our tests and project are compiling, let’s run the tests (Right-click the spec and “Run ‘RouterSpec’”).</p>
<p>The test failed with the exception we were expecting, we haven’t implemented our routes. Let’s begin!</p>
<h3 id="heading-creating-the-listing-route">Creating the listing route</h3>
<p>By looking into the <a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/index.html#composing-directives">official documentation</a> we see that the route begins with the <code>path</code> directive. Let's mimic what they're doing and build our route:</p>
<pre><code><span class="hljs-keyword">import</span> akka.http.scaladsl.server.{Directives, Route}
</code></pre><pre><code>object Router <span class="hljs-keyword">extends</span> Directives {
</code></pre><pre><code>  def route: Route = path(<span class="hljs-string">"tutorials"</span>) {    get {      complete(<span class="hljs-string">"all tutorials"</span>)    }  }}
</code></pre><p>Seems reasonable, let’s run our spec. And it passes, great!</p>
<p>For reference, our entire <code>RouterSpec</code> now looks like:</p>
<pre><code><span class="hljs-keyword">import</span> akka.http.scaladsl.model.StatusCodesimport akka.http.scaladsl.testkit.ScalatestRouteTestimport org.scalatest.{Matchers, WordSpec}<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RouterSpec</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WordSpec</span> <span class="hljs-title">with</span> <span class="hljs-title">Matchers</span> <span class="hljs-title">with</span> <span class="hljs-title">ScalatestRouteTest</span> </span>{  <span class="hljs-string">"A Router"</span> should {    <span class="hljs-string">"list all tutorials"</span> <span class="hljs-keyword">in</span> {      Get(<span class="hljs-string">"/tutorials"</span>) ~&gt; Router.route ~&gt; check {        status shouldBe StatusCodes.OK        responseAs[<span class="hljs-built_in">String</span>] shouldBe <span class="hljs-string">"all tutorials"</span>      }    }  }}
</code></pre><h3 id="heading-getting-a-single-tutorial-by-id">Getting a single tutorial by ID</h3>
<p>Next, we will allow our users to retrieve a single tutorial.</p>
<p>Let’s add a test for our new route:</p>
<pre><code><span class="hljs-string">"return a single tutorial by id"</span> <span class="hljs-keyword">in</span> {  Get(<span class="hljs-string">"/tutorials/hello-world"</span>) ~&gt; Router.route ~&gt; check {    status shouldBe StatusCodes.OK    responseAs[<span class="hljs-built_in">String</span>] shouldBe <span class="hljs-string">"tutorial hello-world"</span>  }}
</code></pre><p>We expect to get back a message that includes the tutorial ID.</p>
<p>The test will fail because we haven’t created our route, let’s do that now.</p>
<p>From the same <a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/index.html#composing-directives">resource</a> we used earlier to base our route on, we can see how we can place multiple directives at the same level in the hierarchy using the <code>~</code> directive.</p>
<p>We will have to nest <code>path</code> directives because need another segment after the <code>/tutorials</code> route for the tutorial ID. In the documentation they use <code>IntNumber</code> to extract a number from the path, but we'll use a string and for that we use can <code>Segment</code> instead.</p>
<p>Our route looks like:</p>
<pre><code>def route: Route = path(<span class="hljs-string">"tutorials"</span>) {  get {    complete(<span class="hljs-string">"all tutorials"</span>)  } ~ path(Segment) { <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span>    get {      complete(s<span class="hljs-string">"tutorial $id"</span>)    }  }}
</code></pre><p>Let’s run the tests. And you should get a similar error:</p>
<pre><code>Request was rejectedScalaTestFailureLocation: RouterSpec at (RouterSpec.scala:<span class="hljs-number">17</span>)org.scalatest.exceptions.TestFailedException: Request was rejected
</code></pre><p>What’s going on?!</p>
<p>Well, a request is rejected when it doesn’t match our directive hierarchy. This is one of the things that got me when starting.</p>
<p>Now is probably a good time to look into how these directives match the incoming request as it goes through the hierarchy.</p>
<p>Different directives will match different aspects of an incoming request, we’ve seen <code>path</code> and <code>get</code>, one matches the URL of the request and the other the method. If a request matches a directive it will go inside it, if it doesn't it will continue to the next one. This also tells us that order matters. If it doesn't match any directive the request is rejected.</p>
<p>Now that we now that our request is not matching our directives, let’s start looking into why.</p>
<p>If we look the documentation for the <code>path</code> directive (Cmd + Click on Mac) we'll find:</p>
<pre><code><span class="hljs-comment">/** * Applies the given [[PathMatcher]] to the remaining unmatched path after consuming a leading slash. * The matcher has to match the remaining path completely. * If matched the value extracted by the [[PathMatcher]] is extracted on the directive level. * * <span class="hljs-doctag">@group </span>path */</span>
</code></pre><p>So, the <code>path</code> directive has to match exactly the path, meaning our first <code>path</code> directive will only match <code>/tutorials</code> and never <code>/tutorials/:id</code>.</p>
<p>In the same <code>PathDirectives</code> trait that contains the <code>path</code> directive we can see another directive named <code>pathPrefix</code>:</p>
<pre><code><span class="hljs-comment">/** * Applies the given [[PathMatcher]] to a prefix of the remaining unmatched path after consuming a leading slash. * The matcher has to match a prefix of the remaining path. * If matched the value extracted by the PathMatcher is extracted on the directive level. * * <span class="hljs-doctag">@group </span>path */</span>
</code></pre><p><code>pathPrefix</code> matches only a prefix and removes it. Sounds like this is what we're looking for, let's update our routes:</p>
<pre><code>def route: Route = pathPrefix(<span class="hljs-string">"tutorials"</span>) {  get {    complete(<span class="hljs-string">"all tutorials"</span>)  } ~ path(Segment) { <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span>    get {      complete(s<span class="hljs-string">"tutorial $id"</span>)    }  }}
</code></pre><p>Run the tests, and… we get another error. ?</p>
<pre><code><span class="hljs-string">"[all tutorials]"</span> was not equal to <span class="hljs-string">"[tutorial hello-world]"</span>ScalaTestFailureLocation: RouterSpec at (RouterSpec.scala:<span class="hljs-number">18</span>)Expected :<span class="hljs-string">"[tutorial hello-world]"</span>Actual   :<span class="hljs-string">"[all tutorials]"</span>
</code></pre><p>Looks like our request matched the first <code>get</code> directive. It now matches the <code>pathPrefix</code>, and because it also is a GET request it will match the first <code>get</code> directive. Order matters.</p>
<p>There are a couple of things we can do. The simplest solution would be to move the first <code>get</code> request to the end of the hierarchy, however, we would have to remember this or document it. Not ideal.</p>
<p>Personally, I prefer avoiding such solutions and instead make the intend clear through code. If we look in the <code>PathDirectives</code> trait from earlier, we'll find a directive called <code>pathEnd</code>:</p>
<pre><code><span class="hljs-comment">/** * Rejects the request if the unmatchedPath of the [[RequestContext]] is non-empty, * or said differently: only passes on the request to its inner route if the request path * has been matched completely. * * <span class="hljs-doctag">@group </span>path */</span>
</code></pre><p>That’s exactly what we want, so let’s wrap our first <code>get</code> directive with <code>pathEnd</code>:</p>
<pre><code>def route: Route = pathPrefix(<span class="hljs-string">"tutorials"</span>) {  pathEnd {    get {      complete(<span class="hljs-string">"all tutorials"</span>)    }  } ~ path(Segment) { <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span>    get {      complete(s<span class="hljs-string">"tutorial $id"</span>)    }  }}
</code></pre><p>Run the tests again, and… finally, the tests are passing! ?</p>
<h3 id="heading-listing-all-comments-in-a-tutorial">Listing all comments in a tutorial</h3>
<p>Let’s put into practice what we learned about nesting routes by taking it a bit further.</p>
<p>First the test:</p>
<pre><code><span class="hljs-string">"list all comments of a given tutorial"</span> <span class="hljs-keyword">in</span> {  Get(<span class="hljs-string">"/tutorials/hello-world/comments"</span>) ~&gt; Router.route ~&gt; check {    status shouldBe StatusCodes.OK    responseAs[<span class="hljs-built_in">String</span>] shouldBe <span class="hljs-string">"comments for the hello-world tutorial"</span>  }}
</code></pre><p>It’s a similar case as before: we know we’ll need to place a route next to another one, which means we need to:</p>
<ul>
<li>change the <code>path(Segmenter)</code> to <code>pathPrefix(Segmenter)</code></li>
<li>wrap the first <code>get</code> with the <code>pathEnd</code> directive</li>
<li>place the new route next to the <code>pathEnd</code></li>
</ul>
<p>Our routes end up looking like:</p>
<pre><code>def route: Route = pathPrefix(<span class="hljs-string">"tutorials"</span>) {  pathEnd {    get {      complete(<span class="hljs-string">"all tutorials"</span>)    }  } ~ pathPrefix(Segment) { <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span>    pathEnd {      get {        complete(s<span class="hljs-string">"tutorial $id"</span>)      }    } ~ path(<span class="hljs-string">"comments"</span>) {      get {        complete(s<span class="hljs-string">"comments for the $id tutorial"</span>)      }    }  }}
</code></pre><p>Run the tests, and they should pass! ?</p>
<h3 id="heading-adding-comments-to-a-tutorial">Adding comments to a tutorial</h3>
<p>Our last endpoint is similar to the previous, but it will match POST requests. We’ll use this example to see the difference between implementing and testing a GET request versus a POST request.</p>
<p>The test:</p>
<pre><code><span class="hljs-string">"add comments to a tutorial"</span> <span class="hljs-keyword">in</span> {  Post(<span class="hljs-string">"/tutorials/hello-world/comments"</span>, <span class="hljs-string">"new comment"</span>) ~&gt; Router.route ~&gt; check {    status shouldBe StatusCodes.OK    responseAs[<span class="hljs-built_in">String</span>] shouldBe <span class="hljs-string">"added the comment 'new comment' to the hello-world tutorial"</span>  }}
</code></pre><p>We’re using the <code>Post</code> method instead of the <code>Get</code> we've been using, and we're giving it an additional parameter which is the request body. The rest is familiar to us now.</p>
<p>To implement our last route, we can refer to the <a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/index.html#longer-example">documentation</a> and look at how it’s usually done.</p>
<p>We have a <code>post</code> directive just as we have a <code>get</code> one. To extract the request body we need two directives, <code>entity</code> and <code>as</code>, to which we supply the type we expect. In our case it's a string.</p>
<p>Let’s give that a try:</p>
<pre><code>post {  entity(<span class="hljs-keyword">as</span>[<span class="hljs-built_in">String</span>]) { <span class="hljs-function"><span class="hljs-params">comment</span> =&gt;</span>    complete(s<span class="hljs-string">"added the comment '$comment' to the $id tutorial"</span>)  }}
</code></pre><p>Looks reasonable. We extract the request body as a string and use it in our response. Let’s add it to our <code>route</code> method next to the previous route we worked on:</p>
<pre><code>def route: Route = pathPrefix(<span class="hljs-string">"tutorials"</span>) {  pathEnd {    get {      complete(<span class="hljs-string">"all tutorials"</span>)    }  } ~ pathPrefix(Segment) { <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span>    pathEnd {      get {        complete(s<span class="hljs-string">"tutorial $id"</span>)      }    } ~ path(<span class="hljs-string">"comments"</span>) {      get {        complete(s<span class="hljs-string">"comments for the $id tutorial"</span>)      } ~ post {        entity(<span class="hljs-keyword">as</span>[<span class="hljs-built_in">String</span>]) { <span class="hljs-function"><span class="hljs-params">comment</span> =&gt;</span>          complete(s<span class="hljs-string">"added the comment '$comment' to the $id tutorial"</span>)        }      }    }  }}
</code></pre><p><em>If you’d like to learn how to parse Scala classes to and from JSON <a target="_blank" href="https://www.codemunity.io/tutorials/akka-http-json-circe/">we’ve got tutorials for that as well</a>.</em></p>
<p>Run the tests, and they should all pass.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Akka HTTP’s routing DSL might seem confusing at first, but after overcoming some bumps it just clicks. After a while it’ll come naturally and it can be very powerful.</p>
<p>We learned how to structure our routes, but more importantly, we learned how to create that structure guided by tests which will make sure we don’t break them at some point in the future.</p>
<p>Even though we only worked on four endpoints, we ended up with a somewhat complicated and deep structure. Stay tuned and we’ll explore different ways to simplify our routes and make them more manageable!</p>
<p><a target="_blank" href="http://link.codemunity.io/website-akka-http-quickstart">Learn how to build REST APIs with Scala and Akka HTTP with this step-by-step free course!</a></p>
<p><em>Originally published at <a target="_blank" href="https://www.codemunity.io/tutorials/akka-http-routing-primer/">www.codemunity.io</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ If you’re still using Synchronized, you should try Akka Actor instead — here’s why ]]>
                </title>
                <description>
                    <![CDATA[ By Martin Budi Synchronized is Java’s traditional concurrency mechanism. Although it is probably not something we see often these days, it is still fueling many libraries. The problem is, synchronized is both blocking and complicated. In this article... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/still-using-synchronized-try-akka-actor-instead-ac2f2b22a9ed/</link>
                <guid isPermaLink="false">66c35fddc337fbd10a4b596d</guid>
                
                    <category>
                        <![CDATA[ Akka ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scala ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 11 Sep 2018 06:15:28 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*qep0tBNdjhQzyunssu4jvw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Martin Budi</p>
<p><em>Synchronized</em> is Java’s traditional concurrency mechanism. Although it is probably not something we see often these days, it is still fueling many libraries. The problem is, synchronized is both blocking and complicated. In this article, I’d like to illustrate the issue in a simple way and my reasoning to move to Akka Actor for better and easier concurrency.</p>
<p>Consider this simple code:</p>
<pre><code class="lang-java">  <span class="hljs-keyword">int</span> x; 

 <span class="hljs-keyword">if</span> (x &gt; <span class="hljs-number">0</span>) {
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
 } <span class="hljs-keyword">else</span> {
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
 }
</code></pre>
<p>So return true if <em>x</em> is positive. Simple.</p>
<p>Next, consider this even simpler code:</p>
<pre><code class="lang-java">x++;
</code></pre>
<p>Yes, a counter. Very simple right?</p>
<p>However, all these codes can blow up spectacularly in a multi-threaded environment.</p>
<p>In the first example, true or false isn’t determined by the value of x. It is actually determined by the if-test. So, if another thread changes x to a negative right after the first thread passed the if-test, we’d still get true even if x is no longer positive.</p>
<p>The second example is pretty deceptive. Although it is just one line, there are actually three operations: reading <em>x</em>, incrementing it and putting the updated value back. If two threads run at exactly the same time, the update might be lost.</p>
<p>When we have different threads simultaneously accessing and modifying a variable, we have a race condition. If we just want to build a counter, Java provides thread-safe Atomic Variables, among them Atomic Integer which we can use for this purpose. Atomic Integer, however, only works on single variables. How do we make several operations atomic?</p>
<p>By using <em>synchronized</em> block. First, let’s take a look at a more elaborate example.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> x; 
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(<span class="hljs-keyword">int</span> deduct)</span></span>{
    <span class="hljs-keyword">int</span> balance = x - deduct; 
    <span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">0</span>) {
      x = balance;
      <span class="hljs-keyword">return</span> deduct;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    }
}
</code></pre>
<p>This is a very basic cash withdraw method. It also happens to be dangerous. Two threads running at the same time may cause the bank to issue two withdrawals even if the balance is no longer enough. Now let’s see how it works with synchronized block:</p>
<pre><code class="lang-java"><span class="hljs-keyword">volatile</span> <span class="hljs-keyword">int</span> x;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(<span class="hljs-keyword">int</span> deduct)</span></span>{
  <span class="hljs-keyword">synchronized</span>(<span class="hljs-keyword">this</span>){
    <span class="hljs-keyword">int</span> balance = x - deduct; 
    <span class="hljs-keyword">if</span> (balance &gt; <span class="hljs-number">0</span>) {
      x = balance;
      <span class="hljs-keyword">return</span> deduct;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    }
  }
}
</code></pre>
<p>The idea of synchronized block is simple. One thread enters it and locks it, while other threads wait outside. The lock is an object, in our case <em>this</em>. After it’s done, the lock is released and passed to another thread which then does the same thing. Also, note the esoteric keyword <em>volatile</em> which is needed to prevent the thread from using the local CPU cache of <em>x.</em></p>
<p>Now with the threads untangled, the bank won’t accidentally issue unfunded withdrawals. However, this structure tends to grow complex with more blocks and more locks. Dealing with multiple locks is particularly risky. The blocks might inadvertently hold the key for each other and end up locking the entire app. And on top of it, we have an efficiency issue. Remember that while a thread works inside, all the other threads wait outside. And waiting threads are well … waiting. They don’t do anything else but wait.</p>
<p>So instead of doing such mechanism, why not just drop the job in a queue? To better visualize it, imagine an email system. When you send an email, you drop the email in the recipient’s mailbox. You don’t wait around until the person reads it.</p>
<p>These are the basics of the Actor model and Akka framework in general.</p>
<p>Actor encapsulates state and behavior. Unlike OOP’s encapsulation, though, actors do not expose their state and behavior at all. The only way for an actor to communicate with each other is by exchanging messages. Incoming messages are dropped in a mailbox and digested in first-in-first-out order. Here’s a reworked sample in Akka and Scala.</p>
<pre><code class="lang-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Withdraw</span>(<span class="hljs-params">deduct: <span class="hljs-type">Int</span></span>)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReplicaActor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{
  <span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span></span>: <span class="hljs-type">Receive</span> = {
    <span class="hljs-keyword">case</span> <span class="hljs-type">Withdraw</span>(deduct) =&gt; <span class="hljs-keyword">val</span> r = withdraw(deduct)
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BossActor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Actor</span> </span>{
  <span class="hljs-keyword">var</span> replica = context.actorOf(<span class="hljs-type">Props</span>[<span class="hljs-type">ReplicaActor</span>])
  replica ! <span class="hljs-type">Withdraw</span>(<span class="hljs-number">6</span>)
  replica ! <span class="hljs-type">Withdraw</span>(<span class="hljs-number">9</span>)   
}
</code></pre>
<p>We have a ReplicaActor that does the work and BossActor that orders the replica around. First, notice the ! sign or <em>tell</em>. This is one of two methods (the other is <em>ask</em>) for an actor to asynchronously send a message to another actor. <em>tell</em> in particular does so without waiting for a reply. So the boss tells the replica to do two withdraw orders and immediately leaves. These messages arrive in the replica's <em>receive</em> where each one is popped and matched with the corresponding handler. In this case, <em>Withdraw</em> executes the <em>withdraw</em> method from the previous example and deducts the requested amount from state x. After it is done, the actor proceeds to the next message in the queue.</p>
<p>So what do we get here? For one, we no longer need to worry about locking and working with atomic/concurrent types. Actor’s encapsulation and queuing mechanism already guarantee thread-safety. And there is no more waiting since threads just drop the message and return. Results can be delivered later with <em>ask</em> or <em>tell</em>. It’s simple and sane.</p>
<p>Akka is based on JVM and available in both Scala and Java. Although this article isn’t debating Java vs Scala, Scala’s pattern matching and functional programming would be very useful in managing Actor’s data messaging. At the very least it can help you write shorter code by avoiding Java’s brackets and semicolons.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How you can build a Hello World API with Scala and Akka HTTP ]]>
                </title>
                <description>
                    <![CDATA[ By Miguel Lopez Yes, it’s still a thing. _Photo by [Unsplash](https://unsplash.com/photos/B3l0g6HLxr8?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" title="">Blake Connally on <a href="https://unsp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-you-can-build-a-hello-world-api-with-scala-and-akka-http-55e2ff67d70d/</link>
                <guid isPermaLink="false">66c356af0cede4e9b1329c78</guid>
                
                    <category>
                        <![CDATA[ Akka ]]>
                    </category>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scala ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Aug 2018 16:27:50 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*9wHrewC1Dyf2Au_qEqwWcg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Miguel Lopez</p>
<h4 id="heading-yes-its-still-a-thing"><em>Yes, it’s still a thing.</em></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ws5H0lYzh1Kol7Aum0Up1pW9eiDRpXHoKkcT" alt="Image" width="800" height="533" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/B3l0g6HLxr8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;Blake Connally on &lt;a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<p>Akka is a popular actor-based toolkit for building concurrent and distributed applications in the JVM. These applications mostly use Scala or Java.</p>
<p>It has several modules that help to build such applications, and Akka HTTP is one of them.</p>
<p>Akka HTTP has both client-side and server-side utilities. We will focus on the server in this tutorial.</p>
<p>You should be familiar with Scala, and you should have SBT and IntelliJ setup and installed. If that’s not the case, check the <a target="_blank" href="https://docs.scala-lang.org/getting-started-intellij-track/getting-started-with-scala-in-intellij.html">official docs</a>.</p>
<p>Without further ado, let’s build a hello world API using Scala and Akka HTTP!</p>
<h3 id="heading-project-setup">Project setup</h3>
<p>Feel free to clone the <a target="_blank" href="https://github.com/Codemunity/akkahttp-quickstart">repo</a>, make sure you are using the branch <code>2.1-review-project</code>.</p>
<p>If not, we’ll be using sbt <code>1.1.6</code> and Scala <code>2.12.6</code> . Check your <code>build.properties</code> and <code>build.sbt</code> files to make sure the versions there match these.</p>
<p>Let’s start by adding the required dependencies. Because Akka HTTP depends on actors and streams, we’ll need to add those libraries as well.</p>
<p>Add the following snippet at the end of your <code>build.sbt</code> file:</p>
<pre><code>libraryDependencies ++= Seq(  <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-actor"</span> % <span class="hljs-string">"2.5.13"</span>,  <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-stream"</span> % <span class="hljs-string">"2.5.13"</span>,  <span class="hljs-string">"com.typesafe.akka"</span> %% <span class="hljs-string">"akka-http"</span> % <span class="hljs-string">"10.1.3"</span>,)
</code></pre><p>If you’re prompted to enable auto-import, do it. Otherwise you can open a terminal and <code>cd</code> into the root directory of your project. Then run <code>sbt update</code> to get the dependencies.</p>
<p>Auto-import will make sure to update your project every time certain files are updated, including the <code>build.sbt</code> file.</p>
<h3 id="heading-instantiate-dependencies">Instantiate dependencies</h3>
<p>Let’s create a Scala object under “src/main/scala” named <code>Server</code>. We will start by instantiating the dependencies required to create a server with Akka HTTP.</p>
<p>First, the object will extend the <code>App</code> trait:</p>
<pre><code>object Server <span class="hljs-keyword">extends</span> App {}
</code></pre><p>This will allow our <code>Server</code> object to be runnable.</p>
<p>We will need a host and a port to bind the server, so let’s add them now:</p>
<pre><code>val host = <span class="hljs-string">"0.0.0.0"</span>val port = <span class="hljs-number">9000</span>
</code></pre><p>Because Akka HTTP uses Akka actors and streams underneath, we will need to supply their dependencies as well:</p>
<pre><code>implicit val system: ActorSystem = ActorSystem(<span class="hljs-string">"helloworld"</span>)implicit val executor: ExecutionContext = system.dispatcherimplicit val materializer: ActorMaterializer = ActorMaterializer()
</code></pre><p>Even though you don’t need to know what they do to start developing Akka HTTP applications, it’s always good to be aware of what they’re for.</p>
<p>An <code>ActorSystem</code> is used to manage actors. It is used for creating and looking them up. Actors in the same system typically share the same config.</p>
<p>The <code>ExecutionContext</code> is in charge of executing <code>Future</code> s. It knows where and how it should execute them, for example in a thread pool.</p>
<p>And finally, an <code>ActorMaterializer</code> is in charge of running streams.</p>
<p>With that done, we can create our hello route!</p>
<h3 id="heading-create-the-route">Create the route</h3>
<p>To create our route, we will use Akka HTTP’s routing DSL. It is based on “layers” of what’s called a directive. For an overview, feel free to browse their <a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/overview.html">official docs</a>.</p>
<p>Add the route below the dependencies:</p>
<pre><code>def route = path(<span class="hljs-string">"hello"</span>) {  get {    complete(<span class="hljs-string">"Hello, World!"</span>)  }}
</code></pre><p>We have a first layer, where we try to match the incoming request’s path as “/hello”. If it doesn’t match it will be rejected.</p>
<p>If it matches it will try to match inner “<a target="_blank" href="https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/index.html">directives</a>”. In our case we are matching GET requests. We complete the request/response cycle with a “Hello, World” message.</p>
<h3 id="heading-start-the-server">Start the server</h3>
<p>With our route created, all we need to do is start the server:</p>
<pre><code>Http().bindAndHandle(route, host, port)
</code></pre><p>We are binding our route to the given host and port using the Akka HTTP <code>Http</code> object.</p>
<p>To run our <code>Server</code> object, you can right-click it and hit <em>Run ‘Server’</em>.</p>
<p>Give it a couple of seconds to compile, then go to a browser. Navigate to <code>http://localhost:9000/hello</code> and you should see our “Hello, World!” message.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/EZYjgm5uULRp-qqC1upw4Q8kGcDad7q4BeXN" alt="Image" width="800" height="461" loading="lazy"></p>
<p>Cool, isn’t it?</p>
<h3 id="heading-logging">Logging</h3>
<p>Before wrapping up this tutorial we’ll add basic logging to our server.</p>
<p>You might have noticed that there was no feedback when we ran our <code>Server</code> object. We have no clue whether it succeeded or failed.</p>
<p>We can only assume it worked because the application didn’t crash.</p>
<p>Let’s add some logging to it.</p>
<p>If you look into the <code>bindAndHandle</code> function from the <code>Http</code> object, it returns a future of <code>ServerBinding</code> . We can hook some logs into the future’s <code>onComplete</code> function.</p>
<p>Let’s do that:</p>
<pre><code>val bindingFuture = Http().bindAndHandle(route, host, port)bindingFuture.onComplete {  <span class="hljs-keyword">case</span> Success(serverBinding) =&amp;gt; println(s<span class="hljs-string">"listening to ${serverBinding.localAddress}"</span>)  <span class="hljs-keyword">case</span> Failure(error) =&gt; println(s<span class="hljs-string">"error: ${error.getMessage}"</span>)}
</code></pre><p>Run the <code>Server</code> again, and this time you should see:</p>
<pre><code>listening to /<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">0</span>:<span class="hljs-number">9000</span>
</code></pre><h3 id="heading-wrapping-up">Wrapping up</h3>
<p>While using Scala and Akka HTTP is not the fastest way to develop APIs, it allows you to integrate other Akka modules, such as actors, streams, clusters, and more, making it easier to develop resilient and scalable systems.</p>
<p>Having said that, it’s good to keep in mind that developing an application using Scala and/or Akka doesn’t necessarily mean that it will be resilient and scalable. You’ll still need to perform work to accomplish that, but it’s easier than with other technologies.</p>
<p>If you liked Akka HTTP, we’ve got a free course that’ll quickstart your way into developing APIs with it. You’ll build an API for a Todo application, explained step by step. Check it out! ??</p>
<p><a target="_blank" href="http://link.codemunity.io/hw-akka-http-quickstart-course"><strong>Akka HTTP Quickstart</strong></a><br><a target="_blank" href="http://link.codemunity.io/hw-akka-http-quickstart-course">_Learn how to create web applications and APIs with Akka HTTP in this free course!_link.codemunity.io</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
