Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 11.0.1 (日本語) » Mobile Link - サーバ管理 » Mobile Link サーバ API » Java による同期スクリプトの作成 » Java 同期論理の作成

 

ユーザ定義起動クラス

サーバの起動時に自動的にロードされる起動クラスを定義できます。この機能の目的は、最初の同期の前に Mobile Link サーバが JVM を起動する時点で実行される Java コードを記述できるようにすることです。つまり、ユーザ同期要求の前に、接続の作成またはデータのキャッシュを実行できます。

この操作を行うには、mlsrv11 -sl java オプションの DMLStartClasses オプションを使用します。たとえば、次に示すのは mlsrv11 コマンド・ラインの一部です。mycl1 と mycl2 が起動クラスとしてロードされます。

-sl java(-DMLStartClasses=com.test.mycl1,com.test.mycl2)

クラスはリスト内の順序でロードされます。同じクラスがリストに 2 回以上指定されている場合は、複数のインスタンスが作成されます。

起動クラスはすべてパブリックにしてください。また、引数を受け付けないか、ianywhere.ml.script.ServerContext 型の引数を 1 つ受け入れるパブリック・コンストラクタが必要です。

ロードされた起動クラスの名前は、「Java 起動クラス classname がロードされました。」というメッセージとともに Mobile Link ログに出力されます。

Java 仮想マシンのオプションの詳細については、-sl java オプションを参照してください。

サーバ起動時に構築される起動クラスを表示する方法については、getStartClassInstances メソッドを参照してください。

次に示すのは、起動クラスのテンプレートです。これは、イベントを処理してデータベース接続を確立するデーモン・スレッドを起動します(すべての起動クラスがスレッドの作成を必要とするわけではありませんが、スレッドを作成する場合はデーモン・スレッドでなければなりません)。

import ianywhere.ml.script.*;
import java.sql.*;

public class StartTemplate extends
    Thread implements ShutdownListener {
    ServerContext   _sc;
    Connection      _conn;
    boolean         _exit_loop;

    public StartTemplate(ServerContext sc) throws SQLException {

        // Perform setup first so that an exception 
        // causes MobiLink startup to fail.
        _sc = sc;

        // Create a connection for use later.
        _conn = _sc.makeConnection();

        _exit_loop = false;
        setDaemon(true);
        start();
    }

    public void run() {
        _sc.addShutdownListener(this);

        // run() cannot throw exceptions.
        try {
            handlerLoop();
            _conn.close();
            _conn = null;
        }
        catch(Exception e) {
    
            // Print some error output to the MobiLink log.
            e.printStackTrace();
 
            // This thread shuts down and so does not 
            // need to be notified of shutdown.
            _sc.removeShutdownListener(this);
    
            // Ask server to shutdown so that this fatal
            // error is fixed.
            _sc.shutdown();
        }
        // Shortly after return this thread no longer exists.
        return;
    }
 
    // stop our event handler loop
    public void shutdownPerformed(ServerContext sc) {
        try {
            // Wait max 10 seconds for thread to die.
            join(10*1000);
        }
        catch(Exception e) {
            // Print some error output to the MobiLink log.
            e.printStackTrace();
        }
    }

    private void handlerLoop() throws InterruptedException {
        while (!_exit_loop) {
            // Handle events in this loop. Sleep not
            // needed, block on event queue.
            sleep(1 * 1000);
        }
    }
}