Introduction
In this tutorial we shall explore how we can use akka-http to create service with scala. Here we create CRUD service with akka actor and try to see how it work.
Versions
Scala version: 2.13.1
SBT version: 1.3.4
Other dependencies -
About the service/project
We’ll create two actors that communicate with each other to get the user data and user activity data.
Data Classes
We need two data classes that keeps the user data and user activity data.
Repository
Repositories are used to fetch the data from the actual source of data. The actual source can be anything like another service or some database. We created `UserActivityRepository` that have only one method `queryHistoricalActivities` to fetch the user activity by `userId`.
Actors to get user data
We need two actor classes for `UserDataActor` and `UserActivityActor`. `UserDataActor` received 4 types of methods `Get`, `Post`,`Put` and `Delete` to retrieve, create, update and delete the user data respectively. Once a message received, User data will be sent to the sender asynchronously.
`UserActivityActor` retrieve the user active once it receives the message `Get`
Routing Configuration
Now, we need to create routing details, to access the user details from rest endpoints. We needs following endpoints
Routing code looks like below -
We have two `implicit` parameters in the routing config `implicit val userDataActorRef: ActorRef` and `implicit val system: ActorSystem`. `userDataActorRef` is used to get the user data. Since user details is required to register `UserActivityActor` we use actor system and implicit parameter to register `UserActivityActor` when we have user information available.
Web Server
This class is used to create http server and bind the endpoints with the http server.
Run Application
Compile the code using below command
sbt compile
Run the application
sbt run
Now go to terminal, and run below httpie scripts
We have seen here it’s easy to create rest services with akka and scala. You can get more information at
No comments:
Post a Comment