4

我在使用以下代码的简单 REST 服务时遇到了麻烦:

@GET
@Path("next/{uuid}")
@Produces({"application/xml", "application/json"})
public synchronized Links nextLink(@PathParam("uuid") String uuid) {
    Links link = null;
    try {
        link = super.next();
        if (link != null) {
            link.setStatusCode(5);
            link.setProcessUUID(uuid);
            getEntityManager().flush(); 
            Logger.getLogger("Glassfish Rest Service").log(Level.INFO, "Process {0} request url : {1} #id  {2} at {3} #", new Object[]{uuid, link.getLinkTxt(), link.getLinkID(), Calendar.getInstance().getTimeInMillis()});
        }
    } catch (NoResultException ex) {
    } catch (IllegalArgumentException ex) {
    }
    return link;
}

这应该提供一个链接对象,并将其标记为已使用 (setStatusCode(5)) 以防止下一次访问服务以发送相同的对象。问题是,当有很多快速客户端访问 Web 服务时,这会为不同的客户端提供 2 或 3 倍的相同链接对象。我该如何解决这个问题?

这是使用 to 的请求:@NamedQuery(name = "Links.getNext", query = "SELECT l FROM Links l WHERE l.statusCode = 2")

和 super.next() 方法:

public T next() {

    javax.persistence.Query q = getEntityManager().createNamedQuery("Links.getNext");
    q.setMaxResults(1);
    T res = (T) q.getSingleResult();
    return res;
}

谢谢

4

4 回答 4

6

(根)JAX-RS 资源的生命周期是每个请求的,因此方法上的(否则正确的)synchronized关键字nextLink很遗憾无效。

您需要的是同步访问/更新的方法。这可以通过多种方式完成:

I)您可以在由框架注入的外部对象上进行同步(例如:CDI 注入 @ApplicationScoped),如下所示:

@ApplicationScoped
public class SyncLink{
    private ReentrantLock lock = new ReentrantLock();
    public Lock getLock(){
       return lock;
    }
}
....
public class MyResource{
  @Inject SyncLink sync;

  @GET
  @Path("next/{uuid}")
  @Produces({"application/xml", "application/json"})
  public Links nextLink(@PathParam("uuid") String uuid) {
    sync.getLock().lock();
    try{
      Links link = null;
      try {
        link = super.next();
        if (link != null) {
            link.setStatusCode(5);
            link.setProcessUUID(uuid);
            getEntityManager().flush(); 
            Logger.getLogger("Glassfish Rest Service").log(Level.INFO, "Process {0} request url : {1} #id  {2} at {3} #", new Object[]{uuid, link.getLinkTxt(), link.getLinkID(), Calendar.getInstance().getTimeInMillis()});
        }
      } catch (NoResultException ex) {
      } catch (IllegalArgumentException ex) {
      }
      return link;
    }finally{
       sync.getLock().unlock();
    }
  }
}

II)你可能很懒惰并在课堂上同步

public class MyResource{
  @Inject SyncLink sync;

  @GET
  @Path("next/{uuid}")
  @Produces({"application/xml", "application/json"})
  public Links nextLink(@PathParam("uuid") String uuid) {
     Links link = null;
    synchronized(MyResource.class){
      try {
        link = super.next();
        if (link != null) {
            link.setStatusCode(5);
            link.setProcessUUID(uuid);
            getEntityManager().flush(); 
            Logger.getLogger("Glassfish Rest Service").log(Level.INFO, "Process {0} request url : {1} #id  {2} at {3} #", new Object[]{uuid, link.getLinkTxt(), link.getLinkID(), Calendar.getInstance().getTimeInMillis()});
        }
      } catch (NoResultException ex) {
      } catch (IllegalArgumentException ex) {
      }

    }
    return link;
  }
}

III)您可以使用数据库进行同步。在这种情况下,您将研究JPA2 中可用的悲观锁定。

于 2013-02-05T17:42:43.397 回答
0

根据您认为创建新的争用的频率,Links您应该选择使用@Version属性的乐观锁定或悲观锁定。

我的猜测是乐观锁定会更适合你。在任何情况下,让您的 Resource 类充当服务外观并将与模型相关的代码放入无状态会话 Bean EJB 并通过简单的重试来处理任何 OptimisticLockExceptions。

我注意到您提到您在捕获与锁定相关的异常时遇到了麻烦,而且看起来您正在使用 Eclipselink。在这种情况下,你可以尝试这样的事情:

@Stateless
public class LinksBean {

  @PersistenceContext(unitName = "MY_JTA_PU")
  private EntityManager em;

  @Resource
  private SessionContext sctx;

  public Links createUniqueLink(String uuid) {
    Links myLink = null;
    shouldRetry = false;
    do {
      try
        myLink = sctx.getBusinessObject(LinksBean.class).createUniqueLinkInNewTX(uuid);
      }catch(OptimisticLockException olex) {
        //Retry
        shouldRetry = true;
      }catch(Exception ex) {
       //Something else bad happened so maybe we don't want to retry 
       log.error("Something bad happened", ex);
       shouldRetry = false;   
    } while(shouldRetry);
    return myLink;
  }

  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public Links createUniqueLinkInNewTX(uuid) {
      TypedQuery<Links> q = em.createNamedQuery("Links.getNext", Links.class);
      q.setMaxResults(1);
      try {
        myLink = q.getSingleResult();
      }catch(NoResultException) {
        //No more Links that match my criteria
        myLink = null;
      }
      if (myLink != null) {
        myLink.setProcessUUID(uuid);
        //If you change your getNext NamedQuery to add 'AND l.uuid IS NULL' you 
        //could probably obviate the need for changing the status code to 5 but if you 
        //really need the status code in addition to the UUID then:
        myLink.setStatusCode(5);
      }
      //When this method returns the transaction will automatically be committed 
      //by the container and the entitymanager will flush. This is the point that any 
      //optimistic lock exception will be thrown by the container. Additionally you 
      //don't need an explicit merge because myLink is managed as the result of the 
      //getSingleResult() call and as such simply using its setters will be enough for 
      //eclipselink to automatically merge it back when it commits the TX
      return myLink; 
  }  
}

Your JAX-RS/Jersey Resource class should then look like so:

@Path("/links")
@RequestScoped
public class MyResource{
  @EJB LinkBean linkBean;

  @GET
  @Path("/next/{uuid}")
  @Produces({"application/xml", "application/json"})
  public Links nextLink(@PathParam("uuid") String uuid) {
     Links link = null;
     if (uuid != null) {
         link = linkBean.createUniqueLink(uuid);
         Logger.getLogger("Glassfish Rest Service").log(Level.INFO, "Process {0} request url : {1} #id  {2} at {3} #", new Object[]{uuid, link.getLinkTxt(), link.getLinkID(), Calendar.getInstance().getTimeInMillis()});
      }
    return link;
  }
}

这是给这只猫剥皮的一种方法的半成品示例,这里有很多事情要做。如果您有任何问题,请告诉我。

此外,从 REST 的角度来看,您可能会考虑对该资源使用 @PUT 而不是 @GET,因为您的端点具有更新(UUID 和/或 statusCode)资源状态的副作用,而不仅仅是获取它。

于 2013-02-08T06:33:21.187 回答
0

您需要使用某种形式的锁定,很可能是乐观版本锁定。这将确保只有一个事务成功,另一个将失败。

见, http ://en.wikibooks.org/wiki/Java_Persistence/Locking

于 2013-02-04T14:37:04.210 回答
0

在使用 Java EE 特性 JAX-RS 时,据我了解,您不应像使用synchronized块一样以 Java SE 样式管理线程。

在 Java EE 中,您可以使用单例 EJB 提供对方法的同步访问:

@Path("")
@Singleton
public class LinksResource {

    @GET
    @Path("next/{uuid}")
    @Produces({"application/xml", "application/json"})
    public Links nextLink(@PathParam("uuid") String uuid) {

默认情况下,这将使用@Lock(WRITE)一次只允许一个请求到您的方法。

于 2018-09-22T12:02:17.240 回答