Akka api

Akka api DEFAULT

How you can build a Hello World API with Scala and Akka HTTP

by Miguel Lopez

Yes, it’s still a thing.

Akka is a popular actor-based toolkit for building concurrent and distributed applications in the JVM. These applications mostly use Scala or Java.

It has several modules that help to build such applications, and Akka HTTP is one of them.

Akka HTTP has both client-side and server-side utilities. We will focus on the server in this tutorial.

You should be familiar with Scala, and you should have SBT and IntelliJ setup and installed. If that’s not the case, check the official docs.

Without further ado, let’s build a hello world API using Scala and Akka HTTP!

Project setup

Feel free to clone the repo, make sure you are using the branch .

If not, we’ll be using sbt and Scala . Check your and files to make sure the versions there match these.

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.

Add the following snippet at the end of your file:

If you’re prompted to enable auto-import, do it. Otherwise you can open a terminal and into the root directory of your project. Then run to get the dependencies.

Auto-import will make sure to update your project every time certain files are updated, including the file.

Instantiate dependencies

Let’s create a Scala object under “src/main/scala” named . We will start by instantiating the dependencies required to create a server with Akka HTTP.

First, the object will extend the trait:

This will allow our object to be runnable.

We will need a host and a port to bind the server, so let’s add them now:

Because Akka HTTP uses Akka actors and streams underneath, we will need to supply their dependencies as well:

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.

An is used to manage actors. It is used for creating and looking them up. Actors in the same system typically share the same config.

The is in charge of executing s. It knows where and how it should execute them, for example in a thread pool.

And finally, an is in charge of running streams.

With that done, we can create our hello route!

Create the route

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 official docs.

Add the route below the dependencies:

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.

If it matches it will try to match inner “directives”. In our case we are matching GET requests. We complete the request/response cycle with a “Hello, World” message.

Start the server

With our route created, all we need to do is start the server:

We are binding our route to the given host and port using the Akka HTTP object.

To run our object, you can right-click it and hit Run ‘Server’.

Give it a couple of seconds to compile, then go to a browser. Navigate to and you should see our “Hello, World!” message.

Cool, isn’t it?

Logging

Before wrapping up this tutorial we’ll add basic logging to our server.

You might have noticed that there was no feedback when we ran our object. We have no clue whether it succeeded or failed.

We can only assume it worked because the application didn’t crash.

Let’s add some logging to it.

If you look into the function from the object, it returns a future of . We can hook some logs into the future’s function.

Let’s do that:

Run the again, and this time you should see:

Wrapping up

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.

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.

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! ??

Akka HTTP Quickstart
Learn how to create web applications and APIs with Akka HTTP in this free course!link.codemunity.io


If this article was helpful, tweet it.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Sours: https://www.freecodecamp.org/news/how-you-can-build-a-hello-world-api-with-scala-and-akka-http-55e2ff67d70d/

Build powerful concurrent & distributed applications more easily.

Akka.NET is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on .NET & Mono.

This community-driven port brings C# & F# developers the capabilities of the original Akka framework in Java/Scala.

Learn about Akka for the JVM here.

Simple Concurrency & Distribution

Asynchronous and Distributed by design. High-level abstractions like Actors and FSM.

High Performance

50 million msg/sec on a single machine. Small memory footprint; ~2.5 million actors per GB of heap.

Resilient by Design

Write systems that self-heal. Remote and/or local supervisor hierarchies.

Elastic & Decentralized

Adaptive load balancing, routing, partitioning and configuration-driven remoting.

Extensible

Use Akka.NET Extensions to adapt Akka to fit your needs.

Open Source

Akka.NET is released under the Apache 2 license



Actor Model

The Actor Model provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct concurrent and parallel systems.

Actors were defined in the 1973 paper by Carl Hewitt but have been popularized by the Erlang language, and used for example at Ericsson with great success to build highly concurrent and reliable telecom systems.

Read more

Distributed by Default

Everything in Akka.NET is designed to work in a distributed setting: all interactions of actors use purely message passing and everything is asynchronous.

This effort has been undertaken to ensure that all functions are available equally when running within a single process or on a cluster of hundreds of machines. The key for enabling this is to go from remote to local by way of optimization instead of trying to go from local to remote by way of generalization. See this classic paper for a detailed discussion on why the second approach is bound to fail.

Read more

Supervision & monitoring

Actors form a tree with actors being parents to the actors they've created.

As a parent, the actor is responsible for handling its children’s failures (so-called supervision), forming a chain of responsibility, all the way to the top. When an actor crashes, its parent can either restart or stop it, or escalate the failure up the hierarchy of actors. This enables a clean set of semantics for managing failures in a concurrent, distributed system and allows for writing highly fault-tolerant systems that self-heal.

Read more

Sours: https://getakka.net/
  1. Youtube familysearch
  2. Voltron toy
  3. Plastic frag tank

Akka HTTP streaming API with cycles never completes

I'm building an application where I take a request from a user, call a REST API to get back some data, then based on that response, make another HTTP call and so on. Basically, I'm processing a tree of data where each node in the tree requires me to recursively call this API, like this:

I'm using Akka HTTP with Akka Streams to build the application, so I'm using it's streaming API, like this:

I understand that the best way to handle recursion in an Akka Streams application is to handle recursion outside of the stream, but since I'm recursively calling the HTTP flow to get each subtree of data, I wanted to make sure that the flow was properly backpressured in case the API becomes overloaded.

The problem is that this stream never completes. If I hook it up to a simple source like this:

It prints out that it's processing all the data in the tree and then stops printing anything, just idling forever.

I read the documentation about cycles and the suggestion was to put a in there, but that didn't seem to help. This question helped, but I don't understand why wouldn't stop the deadlock, since unlike their example, the elements are removed from the stream at each level of the tree.

Why doesn't avoid the deadlock, and is there another way of doing this?

asked Jul 6 at 15:50

BradBrad

2,16122 gold badges2121 silver badges3232 bronze badges

Sours: https://stackoverflow.com/questions/68273709/akka-http-streaming-api-with-cycles-never-completes
Introduction to Akka Actors with Java

Akka Serverless

Lightbend

Build stateful, high performance, back-end services and APIs on a powerful serverless PaaS.

At the core of Akka: A model for concurrency and distribution without all the pain of threading primitives.

Current version:

An intuitive and safe way to do asynchronous, non-blocking backpressured stream processing.

Current version:

Modern, fast, asynchronous, streaming-first HTTP server and client.

Current version:

Achieve resilience and elasticity by distributing your system over multiple nodes.

Current version:

Distribute your actors across the cluster based on their identity.

Current version:

Eventually consistent, highly read and write available, low latency data.

Current version:

Eventsourcing for actors allows them to reach the same state after restarts.

Current version:

Akka Projections let you process a stream of events or records from a source to a projected model or external system.

Extensions for operating Akka systems on cloud systems (k8s, aws, ...)

Alpakka is a Reactive Enterprise Integration library for Java and Scala, based on Reactive Streams and Akka.

Alpakka Kafka connector - Alpakka is a Reactive Enterprise Integration library for Java and Scala, based on Reactive Streams and Akka.

Streaming gRPC servers and clients on top of Akka Streams.

Sours: https://akka.io/docs/

Api akka

Documentation

Akka uses the Actor Model to raise the abstraction level and provide a better platform to build correct concurrent and scalable applications. For fault-tolerance it adopts the ‘Let it crash’ model, which has been used with great success in the telecoms industry to build applications that self-heal - systems that never stop. Actors also provide the abstraction for transparent distribution and the basis for truly scalable and fault-tolerant applications.

§The application actor system

Akka can work with several containers called actor systems. An actor system manages the resources it is configured to use in order to run the actors which it contains.

A Play application defines a special actor system to be used by the application. This actor system follows the application life-cycle and restarts automatically when the application restarts.

§Writing actors

To start using Akka, you need to write an actor. Below is a simple actor that simply says hello to whoever asks it to.

This actor follows a few Akka conventions:

  • The messages it sends/receives, or its protocol, are defined on its companion object
  • It also defines a method on its companion object that returns the props for creating it

§Creating and using actors

To create and/or use an actor, you need an . This can be obtained by declaring a dependency on an ActorSystem, like so:

The method is used to create a new actor. Notice that we’ve declared this controller to be a singleton. This is necessary since we are creating the actor and storing a reference to it, if the controller was not scoped as singleton, this would mean a new actor would be created every time the controller was created, which would ultimate throw an exception because you can’t have two actors in the same system with the same name.

§Asking things of actors

The most basic thing that you can do with an actor is send it a message. When you send a message to an actor, there is no response, it’s fire and forget. This is also known as the tell pattern.

In a web application however, the tell pattern is often not useful, since HTTP is a protocol that has requests and responses. In this case, it is much more likely that you will want to use the ask pattern. The ask pattern returns a , which you can then map to your own result type.

Below is an example of using our with the ask pattern:

A few things to notice:

  • The ask pattern needs to be imported, and then this provides a operator on the actor.
  • The return type of the ask is a , usually the first thing you will want to do after asking actor is map that to the type you are expecting, using the method.
  • An implicit timeout is needed in scope - the ask pattern must have a timeout. If the actor takes longer than that to respond, the returned future will be completed with a timeout error.

§Dependency injecting actors

If you prefer, you can have Guice instantiate your actors and bind actor refs to them for your controllers and components to depend on.

For example, if you wanted to have an actor that depended on the Play configuration, you might do this:

Play provides some helpers to help providing actor bindings. These allow the actor itself to be dependency injected, and allows the actor ref for the actor to be injected into other components. To bind an actor using these helpers, create a module as described in the dependency injection documentation, then mix in the trait and use the method to bind the actor:

This actor will both be named , and will also be qualified with the name for injection. You can now depend on the actor in your controllers and other components:

§Dependency injecting child actors

The above is good for injecting root actors, but many of the actors you create will be child actors that are not bound to the lifecycle of the Play app, and may have additional state passed to them.

In order to assist in dependency injecting child actors, Play utilises Guice’s AssistedInject support.

Let’s say you have the following actor, which depends on configuration to be injected, plus a key:

Note that the parameter is declared to be , this tells that it’s going to be manually provided.

We’ve also defined a trait, this takes the , and returns an . We won’t implement this, Guice will do that for us, providing an implementation that not only passes our parameter, but also locates the dependency and injects that. Since the trait just returns an , when testing this actor we can inject a factory that returns any actor, for example this allows us to inject a mocked child actor, instead of the actual one.

Now, the actor that depends on this can extend , and it can depend on the factory we created:

It uses the to create and get a reference to the child actor, passing in the key. The second parameter ( in this example) will be used as the child actor’s name.

Finally, we need to bind our actors. In our module, we use the method to bind the parent actor, and also bind the child factory to the child implementation:

This will get Guice to automatically bind an instance of , which will provide an instance of to when it’s instantiated.

§Configuration

The default actor system configuration is read from the Play application configuration file. For example, to configure the default dispatcher of the application actor system, add these lines to the file:

For Akka logging configuration, see configuring logging.

§Changing configuration prefix

In case you want to use the settings for another Akka actor system, you can tell Play to load its Akka settings from another location.

Now settings will be read from the prefix instead of the prefix.

§Built-in actor system name

By default the name of the Play actor system is . You can change this via an entry in the :

Note: This feature is useful if you want to put your play application ActorSystem in an Akka cluster.

§Using your own Actor system

While we recommend you use the built in actor system, as it sets up everything such as the correct classloader, lifecycle hooks, etc, there is nothing stopping you from using your own actor system. It is important however to ensure you do the following:

  • Register a stop hook to shut the actor system down when Play shuts down
  • Pass in the correct classloader from the Play Environment otherwise Akka won’t be able to find your applications classes
  • Ensure that either you change the location that Play reads its akka configuration from using , or that you don’t read your akka configuration from the default config, as this will cause problems such as when the systems try to bind to the same remote ports

§Akka Coordinated Shutdown

Play handles the shutdown of the and the using Akka’s Coordinated Shutdown. Find more information in the Coordinated Shutdown common section.

NOTE: Play only handles the shutdown of its internal . If you are using extra actor systems, make sure they are all terminated and feel free to migrate your termination code to Coordinated Shutdown.

§Akka Cluster

You can make your Play application join an existing Akka Cluster. In that case it is recommended that you leave the cluster gracefully. Play ships with Akka’s Coordinated Shutdown which will take care of that graceful leave.

If you already have custom Cluster Leave code it is recommended that you replace it with Akka’s handling. See Akka docs for more details.

§Updating Akka version

If you want to use a newer version of Akka, one that is not used by Play yet, you can add the following to your file:

Of course, other Akka artifacts can be added transitively. Use sbt-dependency-graph to better inspect your build and check which ones you need to add explicitly.

If you also want to update Akka HTTP, you should also add its dependencies explicitly:

Note: When doing such updates, keep in mind that you need to follow Akka’s Binary Compatibility Rules. And if you are manually adding other Akka artifacts, remember to keep the version of all the Akka artifacts consistent since mixed versioning is not allowed.

Note: When resolving dependencies, sbt will get the newest one declared for this project or added transitively. It means that if Play depends on a newer Akka (or Akka HTTP) version than the one you are declaring, Play version wins. See more details about how sbt does evictions here.

Next: Internationalization with Messages


Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines, please feel free to contribute a pull request. Have questions or advice to share? Go to our community forums to start a conversation with the community.

Sours: https://www.playframework.com/documentation/2.8.x/ScalaAkka
Comparing Kafka Streams, Akka Streams and Spark Streaming: what to use when - Rock the JVM

Akka HTTP Quickstart for Scala

Akka HTTP offers a general toolkit for providing and consuming HTTP-based services. The Akka HTTP modules implement a full server- and client-side HTTP stack on top of and . A typical application does not sit on top of Akka HTTP. Instead, Akka HTTP makes it easier to build integration layers based on HTTP, and therefore stays on the sidelines. This allows you to base your app on what makes sense and use Akka HTTP for HTTP integration.

Akka HTTP is not a framework–not because we don’t like frameworks–but to provide maximum flexibility. For example, you might use the Play framework to implement browser-based interactions or Lagom framework for creating microservices, both of them are also based on Akka.

Akka HTTP follows a rather open design and often offers several APIs for accomplishing the same thing. You can choose the API with the level of abstraction that best suits your application. If you have trouble achieving something using a high-level API, you can probably find a lower-level API to use. The low-level APIs offer more flexibility, but might require you to write more application code.

This guide highlights Akka HTTP fundamentals in the context of a simple user registry REST service. Within 30 minutes, you should be able to:

  • Download the quickstart project and run the app.
  • Follow this guide to explore the code.
  • Integrate the project into IntelliJ. If you prefer a different IDE, the principles should be similar, as long as it supports Scala.

Prerequisite

Having a basic understanding of Akka actors will make it easier to understand the example. If you are new to Akka, we recommend completing the Akka Quickstart guide before this tutorial.

You can run the Akka HTTP example project on Linux, MacOS, or Windows. The only prerequisite is Java 8.

Downloading the example

The Akka HTTP example for Scala is a zipped project that includes a distribution of the sbt build tool. Download and unzip the example as follows:

  1. Download the project zip file.
  2. Extract the zip file to a convenient location:
  • On Linux and MacOS systems, open a terminal and use the command akka-quickstart-scala.zip. Note: On OSX, if you unzip using Archiver, you also have to make the sbt files executable by entering the following two commands:
  • On Windows, use a tool such as File Explorer to extract the project.

Running the example

To run Hello World:

In a console, change directories to the top level of the unzipped project.

For example, if you used the default project name, , and extracted the project to your root directory, from the root directory, enter:

Start sbt:

  • On OSX or Linux systems, enter
  • On Windows systems, enter .

When you run sbt, it downloads project dependencies. The prompt indicates that sbt is running in interactive mode.

At the sbt prompt, enter .

sbt builds the project, starts an Akka HTTP server, and runs the example application.

The output should look something like this:

The Akka HTTP server is now running, and you can test it by sending simple HTTP requests.

You can restart it by entering again, and stop it with . To restart your application each time a change is detected, run .

Example app overview

The user registry example contains functionality for adding, retrieving, or deleting a single user and for retrieving all users. Akka HTTP provides a domain-specific language (DSL) to simplify the definition of endpoints as a . In this example, a defines: the paths and , the available HTTP methods, and when applicable, parameters or payloads.

When the example app starts up, it creates an ActorSystem with a Actor and binds the defined routes to a port, in this case, . When the endpoints are invoked, they interact with the Actor, which contains the business logic. The diagram below illustrates runtime behavior, where that the HTTP server receives for the defined endpoints, which are handled by the actor:

Architecture

Exercising the example

To get started, try registering and retrieving a few users. You simply need to know the appropriate parameters for the requests. In our example app, each user has a , an , and a .

You pass request parameters in JSON format. While you could do this in a browser, it is much simpler to use one of the following:

  • A command line tool, such as cURL.
  • Browser add-ons such as RESTClient for Firefox or Postman for Chrome.

Follow the steps appropriate for your tool:

cURL commands

Open a shell that supports cURL and follow these steps to add and retrieve users:

Copy and paste the following lines to create a few users (enter one command at a time):

The system should respond after each command to verify that the user was created.

To retrieve all users, enter the following command:

The system responds with the list of users:

To retrieve a specific user, enter the following command:

The system should respond wiht the following:

Finally, it is possible to delete users:

The response should be:

Browser-based clients

Open a tool such as RESTClient or Postman and follow these steps to create and retrieve users:

To create users:

  1. Select the method.
  2. Enter the URL:
  3. Set the Header to .
  4. In the body, copy and paste the following lines to create three users (send each payload separately). Note: for Postman, you might need to specify that you want to send data.

The system should respond after each command to verify that the user was created.

To retrieve all users:

  1. Select the method.
  2. Enter the URL:
  3. Send the request.

The system should respond with a list of users in JSON format.

Learning from the example

Congratulations, you just ran and exercised your first Akka HTTP app! You got a preview of how routes make it easy to communicate over HTTP.

The example is implemented in the following four source files:

  • – contains the main method which bootstraps the application
  • – Akka HTTP defining exposed endpoints
  • – the actor which handles the registration requests
  • – converts the JSON data from requests into Scala types and from Scala types into JSON responses

First, let’s dissect the backend logic.

Sours: https://developer.lightbend.com/guides/akka-http-quickstart-scala/

You will also be interested:

We started kissing. I began to go down lower and lower undressing her. She did not resist and also began to undress me.



868 869 870 871 872