如何等待Spark服务停止?

时间:2017-09-27 15:05:00

标签: java spark-java

对于我的Spark API,我正在构建集成测试。有时我想停止并启动Spark实例。当我这样做时,我有时遇到的问题是我正在创建一个新的Spark实例,而旧的实例仍在关闭一个单独的线程。了解Spark实例何时实际关闭会很有帮助。

首先,我启动我的Spark实例:

Spark.init();
Spark.awaitInitialization();

然后我就这样停止:

Spark.stop();

现在我打电话给stop()后,Spark服务实际上并没有停止!

是否有与awaitInitialization()类似的功能或其他了解Spark服务何时实际停止的方式?

3 个答案:

答案 0 :(得分:1)

我在https://github.com/perwendel/spark/issues/731中阅读了此解决方案并为我工作:

public static void stopServer() {
        try {
            Spark.stop();
            while (true) {
                try {
                    Spark.port();
                    Thread.sleep(500);
                } catch (final IllegalStateException ignored) {
                    break;
                }
            }
        } catch (final Exception ex) {
            // Ignore
        }
    }

答案 1 :(得分:1)

Spark 2.8.0引入了awaitShutdown()方法:https://github.com/perwendel/spark/pull/730

如果您坚持使用以下版本(例如,使用使用Spark 2.6.0的spark-kotlin),则可以使用一些反射来标识Spark的当前状态:

    fun awaitShutdown() {
        Spark.stop()

        while (isSparkInitialized()) {
            Thread.sleep(100)
        }
    }

    /**
     * Access the internals of Spark to check if the "initialized" flag is already set to false.
     */
    private fun isSparkInitialized(): Boolean {
        val sparkClass = Spark::class.java
        val getInstanceMethod = sparkClass.getDeclaredMethod("getInstance")
        getInstanceMethod.isAccessible = true
        val service = getInstanceMethod.invoke(null) as Service

        val serviceClass = service::class.java
        val initializedField = serviceClass.getDeclaredField("initialized")
        initializedField.isAccessible = true
        val initialized = initializedField.getBoolean(service)

        return initialized
    }

(摘自https://github.com/debuglevel/sparkmicroserviceutils/blob/ec6b9692d808ecc448f1828f5487739101a2f62e/src/main/kotlin/de/debuglevel/microservices/utils/spark/SparkTestUtils.kt

答案 2 :(得分:0)

我使用spark-java为集成/功能测试构建模拟服务。

我的测试推断代码:

public FakeServer shutdown() {
    service.stop();
    // Remove when https://github.com/perwendel/spark/issues/705 is fixed.
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return this;
}

无缝地为我工作,每次测试都设置了FakeServer @Before并在测试完成时将其撕下 - @After。

试一试。