如何在REST API Java中实现最多3次尝试请求资源

问题描述

我想做类似的事情,我应该允许用户请求3次。之后,只有它会引发错误

我看过很多文章,他们说使用类似:

for(int i=0;i<3;i++)
{
  try
  {
  }
  catch(Exception e)
  {
    if(count<3)
    {
        count++;
        countinue;
   }
}

我尝试实现此功能,但这仅在一个请求中执行。

我想做的是,对于每个请求,都应检查计数。

例如,当我一次通过邮递员提出请求时,它应该检查一个

当我再次通过邮递员发出请求时,它应该将计数增加到2,最后是第三次抛出错误

这里是示例代码

    @PUT
    @Path("/{containerId}/assignnexttask")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response somemethod(@Context HttpHeaders headers,@PathParam("containerId") String containerId,@RequestBody String payload) throws JSONException {
        Variant v = RestUtils.getvariant(headers);
        String contentType = RestUtils.getContentType(headers);
        MarshallingFormat format = MarshallingFormat.fromType(contentType);
        // for loop is for maximum 3 attempts,int count=0;
        for (int i = 0; i < 3; i++) {
            try { 
              //here is some code 
            }
            catch(Exception e )
            {
               if(count<3)
               {
                  count++;
                  continue;
               }
             }
         }
     }

希望我能解释。谢谢您。

解决方法

您应该如下更新代码(示例伪代码)。 (假设如果第一个和第二个请求null出错,则应以Response的形式返回。)

因此,您需要维护静态变量。在成功执行错误请求之后或抛出错误之前,应将变量重新初始化为0,以使其可以为随后的请求做好准备。

//class level variable to count the error
private static int count = 0;

    @PUT
        @Path("/{containerId}/assignnexttask")
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_JSON)
        public Response somemethod(@Context HttpHeaders headers,@PathParam("containerId") String containerId,@RequestBody String payload) throws JSONException {
            Variant v = RestUtils.getVariant(headers);
            String contentType = RestUtils.getContentType(headers);
            MarshallingFormat format = MarshallingFormat.fromType(contentType);
            // for loop is for maximum 3 attempts,try { 
                  //here is some code

                   // count = 0 to make it ready for next request if no error
                   count = 0;
                   // Response data
                   return response;
            }
            catch(Exception e ) {
                   if(count<3)
                   {
                      count = count + 1;
                      return null;
                   }
                   // count = 0 to make it ready for next request
                   count = 0;
                   throw e;
             }
        }
,

喜欢吗?

for(int i=0;;i++)
{
  try
  {
     doSomething();
     break;
  }
  catch(Throwable e)
  {
    if(i==2)
    {
       throw e;
    }
  }
}