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

SQL Anywhere 11.0.1 (中文) » MobiLink - 服务器管理 » MobiLink 服务器 API » 使用 Java 语言编写同步脚本 » 编写 Java 同步逻辑

 

用户定义的启动类

可以定义在服务器启动时自动装载的启动类。利用这一功能,您可以编写在 MobiLink 服务器启动 JVM 时(第一次同步之前)执行的 Java 代码。这意味着您可以在用户同步请求之前创建连接或缓存数据。

可使用 mlsrv11 -sl java 选项的 DMLStartClasses 选项来进行创建。例如,以下是 mlsrv11 命令行的部分内容。它将使 mycl1 和 mycl2 作为启动类装载。

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

将按所列顺序装载各个类。如果多次列出同一个类,则会创建多个实例。

所有启动类必须都是公共的,并且必须具有一个不接受任何参数或接受一个类型为 ianywhere.ml.script.ServerContext 的参数的公共构造函数。

装载的启动类的名称输出到 MobiLink 日志,显示以下消息:"已装载 JAVA 启动类:classname"。

有关 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);
        }
    }
}