יצירת סשן (גרסה 1)

יוצרים סשן חדש ב-Dataproc.

דוגמת קוד

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של Managed Service for Apache Spark באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Managed Service for Apache Spark Node.js API.

כדי לבצע אימות ב-Managed Service for Apache Spark, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

'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 .