简体   繁体   中英

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; 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.

Is there a way to add some fault tolerance mechanic to have some features like retry and skipAfterRetry, in particular for database operations.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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