简体   繁体   中英

Using @Transactional on actors class definition with Akka 2.X.X?

I used to use Spring transaction annotation over my beans. However, actors from Akka are reluctant. Here's my code snippet in Scala:

@Service
@Transactional
@Scope("prototype")
class MyActor extends Actor with ActorLogging { 

   def receive = {
     //......  throwing a NotInTransaction (no matter what the calling lib is)
   }
}

However, @Transactional works for all my other non-actor beans.

I added Java as tag since it is likely a similar issue with Akka for Java, I guess.

Did I miss something?

I'm pointing out I follow beforehand this technique (that I adapted in Scala) to make my actors creation aware of Spring: http://www.typesafe.com/activator/template/akka-java-spring

UPDATE WITH AN EXAMPLE -----------

@Service("eventsListenerActor")
@Scope("prototype")
class EventsListenerActor @Autowired()(val eventRepository: EventRepository) extends Actor {

  def receive = {
    case RetrieveNewEvents =>
      val newEvents = eventRepository.findNewEvents(EventBatchSizeProperty)
  }

}

@Repository
class MyEventRepository extends EventRepository {

   @Transactional       //transactional annotation here
   def findNewEvents(batchSize: Int): List[Event] = {
    //................    code warning that transaction context is not present here !
  }
}

Any call to the findNewEvents outside an actor well builds the transaction context.

As I asked in comments below, may it be related to the actor and its way of threading?

Transaction tracking in application containers is based upon ThreadLocal variables, therefore it does not work with Actors. The clash is no coincidence, since having an actor take part in a larger transaction runs counter to the intention: actors shall share nothing and only communicate using messages. Two actors cannot ever be internally consistent without violating this rule.

The benefits of following this rule are plentiful: proper encapsulation, location transparency, painless distribution across CPUs or nodes, sane failure handling model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM