Skip to content

Instantly share code, notes, and snippets.

@tohenryliu
Created January 10, 2015 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tohenryliu/03702a99825a8836349b to your computer and use it in GitHub Desktop.
Save tohenryliu/03702a99825a8836349b to your computer and use it in GitHub Desktop.
thread safe transactions in an actor
object Transactions {
class Transactor(session: Session) extends BaseActor {
/**
* To be defined in child actors
*/
override def handleMessage: Receive = ???
def commit: Future[Unit] = ???
def rollback:Future[Unit] = ???
def execute[T](f: Session => T): Future[T] = ???
}
object Transactor {
def create(implicit s: Session, aCtx: ActorContext): Transactor = {
???
}
}
object Example {
def test = {
implicit val session: Session = ???
implicit val ctx: ActorContext = ???
// to create a transactor, implicitly start the slick transaction
val transactor = Transactor.create
// run some sql work
val lst = transactor.execute{implicit s: Session => Query(ProductsTable).take(5).list}
// send the transactor to some other actors or use it inside a future
Future {
transactor.execute{implicit s: Session => Query(ProductsTable).take(5).list}
}
val someActor: ActorRef = ???
val cmd = "update pricing"
// this will be thread safe
someActor ! (cmd, transactor)
// all done, issue a commit, or rollback when need to
transactor.commit
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment