java调用r,使用rJava从Java调用R脚本函数

在Windows环境中,使用Rserve调用R脚本的Java应用遇到并发问题,无法同时处理多个请求。通过检查发现,第二次请求时由于已有Rengine实例存在导致挂起。解决方法是检查并确保只有一个Rengine实例,使用Rengine.getMainEngine()获取或创建,并在结束时调用re.end()关闭R环境。
摘要由CSDN通过智能技术生成

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

int a = value.asInt();

System.out.println(a);

Maven dependency -

com.github.lucarosellini.rJava

JRI

0.9-7

com.github.lucarosellini.rJava

REngine

0.9-7

com.github.lucarosellini.rJava

JRIEngine

0.9-7

My R script file -

simple

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值