`
sillycat
  • 浏览: 2543645 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Play framework with Akka and WS

 
阅读更多
Play framework with Akka and WS

1 Set Up Akka in Playframework
In my controller which I believe it is single, I set up the AKKA system.
package controllers

import actors._
import actors.jobs.{JobServiceActor, JobParseActor}
import actors.resumes.{ResumeServiceActor, ResumeParseActor, ResumeAttachActor}
import akka.actor.Props
import com.sillycat.dao.{IpplyJobDAO, DAO}
import com.sillycat.util.IncludeLogger
import com.wordnik.swagger.annotations._
import models.ScanTriggerRequest
import play.api.libs.concurrent.Akka
import play.api.libs.json.{JsError, Json}
import play.api.mvc.{BodyParsers, Action, Controller}
import play.api.Play.current
import akka.contrib.throttle.TimerBasedThrottler
import akka.contrib.throttle.Throttler._
import scala.concurrent.duration._
import com.wordnik.swagger.annotations._

object ScanTriggerController extends Controller with IncludeLogger with IncludeWSConfig{

  implicit val scanTriggerWrites = Json.writes[ScanTriggerRequest]
  implicit val scanTriggerReads = Json.reads[ScanTriggerRequest]

  Akka.system.actorOf(JobParseActor.props, name = "job-parse-actor")

  Akka.system.actorOf(JobServiceActor.props, name = "job-service-actor")

  Akka.system.actorOf(ResumeAttachActor.props, name = "resume-attach-actor")

  Akka.system.actorOf(ResumeParseActor.props, name = "resume-parse-actor")

  Akka.system.actorOf(ResumeServiceActor.props, name = "resume-service-actor")

  Akka.system.actorOf(TriggerActor.props, name = "trigger-actor")

  val contextIOActor = Akka.system.actorOf(ContextIOActor.props, name = "contextio-actor")

  val contextIOThrottler = Akka.system.actorOf(Props(classOf[TimerBasedThrottler], contextio_throttle msgsPer 60.second), name = "conetxt-io-throttler")

  contextIOThrottler ! SetTarget(Some(contextIOActor))

  def trigger = Action(BodyParsers.parse.json) { request =>
    val b = request.body.validate[ScanTriggerRequest]
    logger.debug("Processing request with param = " + request.body)
    b.fold(
      errors => {
        BadRequest(Json.obj("status" -> "OK", "message" -> JsError.toJson(errors)))
      },
      trigger => {
        //TODO more validation on the params
        logger.debug("Param validation success, param = " + trigger)

        val triggerActor = Akka.system.actorSelection("/user/trigger-actor")
        logger.debug("Prepare the trigger action = " + triggerActor + ", and fire message!")
        triggerActor ! trigger
        Ok(Json.obj("status" -> "OK"))
      }
    )
  }

}

In any other actors or any other controllers, we can do as follow:
val jobServiceActor = context.actorSelection("/user/job-service-actor")
jobServiceActor ! JobContentPersistMessage(msg.jobId, jobCity, msg.emailContent)

In my case I have one controller to trigger my actions, maybe in the future I need to set up the AKKA system in global class or some where.

2 WS to call other Micro Service
Here is how I call other micro service
import akka.actor.{Actor, Props}
import com.sillycat.dao.{DAO, IpplyJobDAO, ResumeDAO}
import com.sillycat.util.IncludeLogger
import models.messages.jobs.{JobPersistMessage, JobScanMessage, JobContentParseMessage, JobContentScanMessage}
import models.messages.resumes._
import models.{ResumeScanResponse, ResumeScanAttachmentResponse, JobContentResponse, JobScanResponse}
import play.api.libs.json.Json
import play.api.libs.ws.{WS, WSResponse}
import utils.IncludeRegex
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Future
…snip...
    case msg:JobContentScanMessage => {
      logger.debug("receiving the message JobContentScanMessage" + msg)
      //context.io fetch job content, actually it is email content, I need the city and location info
      val future:Future[WSResponse] = WS.url(contextio_host + "/jobs/" + msg.accountCode +"/" + msg.messageCode ).get()
      //scan jobs success
      future onSuccess {
        case response if response.status == 200 => {
          logger.trace("Scanning job content = " + response.json)

          response.json.asOpt[JobContentResponse].map { job =>
            logger.trace("Scanning result job content = " + job)
            val jobContentParseMessage = JobContentParseMessage(msg.jobId, job.content)
            logger.debug("fire the message to job-parse-actor to parse email content.")
            jobParseActor ! jobContentParseMessage
          }
        }
        case response => {
          //handling error
          logger.error("Error handle with status = " + response.status + " message = " + response.body)
        }
      }
      //scan jobs fail
      future onFailure {
        case t => logger.error("An error has occured: " + t.getMessage)
      }
    }

For post
      val request_data = Json.obj(
        "provider" -> "CRAIGSLIST",
        "accountCode" -> msg.accountCode,
        "dateBefore" -> msg.dateBefore.toString(default_date_time_format),
        "dateAfter" -> msg.dateAfter.toString(default_date_time_format),
        "limit" -> msg.limit,
        "offset" -> msg.offset
      )
      logger.debug("Send json request parameter = " + request_data)
      val future:Future[WSResponse] = WS.url(contextio_host + "/jobs/scan").post(request_data)

References:
https://www.playframework.com/documentation/2.4.3/ScalaWS
https://www.playframework.com/documentation/2.4.3/ScalaAkka

akka system
http://sillycat.iteye.com/blog/1767866
http://sillycat.iteye.com/blog/1768625
http://sillycat.iteye.com/blog/1768626
http://sillycat.iteye.com/blog/2099267
http://sillycat.iteye.com/blog/2100232
http://sillycat.iteye.com/blog/2102694
http://sillycat.iteye.com/blog/2175999
分享到:
评论

相关推荐

    Reactive Programming with Scala and Akka mobi

    Reactive Programming with Scala and Akka 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    play framework api,play! framework api,play api

    2. **异步编程**:Play Framework基于Akka框架,支持非阻塞I/O和异步处理,提高了Web应用的并发性能。 3. **路由系统**:Play Framework的路由文件定义了URL到Action的映射,允许开发者灵活地控制请求处理逻辑。 4...

    playframework中文教程.zip

    4. **异步I/O**:Play 使用Akka框架实现非阻塞I/O,可以处理大量的并发请求,适合构建高并发的Web应用。 5. **RESTful API支持**:Play 鼓励开发者使用HTTP协议的特性来构建应用程序,便于构建服务化和微服务化的...

    play-zipkin-tracing:使用Zipkin为Play Framework和Akka提供分布式跟踪

    `play-zipkin-tracing` 是一个项目,它专门用于为Play Framework和Akka这样的工具集添加Zipkin支持,实现分布式跟踪。Zipkin是一个流行的开源系统,用于收集服务间调用的时序数据,帮助开发者在复杂的分布式环境中...

    Play Framework Cookbook

    - **非阻塞 I/O**:Play Framework 基于 Akka 框架实现了非阻塞 I/O,这使得在处理大量并发请求时无需担心性能瓶颈问题。本书会详细介绍如何利用这一特性构建高并发的应用程序。 - **模块化架构**:该框架支持模块化...

    Play Framework应用程序框架 v2.7.9.zip

    1. **异步编程模型**:Play Framework利用Akka Actor系统实现非阻塞I/O,提高了应用的并发性能。 2. **热重载**:在开发过程中,代码的修改可以实时生效,无需重启服务器,极大地提高了开发效率。 3. **可插拔的依赖...

    Reactive.Programming.with.Scala.and.Akka.1783984341.epub

    Get to grips with the full range of Akka features including the upcoming and cutting edge experimental modules A comprehensive coverage of the principles of FRP with real-world use cases to solve ...

    Play Framework2本教程

    5. **异步编程**:Play基于Akka框架,支持非阻塞I/O和异步处理,这使得它在处理高并发请求时表现优秀。通过Future和Promise对象,你可以编写高效的并发代码。 6. **测试支持**:Play提供了内置的测试工具,如...

    playframework 框架学习之路 1

    2. **异步编程模型**: Play使用Akka Actor系统进行异步处理,这意味着它可以处理大量并发请求,提高应用程序的性能。这种非阻塞I/O方式使得Play特别适合构建高并发的Web应用。 3. ** MVC 架构**:Play遵循MVC设计...

    AkkaGuice:Playframework 的 Akka Guice 集成

    Akka Guice 集成安装将以下内容添加到您的 build.sbt: resolvers += " release repository " at " ... 添加行(插件前面的数字是您播放应用程序内的加载顺序): 10000:akkaGuice.AkkaGuicePlugin在 Global.java 中...

    play framework 学生信息管理系统

    7. **异步编程**:Play Framework 基于Akka Actor模型,支持非阻塞I/O和异步处理,这使得它可以高效地处理高并发请求。 8. **测试**:Play Framework 提供了集成测试工具,如`play-test`模块,便于编写单元测试和...

    SignalJ:将 SignalR 创意移植到 PlayFramework 和 Akka

    使用 Actor 将 SignalR到 PlayFramework。 SignalJ(SignalR)是一个服务器到客户端和客户端到服务器的通信框架。 使用回退机制与浏览器通信。 首先尝试 websockets,然后服务器发送事件,最后长轮询。 还有其他几...

    Play Framework应用程序框架 v3.0.1.zip

    1. **异步编程模型**:Play Framework使用Akka Actor系统,支持非阻塞I/O和事件驱动编程,这使得它能处理大量并发请求,提高了应用程序的性能。 2. **热重载**:在开发过程中,Play框架支持代码的实时更新,无需...

    Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams

    This compact book includes in-depth introductions to RxJava, Akka Streams, and Reactor, and integrates the latest related features from Java 9 and 11, as well as reactive streams programming with the...

    Play-Utils是一个专门为PlayFramework开发的实用工具包模块

    Play-Utils 模块是为 Play Framework 设计的一个强大且实用的工具集合,它极大地提升了开发者在使用 Play Framework 进行 Java Web 开发时的效率和便利性。Play Framework 是一个开源的、基于 MVC(模型-视图-控制器...

    java版商城源码-hello2akka:介绍Playframework使用Akka演员和期货的演示文稿和代码示例

    /home/ambantis/Documents/dev/play/play4jug/hello2akka/project [info] Set current project to hello2akka (in build file:/home/ambantis/Documents/dev/play/play4jug/hello2akka/) > compile 基于线程的并发 ...

    playframework做的demo

    10. **异步编程**:Play Framework基于Akka Actor系统,支持非阻塞I/O,这对于处理高并发的Web应用非常有利。在博客系统中,这可能体现在如评论实时刷新、异步保存等场景。 通过这个Play Framework的博客示例,初学...

    Play Framework Cookbook.pdf

    - **非阻塞架构**:基于 Akka 的 Actor 模型,Play Framework 采用了异步和非阻塞 I/O 来处理 HTTP 请求,这使得应用能够高效地处理大量并发连接。 - **简洁性**:框架设计简洁明了,遵循“约定优于配置”的原则,...

    Play Framework应用程序框架 v2.7.9-源码.zip

    4. **Akka集成**:Play Framework基于Akka Actor系统构建,提供高度可扩展性和并发性。研究`play.core.AkkaHttpServer`和`play.api.libs.streams.AkkaStreams`,可以了解Play如何利用Akka处理HTTP请求。 5. **模块...

Global site tag (gtag.js) - Google Analytics