Advertisement
mitrakov

Scala Play Awscala

Apr 2nd, 2018
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 4.14 KB | None | 0 0
  1. // 1. Create an account on Amazon Web Services
  2. // 2. Create your new SQS Service App
  3. // 3. There are "Standard Queue" and "FIFO Queue" (see details on AWS Web page). We gonna create FIFO one now
  4. // Choose "FIFO Queue" and name it "trix.fifo" (please note that .fifo prefix is necessary)
  5. // 4. Go to "AWS Security Credentials" page and generate your own Credentials Pair (Access Key ID, Secret Access Key)
  6. // 5. There are several ways to specify AWS credentials; we use the simplest one: via ENV variables
  7. // Copy your security credntials to your Environment, e.g.:
  8.  
  9. export AWS_ACCESS_KEY_ID=BVOPJ7UNNRP53EXTJQ2A
  10. export AWS_SECRET_ACCESS_KEY=4jz12FxGUyqpPOWTa/r8hwlpx8QskxT/KVA8JwdB
  11.  
  12. // 6. Preliminary work is done... Let's add some code:
  13. // build.sbt:
  14. libraryDependencies += "com.github.seratch" %% "awscala" % "0.6.+"
  15.  
  16. // SqsTrix.scala
  17. import awscala.sqs.SQS
  18. import awscala._
  19. import sqs._
  20. import com.amazonaws.regions.{Region, Regions}
  21. import com.amazonaws.services.sqs.model.SendMessageRequest
  22.  
  23. class SqsTrix {
  24.   private lazy implicit val sqs: SQS = SQS.at(Region.getRegion(Regions.US_EAST_2)) // specify your AWS.Region here
  25.   private lazy implicit val queue: Queue = sqs.queue("trix.fifo") getOrElse {
  26.     throw new IllegalAccessException("Cannot open queues")
  27.   }
  28.  
  29.   /**
  30.    * Sends a single message to the FIFO queue
  31.    * @param msg message body
  32.    */
  33.   def sendMsg(msg: String): Unit = {
  34.     val request = new SendMessageRequest(queue.url, msg)
  35.       .withMessageGroupId("AAA")            // this is necessary for FIFO queues
  36.       .withMessageDeduplicationId(s"${msg.hashCode}${System.nanoTime()}") // you must either check Content-Based
  37.                                             // Deduplication in Queue settings, or specify this setting manually
  38.     sqs.sendMessage(request)
  39.   }
  40.  
  41.   /**
  42.    * Receives messages and removes(!) them from the queue
  43.    * @return list of messages
  44.    */
  45.   def receiveMsg(): Seq[Message] = {
  46.     val messages = sqs.receiveMessage(queue)
  47.     if (messages.nonEmpty) // this check is necessary (otherwise you'll get `NoSuchElementException`)
  48.       sqs.deleteMessages(messages)
  49.     messages
  50.   }
  51. }
  52.  
  53. // TestController.scala:
  54. import javax.inject.Inject
  55.  
  56. import services._
  57. import scala.concurrent.{ExecutionContext, Future}
  58.  
  59. class TestController @Inject()(
  60.     cc: ControllerComponents,
  61.     sqsTrix: SqsTrix)
  62.   (implicit ec: ExecutionContext) extends AbstractController(cc) {
  63.  
  64.  
  65.   // add to routes: POST    /send    controllers.TestController.sendToQueue
  66.   def sendToQueue = Action { request =>
  67.     val msg = request.body.asText getOrElse "<empty message>"
  68.     sqsTrix.sendMsg(msg)
  69.     Ok(s"'$msg' sent...")
  70.   }
  71.  
  72.   // add to routes: GET    /recv    controllers.TestController.recvFromQueue
  73.   def recvFromQueue = Action {
  74.     val messages = sqsTrix.receiveMsg().mkString("\n\n")
  75.     Ok(s"Result: $messages")
  76.   }
  77. }
  78.  
  79. // 7. Now open curl, Postman or another tool you wish and call:
  80. POST http://localhost:9000/send with body "Hello World!"
  81. POST http://localhost:9000/send with body "Good bye World!"
  82.  
  83.     // Output:
  84.     // 'Hello World!' sent...
  85.     // 'Good bye World!' sent...
  86.  
  87. // 8. Open AWS SQS Console and ensure it contains 2 messages
  88.  
  89. // 9. Let's receive them:
  90. GET http://localhost:9000/recv
  91.  
  92.     // Output:
  93.     // Result: {MessageId: 293b241f-4d20-4abc-ade1-e9c95fd1b71e,ReceiptHandle: AQEBMzLkijnzgQxLbXw7FTSHiJ26XCL37AsqgJ+EKm+q+GnwlltDo0zIc84+2EL5lvcV86j3ayCitZMRTwuhyfauvqFyqM+YV2498FBlAskufoJ3/v/6S5c3UlB8+Quhpj6rwendCyJjVfOCrUKiHlhjUuas8FDT54yMHhqOl33lc/IQEnw84ZolUWS1lDyge8EN81Y+v53L/8kN2vhkTajM97nAI9shwJXBeiLNCJBatpoJLd0NXVUbHAReuf26w3KJIdDwo8dwxJjg6DhW5GHhMQ==,Body: Hello World!,Attributes: {},MessageAttributes: {}}
  94.  
  95.     // {MessageId: 048cdf0a-27d4-4da5-99b4-0443366a42f3,ReceiptHandle: AQEBtE9pz8dZcsHpozDath/AAkWcnT1bC3AXDbCAG3+IbX2h4dZ++IWbIdXRHIt7GYw0Bfv/Pi8jgF4x+Mxj5fed/o7mlc8ETmr2WR7qkoTGJ69ZR+62WxrZvuZto3oA9u1Mj67KX9J9S6kI7DVblQJmMbxmP5lnXCCzHQEqPpJDNKUCvAYaUVojHrnbJiWUGD6zVphJyEOSDwMUpFD2yyoBIOiA1vpQNy2fod7vVhInYNix5bIVo4w/HJuAbH/JYcbiLzWbehUX8S6vg9WCBTiBIA==,Body: Good bye World!,Attributes: {},MessageAttributes: {}}
  96.  
  97. // 10. Open AWS SQS Console once again and ensure the queue is empty
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement