13.3. 运行脚本和任务

使用命令行界面在 Data Grid Server 部署上运行任务和脚本。或者,您也可以从 Hot Rod 客户端执行脚本和任务。

先决条件

  • 在 Data Grid Server 中添加脚本或任务。

流程

  1. 创建与 Data Grid 的 CLI 连接。
  2. 使用 task 命令运行任务和脚本,如下例所示:

    • 执行名为 multiplier.js 的脚本,并指定两个参数:

      task exec multiplier.js -Pmultiplicand=10 -Pmultiplier=20
      200.0
    • 执行名为 @@cache@names 的任务,以检索所有可用缓存的列表:

      task exec @@cache@names
      ["___protobuf_metadata","mycache","___script_cache"]

程序执行

  • 使用 Hot Rod RemoteCache 接口调用 execute () 方法来运行脚本,如下例所示:

脚本执行

RemoteCache<String, Integer> cache = cacheManager.getCache();
// Create parameters for script execution.
Map<String, Object> params = new HashMap<>();
params.put("multiplicand", 10);
params.put("multiplier", 20);
// Run the script with the parameters.
Object result = cache.execute("multiplication.js", params);

任务执行

// Add configuration for a locally running server.
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(11222);

// Connect to the server.
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());

// Retrieve the remote cache.
RemoteCache<String, String> cache = cacheManager.getCache();

// Create task parameters.
Map<String, String> parameters = new HashMap<>();
parameters.put("name", "developer");

// Run the server task.
String greet = cache.execute("hello-task", parameters);
System.out.println(greet);