Spring MVC中的同步方法

dea*_*end 7 java multithreading spring-mvc synchronized

我试图在spring控制器中使用synchronize方法.因为我们的支付网关一次点击方法[@RequestMapping(value ="/ pay",method = RequestMethod.POST)]不同的交易[txn id:txn01&txn02].但由于使用了同步块,这两个不同的事务处理逐个并行处理.

问题 - >为什么我在控制器中使用同步块就是说,事务[txn01]命中[@RequestMapping(value ="/ pay",method = RequestMethod.POST)]两次,就像来自支付网关的重复呼叫一样.在完成第一次呼叫[后端处理]之前,我从支付网关获得相同转账的第二次呼叫.

有没有办法处理两个不同的事务并行使用同步块中的事务ID而不是重复调用我的意思是相同的转义.请指教.

如果我的问题不清楚,请告诉我.

@RequestMapping(value="/pay",method=RequestMethod.POST)
public String payAck(HttpServletRequest httpRequest,HttpServletResponse httpResponse,HttpSession session){
    synchronized (this) {
        return this.processPayAck(httpRequest, httpResponse, session);
    }
}

public synchronized String processPayAck(HttpServletRequest httpRequest,HttpServletResponse httpResponse,HttpSession session){
   // Payment Acknowledgment process here
    if (sametranIDNotExists) {
        // first call here
        callWS(); - processing business logic.
        return someURL;
    } else {
       // Gets second call here before first call completed
       return someURL;
    }
}
Run Code Online (Sandbox Code Playgroud)

修改后的代码

在同步块中使用实习生是否正确?

@RequestMapping(value="/pay",method=RequestMethod.POST)
public String payAck(HttpServletRequest httpRequest,HttpServletResponse httpResponse,HttpSession session){
    String tranID = httpRequest.getParameter("tranID");
    synchronized (String.valueOf(tranID).intern()) {
        return processPayAck(httpRequest, httpResponse, session);
    }
}
Run Code Online (Sandbox Code Playgroud)

孙兴斌*_*孙兴斌 5

我不确定您是否在分布式环境中工作。

如果只有一台机器,您可以删除 syncronized 关键字并使用您的交易 ID创建基于名称的锁。

如果这个程序在一个集群中运行并且有多台机器,这意味着请求可能会被分配到不同的机器上,我认为你需要用Redis或其他框架来获取分配锁