简体   繁体   English

spring boot如何在异步方法中处理容错?

[英]spring boot how to handle fault tolerance in async method?

Suppose I have a caller to distribute work to multiple async tasks: 假设我有一个调用者将工作分配给多个异步任务:

public class Caller{
    public boolean run() {
        for (int i = 0: i< 100; i++) {
            worker.asyncFindOrCreate(entites[i]);
        }
        return true;
    }

public class Worker{
    @Autowired
    Dao dao;

    @Async
    public E asyncFindOrCreate(User entity) {
        return dao.findByName(entity.getName).elseGet(() -> dao.save(entity));
    }
}

If we have 2 same entities: with the synchronized method, the first one will be created and then the second one will be retrieved from the existing entity; 如果我们有两个相同的实体:使用synced方法,将创建第一个实体,然后从现有实体中检索第二个实体; with async, the second entities might pass the findByName and go to save because the first entity hasn't been saved yet, which cause the save of the second entity throws unique identifier error. 使用异步,第二个实体可能会通过findByNamesave因为第一个实体尚未保存,这导致第二个实体的save引发唯一标识符错误。

Is there a way to add some fault tolerance mechanic to have some features like retry and skipAfterRetry, in particular for database operations. 有没有一种方法可以添加一些容错机制来具有某些功能,例如重试和skipAfterRetry,尤其是对于数据库操作。

In this special case you should convert your array to a map. 在这种特殊情况下,您应该将数组转换为地图。 Use the name property as a key, so there will be no duplicated entries. 使用name属性作为键,因此不会有重复的条目。

However, if this method also can be called by multiple threads (ie. it's in a web-server) or there are multiple instances running it's still not fail-safe. 但是,如果也可以由多个线程(例如,它在Web服务器中)调用此方法,或者有多个实例在运行,则它仍然不是故障安全的。

In generic, you should let the DB to check the uniqueness. 通常,应该让数据库检查唯一性。 There is no safest/easiest way to do that. 没有最安全/最简单的方法。 Put the save method inside a try-catch block and check/handle the unique identifier exception. 将save方法放入try-catch块中,然后检查/处理唯一标识符异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM