在Servlet中重用Nashorn ScriptEngine

在Servlet中重用Nashorn ScriptEngine,第1张

在Servlet中重用Nashorn ScriptEngine

javax.script.scriptEngineFactory
里面有一种方法
getParameter(Stringkey)

使用特殊键,

THREADING
您可以获得该特定引擎工厂线程信息。

这个小程序为每个注册的引擎工厂打印出此信息:

import javax.script.scriptEngineFactory;import javax.script.scriptEngineManager;public class scriptEngineTest {  public static void main(String[] args) {    final scriptEngineManager mgr = new scriptEngineManager();    for(scriptEngineFactory fac: mgr.getEngineFactories()) {      System.out.println(String.format("%s (%s), %s (%s), %s", fac.getEngineName(),          fac.getEngineVersion(), fac.getLanguageName(),          fac.getLanguageVersion(), fac.getParameter("THREADING")));    }  }}

对于Java 7,它是:

Mozilla Rhino (1.7 release 3 PRERELEASE), ECMAscript (1.8), MULTITHREADED

对于Java 8:

Oracle Nashorn (1.8.0_25), ECMAscript (ECMA - 262 Edition 5.1), null

null
表示引擎实现不是线程安全的。

在您的Servlet中,您可以使用

ThreadLocal
来为每个线程保留一个单独的引擎,从而允许将引擎重新用于同一线程所服务的后续请求。

public class MyServlet extends HttpServlet {  private ThreadLocal<scriptEngine> engineHolder;  @Override  public void init() throws ServletException {    engineHolder = new ThreadLocal<scriptEngine>() {      @Override      protected scriptEngine initialValue() {        return new scriptEngineManager().getEngineByName("nashorn");      }    };  }  @Override  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {    try (PrintWriter writer = res.getWriter()) {      scriptContext newContext = new SimplescriptContext();      newContext.setBindings(engineHolder.get().createBindings(), scriptContext.ENGINE_SCOPE);      Bindings engineScope = newContext.getBindings(scriptContext.ENGINE_SCOPE);      engineScope.put("writer", writer);      Object value = engineHolder.get().eval("writer.print('Hello, World!');", engineScope);      writer.close();    } catch (IOException | scriptException ex) {      Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);    }  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5489051.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存