在Java Spring中进行单独的事务处理。

huangapple go评论75阅读模式
英文:

Separate transaction on Java spring

问题

我对如何完成这个任务不太确定。但我正在寻找一种将函数的交易分开的方法。

我有一个处理每条消息结果的监听器(messageListener)。在将其发送到下一步(sendToNextProcess)之前,我想确保第一个交易(updateMessagesResults)成功。(也许要创建一个单独的交易?)

在Java Spring中,我该如何做?谢谢

public void messageListener(List<Message> messages) {
    resultUpdater.updateMessagesResults(messages);
    sendToNextProcess(messages);
}

注意:监听器和resultUpdater都有@Transactional注释。

谢谢!

英文:

I'm not quite sure on how to do this. But I'm finding a way to separate the transactions of the functions.

I have a listener that processes the results of each messages (messageListener). And before sending it to the next step (sendToNextProcess), I'd like to make sure that the first transaction(updateMessagesResults) was successful. (Create a separate transaction perhaps?)

How do I do this on Java Spring? Thank you

public void messageListener(List&lt;Message&gt; messages) {
	resultUpdater.updateMessagesResults(messages);
	sendToNextProcess(messages);
}

Note: Both the listener and the resultUpdater have the @Transactional annotations.

Thank you!

答案1

得分: 2

sendToNextProcessupdateMessagesResults上都添加REQUIRES_NEW

并且不要直接调用sendToNextProcess,因为这样不会起作用,你应该注入当前的服务,然后像这样调用它:

@Service
public class CurrentService {
    @Autowired
    private CurrentService currentService;
    
    @Transactional
    public void messageListener(List<Message> messages) {
        resultUpdater.updateMessagesResults(messages);
        currentService.sendToNextProcess(messages);
    }
    
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void sendToNextProcess(List<Message> messages) {

    }
}

为什么要从注入的服务中调用它?因为@Transactional会尝试从类的范围外部进行包装,然后尝试使用this调用它,但实际效果不如预期。

英文:

Add REQUIRES_NEW on both sendToNextProcess and updateMessagesResults

and don't call sendToNextProcess directly because it will not work you should inject the current service and call it from like this

@Service
public CurrentService {
	@Autowire
	CurrentService CurrentService;	
    
    @Transactional
	public void messageListener(List&lt;Message&gt; messages) {
	    resultUpdater.updateMessagesResults(messages);
	    currentService.sendToNextProcess(messages);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void sendToNextProcess(List&lt;Message&gt; messages) {

	}
}

why you should call it from injected service because the @transactional
tries to wrap it from outside the class scope and then it tries to call it with this and it will not work as you expect

huangapple
  • 本文由 发表于 2020年4月8日 14:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/61094773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定