I'd like to write a simple batch processor class. It has a request queue and waits this queue to become full or some amount of time to be passed and only then talks to a database.
It is very convenient to implement this queue via channel - so that our clients will be suspended while it is full. But how can I find out if the channel becomes full?
Of course I can create a method that sends something to the channel and then performs some checks. The next step is to encapculate it in a class derived from Channel. Still very dirty (and it's unclear how can I handle onSend
/onReceive
). Are there any more elegant solutins? Maybe something out-of-box?
This is nothing out-of-the box, but the corresponding batching logic can be readily implemented using an actor. You don't really need a class for that (but you wrap this code in a class if you wish). You can use the following implementation as a template:
Now you just do
batchActor.send(data)
whenever you need to send anything to the database and the logic inside the actor takes care about batching and saving the resulting batches to the database.The Channel Interface declares an isFull property which can be queried to determine if it has reached capacity.
I can't see anyway to have a callback function to automatically invoke a function when the capacity is reached but you could periodically check this isFull property to see if it is at capacity.