TaskExecutor を使用した Spring スレッドの例はありますか?[閉まっている]
-
21-08-2019 - |
質問
トランザクション管理に Spring を使用する Java アプリケーションにスレッドを実装する方法を理解しようとしています。TaskExecutor セクションを見つけました。 春のドキュメント, ThreadPoolTaskExecutor は私のニーズに合いそうです。
スレッドプールタスクエグゼキュータ
この実装は Java 5 環境でのみ使用できますが、その環境で最も一般的に使用される実装でもあります。これは、java.util.concurrent.ThreadPoolExecutor を構成するための Bean プロパティを公開し、それを TaskExecutor でラップします。ScheduledThreadPoolExecutor などの高度な機能が必要な場合は、代わりに ConcurrentTaskExecutor を使用することをお勧めします。
しかし、どうやって使えばいいのか全く分かりません。しばらくの間、良い例を探してきましたが、見つかりませんでした。誰かが私を助けてくれれば幸いです。
解決
とてもシンプルです。考え方としては、Bean であるエグゼキュータ オブジェクトがあり、それが新しいタスクを (新しいスレッドで) 起動したいオブジェクトに渡されるということです。優れた点は、Spring 構成を変更するだけで、使用するタスク エグゼキューターのタイプを変更できることです。以下の例では、いくつかのサンプル クラス (ClassWithMethodToFire) を取得し、それを Runnable オブジェクトでラップして起動しています。実際に独自のクラスに Runnable を実装してから、呼び出すだけの実行メソッドに実装することもできます。 classWithMethodToFire.run()
.
非常に簡単な例を次に示します。
public class SomethingThatShouldHappenInAThread {
private TaskExecutor taskExecutor;
private ClassWithMethodToFire classWithMethodToFire;
public SomethingThatShouldHappenInAThread(TaskExecutor taskExecutor,
ClassWithMethodToFire classWithMethodToFire) {
this.taskExecutor = taskExecutor;
this.classWithMethodToFire = classWithMethodToFire;
}
public void fire(final SomeParameterClass parameter) {
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
}
}
そしてこちらが春の豆です。
<bean name="somethingThatShouldHappenInAThread" class="package.name.SomethingThatShouldHappenInAThread">
<constructor-arg type="org.springframework.core.task.TaskExecutor" ref="taskExecutor" />
<constructor-arg type="package.name.ClassWithMethodToFire" ref="classWithMethodToFireBean"/>
</bean>
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="25" />
</bean>