مشاركة عبر


استخدم #C مع MapReduce المتدفقة على Apache Hadoop في HDInsight

تعرّف على كيفية استخدام #C لإنشاء حل MapReduce على HDInsight.

يسمح لك دفق Apache Hadoop بتشغيل وظائف MapReduce باستخدام برنامج نصي أو ملف تنفيذي. هنا، يتم استخدام NET. لتنفيذ المخطط والمخفض لحل عدد الكلمات.

NET على HDInsight

تستخدم مجموعات HDInsight Mono (https://mono-project.com) لتشغيل تطبيقات NET. يتم تضمين إصدار Mono 4.2.1 مع HDInsight الإصدار 3.6. لمزيدٍ من المعلومات حول إصدار Mono المضمن مع HDInsight، راجع مكونات Apache Hadoop المتوفرة مع إصدارات HDInsight.

لمزيدٍ من المعلومات حول التوافق الأحادي مع إصدارات.NET Framework، راجع التوافق الأحادي.

كيف يعمل Hadoop المتدفق

العملية الأساسية المستخدمة للدفق في هذا المستند هي كما يلي:

  1. يقوم Hadoop بتمرير البيانات إلى مصمم الخرائط (mapper.exe في هذا المثال) على STDIN.
  2. يقوم المعين بمعالجة البيانات، ويصدر أزواج مفتاح/قيمة محددة بعلامات جدولة إلى STDOUT.
  3. تتم قراءة الإخراج بواسطة Hadoop، ثم يتم تمريره إلى جهاز التخفيض (reducer.exe في هذا المثال) على STDIN.
  4. يقرأ المخفض أزواج المفتاح/القيمة المحددة بعلامات جدولة، ويعالج البيانات، ثم يرسل النتيجة كأزواج مفتاح/قيمة محددة بعلامات جدولة في STDOUT.
  5. تتم قراءة الإخراج بواسطة Hadoop وكتابته إلى دليل الإخراج.

لمزيدٍ من المعلومات حول البث، راجع Hadoop Streaming.

المتطلبات الأساسية

  • Visual Studio.

  • الإلمام بكتابة وبناء التعليمة البرمجية #C الذي يستهدف.NET Framework 4.5.

  • طريقة لتحميل ملفات exe. إلى نظام المجموعة. تستخدم الخطوات الواردة في هذا المستند Data Lake Tools لـ Visual Studio لتحميل الملفات إلى التخزين الأساسي للمجموعة.

  • إذا كنت تستخدم PowerShell، فستحتاج إلى Az Module.

  • نظام مجموعة Apache Hadoop على HDInsight. راجع بدء استخدام HDInsight على Linux.

  • مخطط URI للتخزين الأساسي لمجموعاتك. سيكون هذا المخطط wasb:// لتخزين Azure، abfs:// لوحدة تخزين Azure Data Lake Gen2 أو adl:// لـ Azure Data Lake Storage Gen1. إذا تم تمكين النقل الآمن لـ Azure Storage أو Data Lake Storage Gen2، فسيكون URI wasbs:// أو abfss://، على التوالي.

قم بإنشاء مخطط الخرائط

في Visual Studio، قم بإنشاء تطبيق وحدة تحكم.NET Framework جديد باسم mapper. استخدم التعليمة البرمجية التالية للتطبيق:

using System;
using System.Text.RegularExpressions;

namespace mapper
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            //Hadoop passes data to the mapper on STDIN
            while((line = Console.ReadLine()) != null)
            {
                // We only want words, so strip out punctuation, numbers, etc.
                var onlyText = Regex.Replace(line, @"\.|;|:|,|[0-9]|'", "");
                // Split at whitespace.
                var words = Regex.Matches(onlyText, @"[\w]+");
                // Loop over the words
                foreach(var word in words)
                {
                    //Emit tab-delimited key/value pairs.
                    //In this case, a word and a count of 1.
                    Console.WriteLine("{0}\t1",word);
                }
            }
        }
    }
}

بعد إنشاء التطبيق، قم بإنشائه لإنتاج /bin/Debug/mapper.exe الملف في دليل المشروع.

إنشاء المخفض

في Visual Studio، قم بإنشاء تطبيق وحدة تحكم.NET Framework جديد باسم reducer. استخدم التعليمة البرمجية التالية للتطبيق:

using System;
using System.Collections.Generic;

namespace reducer
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dictionary for holding a count of words
            Dictionary<string, int> words = new Dictionary<string, int>();

            string line;
            //Read from STDIN
            while ((line = Console.ReadLine()) != null)
            {
                // Data from Hadoop is tab-delimited key/value pairs
                var sArr = line.Split('\t');
                // Get the word
                string word = sArr[0];
                // Get the count
                int count = Convert.ToInt32(sArr[1]);

                //Do we already have a count for the word?
                if(words.ContainsKey(word))
                {
                    //If so, increment the count
                    words[word] += count;
                } else
                {
                    //Add the key to the collection
                    words.Add(word, count);
                }
            }
            //Finally, emit each word and count
            foreach (var word in words)
            {
                //Emit tab-delimited key/value pairs.
                //In this case, a word and a count of 1.
                Console.WriteLine("{0}\t{1}", word.Key, word.Value);
            }
        }
    }
}

بعد إنشاء التطبيق، قم بإنشائه لإنتاج /bin/Debug/reducer.exe الملف في دليل المشروع.

تحميل إلى التخزين

بعد ذلك، تحتاج إلى تحميل تطبيقات mapper وreducer إلى تخزين HDInsight.

  1. في Visual Studio، حدد View>Server Explorer.

  2. انقر بزر الماوس الأيمن فوق Azure، وحدد الاتصال باشتراك Microsoft Azure...، وأكمل عملية تسجيل الدخول.

  3. قم بتوسيع مجموعة HDInsight التي ترغب في نشر هذا التطبيق عليها. تم إدراج إدخال بالنص (حساب التخزين الافتراضي).

    حساب التخزين، نظام مجموعة HDInsight، مستكشف الخادم، Visual Studio.

    • إذا كان من الممكن توسيع إدخال (حساب التخزين الافتراضي)، فأنت تستخدم حساب تخزين Azure كتخزين افتراضي للمجموعة. لعرض الملفات على وحدة التخزين الافتراضية للمجموعة، قم بتوسيع الإدخال ثم انقر نقراً مزدوجاً فوق (حاوية افتراضية).

    • إذا تعذر توسيع الإدخال (حساب التخزين الافتراضي)، فأنت تستخدم Azure Data Lake Storage باعتباره التخزين الافتراضي للمجموعة. لعرض الملفات على وحدة التخزين الافتراضية للمجموعة، انقر نقراً مزدوجاً فوق الإدخال (حساب التخزين الافتراضي).

  4. لتحميل ملفات exe.، استخدم إحدى الطرق التالية:

    • إذا كنت تستخدم حساب تخزين Azure، فحدد رمز تحميل Blob.

      أيقونة تحميل HDInsight لمعين، Visual Studio.

      في مربع الحوار Upload New File، ضمن File name، حدد Browse. في مربع الحوار تحميل Blob، انتقل إلى المجلد bin \ debug لمشروع mapper، ثم اختر mapper.exe ملف. أخيراً، حدد Open ثم OK لإكمال التحميل.

    • بالنسبة إلى Azure Data Lake Storage، انقر بزر الماوس الأيمن فوق منطقة فارغة في قائمة الملف، ثم حدد Upload. أخيراً، حدد ملف mapper.exe ثم حدد Open.

    بمخزون انتهاء تحميل mapper.exe، كرر عملية التحميل لملف reducer.exe.

قم بتشغيل دالة: استخدام جلسة SSH

يصف الإجراء التالي كيفية تشغيل مهمة MapReduce باستخدام جلسة SSH:

  1. استخدم الأمر ssh للاتصال بنظام المجموعة الخاص بك. قم بتحرير الأمر أدناه عن طريق استبدال اسم نظام المجموعة باسم نظام مجموعتك ثم إدخال الأمر:

    ssh sshuser@CLUSTERNAME-ssh.azurehdinsight.net
    
  2. استخدم أحد الأوامر التالية لبدء مهمة MapReduce:

    • إذا كان التخزين الافتراضي هو Azure Storage:

      yarn jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar \
          -files wasbs:///mapper.exe,wasbs:///reducer.exe \
          -mapper mapper.exe \
          -reducer reducer.exe \
          -input /example/data/gutenberg/davinci.txt \
          -output /example/wordcountout
      
    • إذا كان التخزين الافتراضي هو Data Lake Storage Gen1:

      yarn jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar \
          -files adl:///mapper.exe,adl:///reducer.exe \
          -mapper mapper.exe \
          -reducer reducer.exe \
          -input /example/data/gutenberg/davinci.txt \
          -output /example/wordcountout
      
    • إذا كان التخزين الافتراضي هو Data Lake Storage Gen2:

      yarn jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar \
          -files abfs:///mapper.exe,abfs:///reducer.exe \
          -mapper mapper.exe \
          -reducer reducer.exe \
          -input /example/data/gutenberg/davinci.txt \
          -output /example/wordcountout
      

    تصف القائمة التالية ما يمثله كل معلمة وخيار:

    المعلمة ‏‏الوصف‬
    hadoop-streaming.jar يحدد ملف jar الذي يحتوي على دالة MapReduce المتدفقة.
    -الملفات يحدد ملفي mapper.exe وauther.exe لهذه المهمة. يعتبر تعريف البروتوكول wasbs:///أو adl:///أو abfs:/// قبل كل ملف هو المسار إلى جذر التخزين الافتراضي للمجموعة.
    -mapper يحدد الملف الذي يقوم بتنفيذ مخطط الخرائط.
    -reducer يحدد الملف الذي يقوم بتنفيذ المخفض.
    -input يحدد بيانات الإدخال.
    -output يحدد دليل الإخراج.
  3. بمخزون اكتمال مهمة MapReduce، استخدم الأمر التالي لعرض النتائج:

    hdfs dfs -text /example/wordcountout/part-00000
    

    النص التالي هو مثال على البيانات التي أرجعها هذا الأمر:

    you     1128
    young   38
    younger 1
    youngest        1
    your    338
    yours   4
    yourself        34
    yourselves      3
    youth   17
    

قم بتشغيل دالة: باستخدام PowerShell

استخدم البرنامج النصي PowerShell التالي لتشغيل مهمة MapReduce وتنزيل النتائج.

# Login to your Azure subscription
$context = Get-AzContext
if ($context -eq $null) 
{
    Connect-AzAccount
}
$context

# Get HDInsight info
$clusterName = Read-Host -Prompt "Enter the HDInsight cluster name"
$creds=Get-Credential -Message "Enter the login for the cluster"

# Path for job output
$outputPath="/example/wordcountoutput"

# Progress indicator
$activity="C# MapReduce example"
Write-Progress -Activity $activity -Status "Getting cluster information..."
#Get HDInsight info so we can get the resource group, storage, etc.
$clusterInfo = Get-AzHDInsightCluster -ClusterName $clusterName
$resourceGroup = $clusterInfo.ResourceGroup
$storageActArr=$clusterInfo.DefaultStorageAccount.split('.')
$storageAccountName=$storageActArr[0]
$storageType=$storageActArr[1]

# Progress indicator
#Define the MapReduce job
# Note: using "/mapper.exe" and "/reducer.exe" looks in the root
#       of default storage.
$jobDef=New-AzHDInsightStreamingMapReduceJobDefinition `
    -Files "/mapper.exe","/reducer.exe" `
    -Mapper "mapper.exe" `
    -Reducer "reducer.exe" `
    -InputPath "/example/data/gutenberg/davinci.txt" `
    -OutputPath $outputPath

# Start the job
Write-Progress -Activity $activity -Status "Starting MapReduce job..."
$job=Start-AzHDInsightJob `
    -ClusterName $clusterName `
    -JobDefinition $jobDef `
    -HttpCredential $creds

#Wait for the job to complete
Write-Progress -Activity $activity -Status "Waiting for the job to complete..."
Wait-AzHDInsightJob `
    -ClusterName $clusterName `
    -JobId $job.JobId `
    -HttpCredential $creds

Write-Progress -Activity $activity -Completed

# Download the output 
if($storageType -eq 'azuredatalakestore') {
    # Azure Data Lake Store
    # Fie path is the root of the HDInsight storage + $outputPath
    $filePath=$clusterInfo.DefaultStorageRootPath + $outputPath + "/part-00000"
    Export-AzDataLakeStoreItem `
        -Account $storageAccountName `
        -Path $filePath `
        -Destination output.txt
} else {
    # Az.Storage account
    # Get the container
    $container=$clusterInfo.DefaultStorageContainer
    #NOTE: This assumes that the storage account is in the same resource
    #      group as HDInsight. If it is not, change the
    #      --ResourceGroupName parameter to the group that contains storage.
    $storageAccountKey=(Get-AzStorageAccountKey `
        -Name $storageAccountName `
    -ResourceGroupName $resourceGroup)[0].Value

    #Create a storage context
    $context = New-AzStorageContext `
        -StorageAccountName $storageAccountName `
        -StorageAccountKey $storageAccountKey
    # Download the file
    Get-AzStorageBlobContent `
        -Blob 'example/wordcountoutput/part-00000' `
        -Container $container `
        -Destination output.txt `
        -Context $context
}

يطالبك هذا البرنامج النصي باسم حساب تسجيل الدخول إلى المجموعة وكلمة المرور، إلى جانب اسم مجموعة HDInsight. بمخزون اكتمال المهمة، يتم تنزيل الإخراج إلى ملف يُسمى output.txt. النص التالي هو مثال على البيانات الموجودة في ملف output.txt :

you     1128
young   38
younger 1
youngest        1
your    338
yours   4
yourself        34
yourselves      3
youth   17

الخطوات التالية