El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

HDFS Application Development Rules

Updated on 2024-08-30 GMT+08:00

Set the HDFS NameNode metadata storage path

NameNode metadata is stored in ${BIGDATA_DATA_HOME}/namenode/data by default. This parameter sets the storage path of HDFS metadata.

Enable NameNode image backup for the HDFS

fs.namenode.image.backup.enable specifies whether to enable the NameNode image backup function. You need to set this parameter to true. Then the system can periodically back up the NameNode data.

Set the HDFS DataNode data storage path

DataNode data is stored in ${BIGDATA_DATA_HOME}/hadoop/dataN/dn/datadir by default. N indicates the number of directories is greater than or equal to1.

For example, ${BIGDATA_DATA_HOME}/hadoop/data1/dn/datadir, ${BIGDATA_DATA_HOME}/hadoop/data2/dn/datadir.

After the storage path is set, data is stored in the corresponding directory of each mounted disk on a node.

Improve HDFS read/write performance

The data write process is as follows:

After receiving service data and obtaining the data block number and location from the NameNode, the HDFS client contacts DataNodes and establishes a pipeline with the DataNodes to be written. Then, the HDFS client writes data to DataNode1 using a proprietary protocol, and DataNode1 writes data to DataNode2 and DataNode3 (three duplicates). After data is written, a message is returned to the HDFS client.

  1. Set a proper block size. For example, set dfs.blocksize to 268435456 (256 MB).
  2. It is not necessary to cache the big data that is not reused. In this case, set the following parameters to false:

    dfs.datanode.drop.cache.behind.reads and dfs.datanode.drop.cache.behind.writes

Set the MapReduce intermediate file storage path

Only one default path is provided for storing MapReduce intermediate files, that is, ${hadoop.tmp.dir}/mapred/local.It is recommended that intermediate files be stored on each disk.

For example, /hadoop/hdfs/data1/mapred/local, /hadoop/hdfs/data2/mapred/local, /hadoop/hdfs/data3/mapred/local. Directories that do not exist are automatically ignored.

Release applied resources in finally during Java development.

Applied HDFS resources are released in try/finally and cannot be released outside the try statement only. Otherwise, resource leakage occurs.

HDFS file operation APIs

Almost all Hadoop file operation classes are in the org.apache.hadoop.fs package. These APIs support operations such as opening, reading, writing, and deleting a file. FileSystem is the interface class provided for users in the Hadoop class library. FileSystem is an abstract class. Concrete classes can be obtained only using the get method. The get method has multiple overload versions, and the following get method is often used.

static FileSystem get(Configuration conf);

This class encapsulates almost all file operations, such as mkdir and delete. The program library framework for file operations is as follows:

operator() 
{
     Obtain the Configuration object.
     Obtain the FileSystem object.
     Perform file operations.
 } 

HDFS initialization method

HDFS initialization is a prerequisite for using APIs provided by HDFS.

To initialize HDFS, load the HDFS service configuration file, implement Kerberos security authentication, and instantiate FileSystem. Obtain keytab files for Kerberos security authentication in advance.

Example:
private  void init() throws IOException {
 Configuration conf = new Configuration();
 // Read a configuration file.
  conf.addResource("user-hdfs.xml");
 // Implement security authentication in security mode.
  if ("kerberos".equalsIgnoreCase(conf.get("hadoop.security.authentication"))) {
 String PRINCIPAL = "username.client.kerberos.principal";
 String KEYTAB = "username.client.keytab.file";
 // Set the keytab key file.
  conf.set(KEYTAB, System.getProperty("user.dir") + File.separator + "conf" + File.separator + conf.get(KEYTAB));
  // Set the Kerberos configuration file path. */
 String krbfilepath = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "krb5.conf";
 System.setProperty("java.security.krb5.conf", krbfilepath);
 // Implement login authentication. */
 SecurityUtil.login(conf, KEYTAB, PRINCIPAL);
 }
  // Instantiate FileSystem.
 fSystem = FileSystem.get(conf);
 } 

Upload local files to the HDFS

FileSystem.copyFromLocalFile (Path src, Patch dst) is used to upload local files to a specified directory in the HDFS. src and dst indicate complete file paths.

Example:

public class CopyFile {
        public static void main(String[] args) throws Exception { 
        Configuration conf=new Configuration();
        FileSystem hdfs=FileSystem.get(conf);
              //Local file
                 Path src =new Path("D:\\HebutWinOS");
                  //To the HDFS
        Path dst =new Path("/"); 
               hdfs.copyFromLocalFile(src, dst);
        System.out.println("Upload to"+conf.get("fs.default.name"));
              FileStatus files[]=hdfs.listStatus(dst);
              for(FileStatus file:files){ 
                 System.out.println(file.getPath());
              }
        }
 } 

Create files on the HDFS

FileSystem.mkdirs (Path f) is used to create folders on HDFS. f indicates a complete folder path.

Example:

public class CreateDir { 
    public static void main(String[] args) throws Exception{
         Configuration conf=new Configuration();
         FileSystem hdfs=FileSystem.get(conf);
                Path dfs=new Path("/TestDir");
                hdfs.mkdirs(dfs);
      }
  } 

Query the modification time of an HDFS file

FileSystem.getModificationTime() is used to query the modification time of a specified HDFS file.

Example:

     public static void main(String[] args) throws Exception {
          Configuration conf=new Configuration();
          FileSystem hdfs=FileSystem.get(conf);
          Path fpath =new Path("/user/hadoop/test/file1.txt");
          FileStatus fileStatus=hdfs.getFileStatus(fpath);
          long modiTime=fileStatus.getModificationTime();
          System.out.println("file1.txt modification time is"+modiTime); 
    }

Read all files in an HDFS directory

FileStatus.getPath() is used to query all files in an HDFS directory.

Example:

public static void main(String[] args) throws Exception {
         Configuration conf=new Configuration();
         FileSystem hdfs=FileSystem.get(conf);
         Path listf =new Path("/user/hadoop/test");

         FileStatus stats[]=hdfs.listStatus(listf);
         for(int i = 0; i < stats.length; ++i) {
            System.out.println(stats[i].getPath().toString());
         }         
         hdfs.close();     
  } 

Query the location of a specified file in an HDFS cluster

FileSystem.getFileBlockLocation (FileStatus file, long start, long len) is used to query the location of a specified file in an HDFS cluster. file indicates a complete file path, and start and len specify the file path.

Example:

public static void main(String[] args) throws Exception {
         Configuration conf=new Configuration();
         FileSystem hdfs=FileSystem.get(conf);
         Path fpath=new Path("/user/hadoop/cygwin");

         FileStatus filestatus = hdfs.getFileStatus(fpath);
         BlockLocation[] blkLocations = hdfs.getFileBlockLocations(filestatus, 0, filestatus.getLen());

         int blockLen = blkLocations.length;
         for(int i=0;i < blockLen;i++){
             String[] hosts = blkLocations[i].getHosts();
             System.out.println("block_"+i+"_location:"+hosts[0]); 
         }
    } 

Obtain all node names in an HDFS cluster

DatanodeInfo.getHostName() is used to obtain all node names in an HDFS cluster.

Example:

public static void main(String[] args) throws Exception {         
        Configuration conf=new Configuration();         
        FileSystem fs=FileSystem.get(conf);
        
        DistributedFileSystem hdfs = (DistributedFileSystem)fs;

        DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats(); 
                
        for(int i=0;i < dataNodeStats.length;i++){            
            System.out.println("DataNode_"+i+"_Name:"+dataNodeStats[i].getHostName());         
        }     
   } 

Multithread security login mode

If multiple threads are performing login operations, the relogin mode must be used for the subsequent logins of all threads after the first successful login of an application.

login example code:

  private Boolean login(Configuration conf){     
    boolean flag = false;     
    UserGroupInformation.setConfiguration(conf);          
    try {       
          UserGroupInformation.loginUserFromKeytab(conf.get(PRINCIPAL), conf.get(KEYTAB));       
          System.out.println("UserGroupInformation.isLoginKeytabBased(): " +UserGroupInformation.isLoginKeytabBased());       
          flag = true;     
        } catch (IOException e) {       
           e.printStackTrace();     
        }     
     return flag;        
  }

relogin example code:

public Boolean relogin(){         
        boolean flag = false;         
        try {                        
              UserGroupInformation.getLoginUser().reloginFromKeytab();    
              System.out.println("UserGroupInformation.isLoginKeytabBased(): " +UserGroupInformation.isLoginKeytabBased());           
              flag = true;         
            } catch (IOException e) {             
                e.printStackTrace();         
            }         
        return flag;     
   }
NOTICE:

Repetitive logins will cause a newly created session to overwrite the previous session. As a result, the previous session cannot be maintained or monitored, and some functions are unavailable after the previous session expires.

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback