How to start rserve automatically from java in windows

自作多情 提交于 2019-12-12 05:14:29

问题


I have created a java application in eclipse. The application used Rserve package to connect to R and run r scripts. Before running my application, i have to start rserve from within Rstudio like this:

library(Rserve)
Rserve()

This Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically(in windows) as soon as the code is run so that I can skip this manual step of starting Rserve using through RStudio?


回答1:


The https://github.com/yannrichet/rsession project achieves exactly that for you.

Though it might be interesting to have a look at this: https://github.com/subes/invesdwin-context-r As it integrates RSession and keeps a pool of Rserve connections for performance reasons without you having to do much for it. You can also switch to other runtime solutions like JRI, RCaller, Renjin without having to change your script code.




回答2:


I'm not sure if there's a cleaner way to do this, but the way I've solved this is by starting it up console style from within my java program. For this to work, you have to put the path to the R executables in your systems path:

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://stackoverflow.com/questions/44246794/how-to-start-rserve-automatically-from-java-in-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!