zwwcn

Just another WordPress.com site

JMS queue listener

Let’s say we are saving a note along some pics into the database. We will need to resize the pics and only save thumbnails. The resizing images part could take a couple seconds and we don’t want user to wait on the page, so we do it asynchronously.

The workflow would be: 1 save note;  2 flush session; 3 send resizing images request to jms ; 4 JMS queue listener receive the msg and find service action to create thumbnail.

During the resizing image process, I need to link the resized images to the note and then save the thumbnail. I had some code like below:

     ......
     saveNote(note);
     em.flush();
     AddNoteToJMSQueue(note);
    public void createThumbnail(Note note){
        Note note = em.merge(note);
        createThumbnailMethod(note);
    }

This doesn’t work because the process is asynchronous, when the resizing starts in JMS the note may not be in the database yet. What I had in my case the createThumbnail method then create another record for note, so I have duplicate record in the database.

To solve this problem, we should use find to look up the record in database before perform any action. If we can’t find the record in database then we should rollback and retry in JMS.

so the code goes:

    public void createThumbnail(Note note){
        Note newNote = em.find(note);
        if(newNote == null){
           ctx.setrollbackOnly();
        }
        createThumbnailMethod(note);
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: