如何在Java EE容器中同步其余Web服务

时间:2014-03-06 22:35:04

标签: spring jersey weblogic spring-jdbc

我正在维护一个正在运行的系统,如果其余的webservice方法以某种方式同步,我发现了一个可以解决的错误。系统使用Jersey作为休息方法和Spring框架用于JDBC - 我从未见过有人在webservices上使用普通的旧java“同步”方法,所以不知道这是不是对错。

以下是代码的结构(只是表面细节)+注释内联:

@Path("/path")
@Component
public class WebService {
  @Autowired
  private ServiceImpl serviceImpl;
  ...
  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  @Path("/innerPath")
  public Response method1(@FormDataParam("id") String id) {
    ...
    /* this is where I need synchronization
     * both the verify and insert methods should execute one user at a time
     * otherwise all users will be able to insert
     */
    boolean v = serviceImpl.verify();
    if (v) {
      serviceImpl.insert(); //once insert succeeds, verify will start to fail
    }
    ...
  }
}

@Service
public class ServiceImpl {
   @Autowired
   private DaoImpl daoImpl;
   ...
   @Transactional
   public boolean verify() {
     boolean v = daoImpl.verify();
     return v
   }

   @Transactional
   public void insert() {
     daoImpl.insert();
   }
}

@Repository
public class DaoImpl {
  private JdbcTemplate jdbcTemplate;
  ...
  public boolean verify() {
    String sql = "....";
    ...
    int count = jdbcTemplate.queryForInt(sql);
    if (count > 0) {
      return false;
    }
    return true;
  }

  public void insert() {
    String sql = "....";
    ...
    jdbcTemplate.queryForInt(sql);
  }
}

1 个答案:

答案 0 :(得分:0)

我正在通过使用第三个虚拟表来解决并发问题,其中每个线程将首先尝试将其唯一数据作为记录插入,然后继续执行它想要做的任何事情。

这个虚拟表的主键是一组列,它们与线程保存的所有唯一数据一对一映射。

如果并发线程尝试插入此虚拟表,则只有一个插入成功(因为主键约束)。