且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Servlet中重用Nashorn ScriptEngine

更新时间:2023-11-18 17:13:34

javax.script.ScriptEngineFactory 中有一个方法 getParameter(String key)

In javax.script.ScriptEngineFactory there is a method getParameter(String key).

使用特殊键 THREADING ,您将获得此特定的线程信息发动机工厂。

With the special key THREADING you get threading information for this specific engine factory.

这个小程序为每个注册的发动机工厂打印出这些信息:

This small program prints out this information for every registered engine factory:

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,它是:

For Java 7 it is:

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 表示引擎实现不是线程安全的。

null means the engine implementation is not thread safe.

在你的servlet中你可以使用 ThreadLocal 为每个人保留一个单独的引擎线程允许为同一线程提供的后续请求重用引擎。

In your servlet you can use a ThreadLocal to hold a seperate engine for each thread allowing to reuse the engine for subsequent requests served by the same thread.

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);
    }
  }
}