2014年5月25日日曜日

Spring でのAsync処理 Queue



Queuingといえばメール送信や重たい処理を非同期で実行させる場合に
使わないと行けないというケースがあります。Spring には TaskExecutor という
非同期で処理を実行するQueueを取り扱うクラスがあります


これが何かと便利なので覚書


コマンド実行をQueueにするサンプル
asyncExecutorをautowiredして使います。


AsyncExecutor.java :

public class AsyncExecutor {

    String command;
   
    public void setCommand(String command) {
        this.command = command;
    }
   
    @Autowired
    private TaskExecutor taskExecutor;
   
    public void execute(File file) {
        taskExecutor.execute(new AsyncTask(file));
    }

    private class AsyncTask implements Runnable {
        File file;

        private AsyncTask(File file) {
            this.file = file;
        }

        public void run() {
            Runtime rt = Runtime.getRuntime();
            try {
                Process pr = rt.exec(command + " " + file.toString());
                pr.waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}



bean定義


    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" p:corePoolSize="5"
          p:maxPoolSize="10" p:queueCapacity="100" p:waitForTasksToCompleteOnShutdown="true"/>
   
    <bean id="asyncExecutor" class="sample.AsyncExecutor">
        <property name="command" value=”/opt/jetty/bin/batch.sh"></property>    </bean>





MailをTaskExecutorでおくる例は下記参照
http://www.i-develop.be/blog/2010/10/01/execute-tasks-asynchronously-with-spring-3-0/


非同期処理は自分で実装するのは気が引けるのでSpringでの実装は助かります

0 件のコメント: