0

如果消息是并行的,一次最多创建 10 个以下NewProcessor的线程。为了进行测试,使用了 20 条具有相同参数的消息,并且预期在Net域的 DB 中只有一条记录,但创建了多条记录。

经过几个小时的各种更改,我仍然无法弄清楚问题所在......


    class NewProcessor implements Runnable {
        ...
        NewService newService = ApplicationContextHolder.getBean("newService")

        public void run(){
            process()
        }

        public boolean process(){
            ...
            def obj = newService.process(param)
            ...
        }
    }

    class NewService {

        NetService netService
        ...

        public Info process(String param){
            Info info = new Info()
            ...

            info.net = netService.getNet(param)
            ...
            ...
            info.save()
        }

        ...
    }

    class NetService {
         public synchronized Info getNet(String param) {

              Rule trule = Rule.findByParam(param)
              Net net = Net.findByRule(trule)
              if (!net){
                    net = new Net(rule: trule).save(flush: true, validate: false)
              }

              return net
         }

         ....
    } 
4

1 回答 1

1

我必须通过将@Transactional(propagation = Propagation.REQUIRES_NEW)添加到 getNet() 方法来使其工作,如下所示。

class NetService {
     @Transactional(propagation = Propagation.REQUIRES_NEW)
     public synchronized Info getNet(String param) {

          Rule trule = Rule.findByParam(param)
          Net net = Net.findByRule(trule)
          if (!net){
                net = new Net(rule: trule).save(flush: true, validate: false)
          }

          return net
     }

     ....
}
于 2014-02-06T11:47:58.987 回答