새 Akamai CDN 키 만들기

동영상 애셋은 일반적으로 CDN이라고도 하는 콘텐츠 전송 네트워크를 통해 배포됩니다. 콘텐츠가 보호되도록 동영상 애셋 URL을 검색하려면 서명을 요구할 수 있습니다. 이를 URL 서명이라고 합니다. 동영상 애셋에 대한 API 액세스를 사용 설정하는 CDN 키를 만듭니다.

코드 샘플

C#

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용C# 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API C# API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf;
using System.Threading.Tasks;

public class CreateCdnKeyAkamaiSample
{
    public async Task<CdnKey> CreateCdnKeyAkamaiAsync(
        string projectId, string location, string cdnKeyId, string hostname,
        string akamaiTokenKey)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            Hostname = hostname,
            AkamaiCdnKey = new AkamaiCdnKey
            {
                TokenKey = ByteString.CopyFromUtf8(akamaiTokenKey)
            }
        };

        CreateCdnKeyRequest request = new CreateCdnKeyRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            CdnKeyId = cdnKeyId,
            CdnKey = cdnKey
        };

        // Make the request.
        Operation<CdnKey, OperationMetadata> response = await client.CreateCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<CdnKey, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API Go API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createCDNKeyAkamai creates an Akamai CDN key. A CDN key is used to retrieve
// protected media.
func createCDNKeyAkamai(w io.Writer, projectID, keyID, akamaiTokenKey string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// akamaiTokenKey := "my-private-token-key"
	location := "us-central1"
	hostname := "cdn.example.com"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.CreateCdnKeyRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		CdnKeyId: keyID,
		CdnKey: &stitcherstreampb.CdnKey{
			CdnKeyConfig: &stitcherstreampb.CdnKey_AkamaiCdnKey{
				AkamaiCdnKey: &stitcherstreampb.AkamaiCdnKey{
					TokenKey: []byte(akamaiTokenKey),
				},
			},
			Hostname: hostname,
		},
	}

	// Creates the CDN key.
	op, err := client.CreateCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateCdnKey: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "CDN key: %v", response.GetName())
	return nil
}

Java

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API Java API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.video.stitcher.v1.AkamaiCdnKey;
import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CreateCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateCdnKeyAkamai {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";
    String hostname = "cdn.example.com";
    String akamaiTokenKey = "my-token-key"; // will be converted to a byte string

    createCdnKeyAkamai(projectId, location, cdnKeyId, hostname, akamaiTokenKey);
  }

  // createCdnKeyAkamai creates an Akamai CDN key. A CDN key is used to retrieve protected media.
  public static void createCdnKeyAkamai(
      String projectId, String location, String cdnKeyId, String hostname, String akamaiTokenKey)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    VideoStitcherServiceClient videoStitcherServiceClient = VideoStitcherServiceClient.create();
    CdnKey cdnKey =
        CdnKey.newBuilder()
            .setHostname(hostname)
            .setAkamaiCdnKey(
                AkamaiCdnKey.newBuilder()
                    .setTokenKey(ByteString.copyFromUtf8(akamaiTokenKey))
                    .build())
            .build();

    CreateCdnKeyRequest createCdnKeyRequest =
        CreateCdnKeyRequest.newBuilder()
            .setParent(LocationName.of(projectId, location).toString())
            .setCdnKeyId(cdnKeyId)
            .setCdnKey(cdnKey)
            .build();

    CdnKey result =
        videoStitcherServiceClient
            .createCdnKeyAsync(createCdnKeyRequest)
            .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
    System.out.println("Created new CDN key: " + result.getName());
    videoStitcherServiceClient.close();
  }
}

Node.js

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API Node.js API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const location = 'us-central1';
const hostname = 'cdn.example.com';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// akamaiTokenKey = 'my-token-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createCdnKeyAkamai() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    cdnKey: {
      hostname: hostname,
      akamaiCdnKey: {
        tokenKey: akamaiTokenKey,
      },
    },
    cdnKeyId: cdnKeyId,
  };

  const [operation] = await stitcherClient.createCdnKey(request);
  const [response] = await operation.promise();
  console.log(`CDN key: ${response.name}`);
}

createCdnKeyAkamai();

PHP

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용PHP 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API PHP API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Video\Stitcher\V1\AkamaiCdnKey;
use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateCdnKeyRequest;

/**
 * Creates an Akamai CDN key.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the CDN key
 * @param string  $cdnKeyId           The ID of the CDN key to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $tokenKey           The base64-encoded string token key for
 *                                    the Akamai CDN edge configuration
 */
function create_cdn_key_akamai(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $tokenKey
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $cdnKey = new CdnKey();
    $cdnKey->setHostname($hostname);
    $cloudCdn = new AkamaiCdnKey();
    $cloudCdn->setTokenKey($tokenKey);
    $cdnKey->setAkamaiCdnKey($cloudCdn);

    // Run CDN key creation request
    $request = (new CreateCdnKeyRequest())
        ->setParent($parent)
        ->setCdnKey($cdnKey)
        ->setCdnKeyId($cdnKeyId);
    $operationResponse = $stitcherClient->createCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('CDN key: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API Python API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)

def create_cdn_key_akamai(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    akamai_token_key: str,
) -> stitcher_v1.types.CdnKey:
    """Creates an Akamai CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the CDN key.
        cdn_key_id: The user-defined CDN key ID.
        hostname: The hostname to which this CDN key applies.
        akamai_token_key: A base64-encoded string token key.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    cdn_key = stitcher_v1.types.CdnKey(
        name=cdn_key_id,
        hostname=hostname,
        akamai_cdn_key=stitcher_v1.types.AkamaiCdnKey(
            token_key=akamai_token_key,
        ),
    )

    operation = client.create_cdn_key(
        parent=parent, cdn_key_id=cdn_key_id, cdn_key=cdn_key
    )
    response = operation.result()
    print(f"CDN key: {response.name}")
    return response

Ruby

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Ruby 설정 안내를 따르세요. 자세한 내용은 Video Stitcher API Ruby API 참조 문서를 확인하세요.

Video Stitcher API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정하세요. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

require "google/cloud/video/stitcher"

##
# Create an Akamai CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param cdn_key_id [String] The user-defined CDN key ID
# @param hostname [String] The hostname to which this CDN key applies
# @param akamai_token_key [String] Applies to an Akamai CDN key. A
#   base64-encoded string token key.
#
def create_cdn_key_akamai project_id:, location:, cdn_key_id:, hostname:,
                          akamai_token_key:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location
  # Build the path for the CDN key resource.
  cdn_key_path = client.cdn_key_path project: project_id, location: location,
                                     cdn_key: cdn_key_id

  # Set the CDN key fields.
  new_cdn_key = {
    name: cdn_key_path,
    hostname: hostname,
    akamai_cdn_key: {
      token_key: akamai_token_key
    }
  }

  operation = client.create_cdn_key parent: parent, cdn_key: new_cdn_key,
                                    cdn_key_id: cdn_key_id

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the CDN key name.
  puts "CDN key: #{operation.response.name}"
end

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.