如何将 java 对象传递到 servlet 环境中的嵌入式 JRuby 容器?
我需要一种在多线程环境中执行 jruby 脚本的方法,其中脚本的每次执行都会传递一个不同的 java 对象。
目前,我可以使用以下代码运行独立的脚本:
public class Executor {
public Executor() {
this.container = new ScriptingContainer(LocalContextScope.THREADSAFE, LocalVariableBehavior.TRANSIENT);
this.evalUnit = this.container.parse(getScriptContent());
}
public execute(HttpServletRequest request) {
this.evalUnit.run()
}
}
似乎执行良好,因为 ruby 脚本在构造函数中解析到 evalUnit 中一次,并且不需要在每次执行时重新解析。
但是,我希望能够将请求对象传递给脚本,但我找不到正确的方法来做到这一点。会有多个同时请求,所以我认为我不能使用 this.container.put("$request", request),对吗?
更新 在 JRuby 1.6 中,现在有一个 LocalContextScope.CONCURRENT ,这似乎就是我正在寻找的。据我所知,如果我将 ScriptingContainer 构造为 new ScriptingContainer(LocalContextScope.CONCURRENT, LocalVariableBehavior.TRANSIENT) 那么我可以调用
container.getProvider().getVarMap().put("@request", request);
service.getEvalUnit().run();
并且每个线程都有自己的 @request 值。
我对这个用法的理解正确吗?
I need a way to execute a jruby script in a multi-threaded environment, where each execution of the script is passed a different java object.
Currently, I am able to run self-contained scripts using code like:
public class Executor {
public Executor() {
this.container = new ScriptingContainer(LocalContextScope.THREADSAFE, LocalVariableBehavior.TRANSIENT);
this.evalUnit = this.container.parse(getScriptContent());
}
public execute(HttpServletRequest request) {
this.evalUnit.run()
}
}
Which appears to perform well since the ruby script is parsed once in the constructor into the evalUnit and does not need to be re-parsed on each execution.
However, I want to be able to pass the request object to the script, but I cannot find the correct way to do that. There will be multiple simultaneous requests, so I don't think I can use this.container.put("$request", request), correct?
UPDATE
In JRuby 1.6 there is now a LocalContextScope.CONCURRENT which appears to be what I am looking for. From what I can tell, if I construct ScriptingContainer as new ScriptingContainer(LocalContextScope.CONCURRENT, LocalVariableBehavior.TRANSIENT) then I can call
container.getProvider().getVarMap().put("@request", request);
service.getEvalUnit().run();
and each thread will have its own @request value.
Am I understanding this usage correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论