创建会话 (v1)

创建新的 Dataproc 会话。

代码示例

Node.js

在尝试此示例之前,请按照《Managed Service for Apache Spark 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Managed Service for Apache Spark Node.js API 参考文档。

如需向 Managed Service for Apache Spark 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

'use strict';

const {SessionControllerClient} = require('@google-cloud/dataproc');
const {status} = require('@grpc/grpc-js');

/**
 * Creates a Dataproc session.
 *
 * @param {string} sessionId - The caller-chosen ID to use for the session, which becomes the final component of the session's resource name. Must be 4-63 characters containing lowercase letters, numbers, and hyphens.
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Dataproc location (region) where the session is created (for example, 'us-central1').
 */
async function createSession(sessionId, projectId, locationId) {
  // Dataproc is a regional service requiring the regional API endpoint.
  const client = new SessionControllerClient({
    apiEndpoint: `${locationId}-dataproc.googleapis.com`,
  });

  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const session = {
      jupyterSession: {
        kernel: 'PYTHON',
      },
    };

    const request = {
      parent,
      session,
      sessionId,
    };

    // Dataproc session creation is a long-running operation.
    const [operation] = await client.createSession(request);
    const [response] = await operation.promise();

    console.log(`Created session: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Session already exists: ${err.message}`);
    } else if (err.code) {
      console.error(`Google API error (${err.code}): ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createSession };

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器。