How to persist Entity in separate thread with JPA on J2EE App server?
I have a chat application that needs to store messages to DB. But connection with DB is a little bit slow, therefore it delays response to chat client.
Is it possible to persist Message entity in separate thread? What I'm actually need in: reduce delay before send-recieve message on client.
I try to do it, but it doen't work.
Dao object:
@Stateless
pub开发者_运维问答lic class MessagesDAO {
@PersistenceContext(type= PersistenceContextType.EXTENDED)
private EntityManager entityManager;
private PersistenceThread persistenceThread = new PersistenceThread();
//another methods
public void addMessage(Message message) {
Thread thread = new Thread(persistenceThread);
persistenceThread.setMessage(message);
thread.start();
}
private class PersistenceThread implements Runnable {
private Message message;
public void setMessage(Message message) {
this.message = message;
}
public void run() {
entityManager.persist(message);
}
}
}
Interface service that calls DAO to persist new message and then return it to clients:
@Stateless
@Path("/messages")
@Produces("application/xml")
@Consumes("application/xml")
public class MessagesServiceImpl {
@EJB
private MessagesDAO messagesDAO;
@POST
@Broadcast(resumeOnBroadcast = true)
public Message postMessage(Message message) {
messagesDAO.addMessage(message);
return message;
}
@GET
@Path("/wait")
@Suspend(outputComments = false)
public Message waitForLastMessage() {
return null;
}
//another methods
}
Thanks.
Give the @Asynchronous annotation a try:
@Stateless
public class MessagesDAO {
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
@Asynchronous
public void addMessage(Message message) {
entityManager.persist(message);
}
}
Just bear in mind that it requires EJB 3.1.
精彩评论