Calling R script function from Java using rJava

2019-04-17 09:15发布

问题:

My Requirement -

I need to deploy a Java webservice in a server which internally executes a R scipt file. I googled about various solutions for calling R from Java and the best were rJava and Rserve. Using Rserve I can call R function BUT as I am running this in Windows it can not handle multiple requests at a time and I dont want to switch to Linux.

[Edit]

What I tried - I have used rJava to call a R function :

    String[] args = new String[3];
    args[0] = "--quiet"; // Don't print startup message
    args[1] = "--no-restore"; // Don't restore anything
    args[2] = "--no-save";
    String rFilePath = "D:/Dataset_Info/AI-KMS_v2.0/tika/src/main/resources/HSConcordance.R";
    Rengine engine = new Rengine(args, false, null);
    if (!engine.waitForR()) {
        System.out.println("Cannot load R");
    }
    System.out.print("JRI R-Engine call: ");
    engine.eval("source(\"" + rFilePath + "\")");
    REXP value = engine.eval("as.integer(a<-simple())");
    int a = value.asInt();
    System.out.println(a);

Maven dependency -

    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>JRI</artifactId>
        <version>0.9-7</version>
    </dependency>
    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>REngine</artifactId>
        <version>0.9-7</version>
    </dependency>
    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>JRIEngine</artifactId>
        <version>0.9-7</version>
    </dependency>

My R script file -

simple<-function(){
a=1
return(a)
}

Output - JRI R-Engine call: 1 and then it hangs. I debugged it and found that it got stuck in Thread.class

Any kind of help will be greatly appreciated.

回答1:

The issue was when I am acessing the webservice for the 2nd time it got hanged because we already have an instance of Rengine present which was created at first call.

    Rengine re = Rengine.getMainEngine();
    if(re == null){
        re=new Rengine (new String [] {"--vanilla"}, false, null);
        if (!re.waitForR())
        {
            System.out.println ("Cannot load R");
            return "failure";
        }
    }
    re.eval("source(\"" + rFilePath + "\")");
    re.eval("copyfile(\""+filePath+"\")");
    re.end();

Few points to note -

  • Check if any instance of Rengine is already present by Rengine re = Rengine.getMainEngine();
  • Shut down R in the end by re.end();

It may be helpful. thanks.