Spring 如何在JavaEE容器中同步RESTWebServices
我正在维护一个工作中的系统,我发现了一个bug,如果RESTWebService方法以某种方式同步,这个bug可以解决。该系统使用Jersey for rest方法和Spring framework for JDBC——我从未见过有人在Web服务上使用纯java的synchronized方法,所以不知道这是对还是错 下面是代码的结构,只是表面细节+内联注释:Spring 如何在JavaEE容器中同步RESTWebServices,spring,jersey,weblogic,spring-jdbc,Spring,Jersey,Weblogic,Spring Jdbc,我正在维护一个工作中的系统,我发现了一个bug,如果RESTWebService方法以某种方式同步,这个bug可以解决。该系统使用Jersey for rest方法和Spring framework for JDBC——我从未见过有人在Web服务上使用纯java的synchronized方法,所以不知道这是对还是错 下面是代码的结构,只是表面细节+内联注释: @Path("/path") @Component public class WebService { @Autowired pr
@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);
}
}
我通过使用第三个虚拟表来解决并发性问题,其中每个线程将首先尝试将其唯一的数据作为记录插入,然后继续执行它想要执行的任何操作 这个虚拟表的主键是一组列,这些列与线程持有的所有唯一数据一一对应 如果并发线程试图插入到这个虚拟表中,那么由于主键约束,只有一个插入会成功