0

通过Websocket从客户端接收消息时,我试图保留以下实体:

import javax.persistence.Column;
import javax.persistence.Entity;
import io.quarkus.hibernate.orm.panache.PanacheEntity;

@Entity
public class Penguin extends PanacheEntity{
    @Column(name="penguin_name")
    public String name;
}

在收到 POST 请求时,以下持久性有效:

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.transaction.Transactional;
import com.penguins.demo.pojos.Penguin;

@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PenguinResource {
    
    @GET
    public List<Penguin> getPenguins(){
        return Penguin.listAll();
    }

    @POST
    @Transactional
    public Response addPenguin(Penguin penguin){
        penguin.persist();
        return Response.ok(penguin).status(201).build();
    }
}

但是,以下代码在到达 persist 行时会冻结。该message.getPenguin()方法返回一个实际的Penguin引用(MessageDecoder.class正在做它的一部分):

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.penguins.demo.pojos.Message;
import com.penguins.demo.pojos.Penguin;

@ServerEndpoint(value = "/waddle/{user}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
public class PenguinHub {
   @OnMessage
   @Transactional
   public void onMessage(Session session, Message message) throws IOException {
        // Handle new messages
        message.setFrom(users.get(session.getId()));
        // it freezes on persist :(
        message.getPenguin().persist();
        broadcast(message);
   }
}

我是 Panache/Hibernate 的新手,任何帮助都将不胜感激,谢谢。

4

1 回答 1

0

它是这样工作的:

@Inject
ManagedExecutor managedExecutor;

@Inject
TransactionManager transactionManager;

@OnMessage
public void onMessage(Session session, Message message) throws IOException {
    message.setFrom(users.get(session.getId()));
    managedExecutor.submit(() -> {
        try{
            transactionManager.begin();
            parseMessage(message); // persist the entity here
            transactionManager.commit();
        }catch(Exception e){
            e.printStackTrace();
        } 
    });
}
于 2022-03-03T03:29:34.483 回答