Skip to content

Instantly share code, notes, and snippets.

@crockpotveggies
Forked from minosiants/gist:3163791
Created September 20, 2012 17:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crockpotveggies/3757237 to your computer and use it in GitHub Desktop.
Save crockpotveggies/3757237 to your computer and use it in GitHub Desktop.
Akka MessageBus with WebSockets access wrapped in Actors
/**
* actor wrapping access for browser socket
*/
class BrowserSocket(
val s: WebSocketConnection,
val userId: Long,
val teamId: Long
) extends Actor {
def receive = {
case MessageEvent(channel,message) =>
s.send(message)
}
}
import akka.event.ActorEventBus
import akka.event.LookupClassification
import akka.actor._
case class MessageEvent(val channel:String, val message:String)
/**
* message bus to route messages to their appropriate contexts
*/
class MessageBus extends ActorEventBus with LookupClassification {
type Event = MessageEvent
type Classifier = String
protected val mapSize(): Int = {
10
}
protected def classify(event: Event): Classifier = {
event.channel
}
protected def publish(event: Event, subscriber: Subscriber): Unit = {
subscriber ! event
}
}
object MessageBus {
val actorSystem = ActorSystem("contexts")
val Bus = new MessageBus
/**
* create an actor that stores a browser socket
*/
def browserSocketContext(s: WebSocketConnection, userId: Long, teamId: Long) = {
val subscriber = actorSystem.actorOf(Props(new BrowserSocket(s,userId,teamId)))
Bus.subscribe( subscriber, "/app/socket/%s" format s.toString)
Bus.subscribe( subscriber, "/app/browser/u/%s" format userId )
Bus.subscribe( subscriber, "/app/browser/t/%s" format teamId )
Bus.subscribe( subscriber, "/app/browser" )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment