java - 并发请求中rest api数据不匹配

标签 java spring rest concurrency

在我的项目中,我们使用带有 spring 框架的 Restful Webservices,当我同时调用相同的请求时, 对象被另一个对象覆盖。

下面是我的代码。

@Service("testService")
@Scope(value ="prototype")
public class TestServiceImpl extends DefaultServiceBuilder {

        public void test() {
                 process();
                 System.err.println(tranLog.getTxnId());

        }
}


  public class DefaultServiceBuilder {

protected TransactionLog tranLog;

public void process() {
    tranLog = new TransactionLog();
    Random r = new Random();
    String rid = r.nextInt(40000)+"";
    tranLog.setTxnid(rid);
    setTranLog(tranLog);
}


    public TransactionLog getTranLog() {
        return tranLog;
    }

    public void setTranLog(TransactionLog tranLog) {
        this.tranLog = tranLog;
    }
}

public class TransactionLog {
   private String txnId;

   public void setTxnId(String txnId) {
        this.txnId = txnId;
   }

   public String getTxnId() {
        return txnId;
   }
}

我正在使用 2 个线程并行调用以下请求。

My expected input is 
123456
242422

But the output is 
242422
242422

为什么即使我给出了作用域原型(prototype),TransactionLog 对象值仍然会被覆盖。 如何安全地访问Transalog对象?

任何帮助将不胜感激!!!!

最佳答案

您可以通过同步以下代码行来同步您的代码

protected static TransactionLog tranLog;

public static synchronized void process() {
    Random r = new Random();
    tranLog = new TransactionLog();
    String rid = r.nextInt(40000)+"";
    tranLog.setTxnid(rid);
}

设置静态同步将在任何给定时间只允许一个线程。

关于java - 并发请求中rest api数据不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519407/

相关文章:

java - Spring ControllerAdvice 中未处理 404 异常

java - 使用Spring框架提供的StoredProcedure调用Oracle存储过程

rest - PUT 请求的 Pyramid 遍历

java - 如何绕过 https 安全证书屏幕?

java - java中BufferedOutputStream有什么好处?不是每个OutputStream都有一个缓冲区吗?

java - 从数据库中检索一些特定的表

python - 与 Spark 交互的 REST API

java - 接收byte[]并显示在ImageView android上

spring - Maven错误 "annotations are not supported....."

java - Apache 服务器上的第一个 REST 调用速度缓慢