繁体   English   中英

如何在Windows中从Java自动启动Rserve

[英]How to start rserve automatically from java in windows

我在eclipse中创建了一个Java应用程序。 该应用程序使用Rserve软件包连接到R和运行r脚本。 在运行我的应用程序之前,我必须像这样从Rstudio中启动rserve:

library(Rserve)
Rserve()

该Java代码将作为可执行文件捆绑在一起,因此有没有一种方法可以在代码运行后立即自动在Windows中调用Rserve(),这样我就可以跳过通过RStudio使用Rserve启动该手动步骤?

我不确定是否有更清洁的方法来执行此操作,但是我解决此问题的方法是从Java程序中启动控制台样式。 为此,您必须将R可执行文件的路径放在系统路径中:

public Process rserve = null;

public static void startRServer() throws InterruptedException, IOException {
    // check the runtime environment to see if there's an active Rserve running
    String existingRserve = "";
    try {
        Process p = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq Rserve.exe\"");
        p.waitFor();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        existingRserve = in.readLine();
    } catch(IOException e){}

    if(rserve == null || existingRserve.contains("No tasks are running")) {
        // start and rserve if we don't have one for this run yet, 
        // or if it has unexpectedly failed since we last used it
        try {
            rserve = Runtime.getRuntime().exec("Rscript -e \"library(Rserve); Rserve()\"");
            rserve.waitFor();
        } catch (IOException e) {
            System.out.print("*** R Error: Unable to start the R server ***");
        }
    }
}

https://github.com/yannrichet/rsession项目完全可以为您实现目标。

尽管看一下它可能很有趣: https : //github.com/subes/invesdwin-context-r由于它集成了RSession并出于性能原因保留了Rserve连接池,而无需为此做很多事情。 您也可以切换到其他运行时解决方案,例如JRI,RCaller,Renjin,而无需更改脚本代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM