【问题标题】:Spring Data Repository Async SaveSpring Data Repository 异步保存
【发布时间】:2019-03-22 20:45:25
【问题描述】:

我有一个使用 Spring Data Redis 和 CrudRepository 的服务,在我的一个服务方法中,它执行查询然后保存。我想让保存异步。是否可以在我的扩展 CrudRepository 中使 save 方法异步?

对于下面的示例,我希望 save 操作是异步的。

public interface MyRepository extends CrudRepository<User, String> {
    public List<User> findByUserId(Long userId);
}

public class MyServiceImpl implements MyService {

    @Autowired
    private MyRepository myRepository;

    public void addUser(User newUser) {
        List<User> users = myRepository.findByUserId(newUser.getUserId());
        // other operations on users
        myRepository.save(); // want this be async
    }
}

【问题讨论】:

    标签: spring asynchronous spring-data-redis


    【解决方案1】:

    您可以在MyRepository 中再次声明save 方法并添加@Async 注释。

    public interface MyRepository extends CrudRepository<User, String> {
        public List<User> findByUserId(Long userId);
        @Async
        public <S extends User> S save(S entity);
    }
    

    【讨论】:

    • 不需要Future的返回类型吗?
    • 这样,如果@Async 设置正确,您将始终得到 null 作为回报。
    • 如何获得未来
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多