JavaSpring异步数据库交互
我有一个spring应用程序,它使用多个存储库在数据库中保存对象。问题是这些行动需要很长时间。因此,我希望这是异步的,但是操作应该按照创建的顺序执行。我研究了可能的解决方案,但没有找到任何合适的解决方案
我的想法或方法是创建一个具有可运行文件列表的组件,如果列表中有可运行文件,它必须执行这些可运行文件。此组件应该从应用程序启动到停止运行。其他服务可以将Runnable添加到列表中,bean执行它们。可运行文件包含数据库的操作。我希望示例代码能让我更清楚地了解我想要实现的目标
豆子:
@Component
@Scope("singleton")
public class DatabaseHandler {
private static final List<Runnable> transactions = new ArrayList<>();
private static final Object lock = new Object();
private boolean runHandler = true;
@Async
@PostConstruct
public void runDBHandler() {
System.err.println("Started handler!");
while(runHandler) {
while (transactions.size() == 0) {
try {
synchronized (this) {
lock.wait();
}
} catch (InterruptedException e) {
//do nothing
}
}
transactions.get(0).run();
}
}
public synchronized void addTransaction(Runnable transaction){
transactions.add(transaction);
lock.notify();
}
@PreDestroy
void stop() {
this.runHandler = false;
}
}
具有Runnable的示例服务:
@Service
public class ExampleService {
@Autowired
private ExampleRepository exampleRepository;
@Autowired
private DatabaseHandler databaseHandler;
//some method that has to save a object
public void someMethod(){
// Create the object
Object object = new Object();
// Runnable that should save asynchronous
Runnable runnable = ()->{
exampleRepository.save(object);
};
// Give runnable
databaseHandler.addTransaction(runnable);
}
}
这段代码的问题在于,我无法使用类DatabaseHandler中的锁并获取以下执行项:未能加载ApplicationContext。所以我的第一个问题是为什么我不能使用wait方法?在此PostConstruct注释中进行while循环是否错误
其他问题更一般:我的想法不好吗?我能以更好的方式解决我的问题吗
我希望我的问题是可以理解的,并有适当的格式!(这是我的第一个问题)
我将很高兴得到任何有帮助、评论或想法的回复。谢谢大家!
共 (0) 个答案