-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathActorClient.scala
71 lines (58 loc) · 1.93 KB
/
ActorClient.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package http
import akka.actor.{Actor, ActorLogging}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.{ActorMaterializer, ActorMaterializerSettings}
import akka.util.ByteString
/**
* Akka http it´s just a simple implementation of Http client using Actor system
*
*/
class ActorClient extends Actor with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))
val http = Http(context.system)
/**
* preStart method it´s invoked when the actor it´s completely initialized
*
* http class it´s used to invoke singleRequest which allow all types of request GET, POST, PUT, DELETE
* After we make the request we pipe the request to the actorSystem which provide a Future[HttpResponse]
*
*/
override def preStart(): Unit = {
getVersion
postOrder.onComplete(_ => getOrder)
}
private def getVersion = {
http.singleRequest(HttpRequest(uri = "http://localhost:8080/version"))
.pipeTo(self)
}
private def postOrder = {
http.singleRequest(HttpRequest(HttpMethods.POST, uri = "http://localhost:8080/order", entity = ByteString(createBody)))
.pipeTo(self)
}
private def createBody = {
"""
{
"id":"1",
"product":"cocal-cola"
}
""".stripMargin
}
private def getOrder = {
http.singleRequest(HttpRequest(uri = "http://localhost:8080/order", entity = "1"))
.pipeTo(self)
}
def receive: PartialFunction[Any, Unit] = {
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
getBody(entity)
case HttpResponse(code, _, _, _) =>
log.info("Request failed, response code: " + code)
}
private def getBody(entity: ResponseEntity) = {
entity.dataBytes
.map(value => value.decodeString("UTF-8"))
.runForeach(value => log.info(value))
}
}