HBase Java API 프로 그래 밍: 원본 상세 설명
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
public class HBaseJavaAPIDemo
{
public static void main(String args[]) throws IOException
{
// Configuration configuration = new Configuration();//
Configuration configuration = HBaseConfiguration.create();//HBaseConfiguration Configuration , HBaseConfiguration create , HBase
//configuration.addResource(file);
System.out.println(configuration.toString());// , hbase-default.xml , HBase , hbase-1.2.0-cdh5.7.0/hbase-common/src/main/resources/hbase-default.xml
configuration.set("hbase.zookeeper.quorum", "hadoop");//// HBase , win7 hosts hadoop IP
// configuration.set("hbase.zookeeper.property.clientPort", "2181");
// configuration.set("hbase.rootdir", "hdfs://hadoop:8020/hbase");
System.out.println(configuration.get("hbase.zookeeper.quorum"));//
System.out.println(configuration.get("hbase.rootdir"));
// Connection connection = new Connection();//Connection ,
Connection connection = ConnectionFactory.createConnection(configuration);// , ; Connection interface,createConnection , connection
System.out.println(connection.getClass().getName());
TableName tableName = TableName.valueOf("students1");// TableName valueOf , TableName ,tableName
// Admin admin = new Admin();//Admin ,
Admin admin = connection.getAdmin();// connection getAdmin , Admin HBaseAdmin ,
boolean isTableExists = admin.tableExists(tableName);
System.out.println(isTableExists);
}
}
예제 소스 코드 2:
자바 문법 점: "인터페이스 인용 은 실제 클래스 의 대상 을 가리 킬 수 있 습 니 다"
interface Running // Running
{
void run();//
}
class Dog implements Running // Dog, Running
{
public void run() // Running run()
{
System.out.println("dog is running");
}
}
class Horse implements Running // Horse, Running
{
public void run() // Running run()
{
System.out.println("horse is running");
}
}
public class testInterface
{
public static void main(String args[])
{
Running running;// Running
// Dog dog = new Dog();// Dog dog
// running = dog; // Running , Dog dog
running = new Dog();
running.run();// Running , dog run()
// Horse horse = new Horse();// Horse horse
// running = horse; // Running , Horse horse
running = new Horse();
running.run();// Running , dog run()
}
}
// ? Java
// : , 。
// Running , Dog Horse , Horse, Dog ?
// :Running running = new Horse(); running 。
// Horse horse = new Horse(), ;, Running running = new Horse(); ,
// .
코드 재 구성 을 진행 하여 코드 재 활용 성과 가 독성 을 향상 시 킵 니 다.
STEP 1: main 방법 중의 업무 코드 를 하나의 방법 으로 추출
두 번 째 단계: Configuration 과 관련 된 코드 를 자바 정적 코드 블록 에 배치 합 니 다 (주 클래스 로 딩 후 한 번 만 실 행 됩 니 다)
STEP 3: Connection 과 관련 된 코드 를 자바 정적 코드 블록 에 배치 합 니 다 (주 클래스 로 딩 후 한 번 만 실 행 됩 니 다)
4 단계: Admin 관련 코드 를 자바 정적 코드 블록 에 배치 합 니 다 (주 클래스 로 딩 후 한 번 만 실 행 됩 니 다)
STEP 5: Configuration, Connection, Admin 과 관련 된 코드 를 모두 정적 초기 화 방법 init () 에 넣 습 니 다.
STEP 6: 데이터베이스 작업 이 끝 난 후 데이터베이스 연결 을 닫 는 모든 작업 을 정적 닫 는 방법 close () 에 통일 합 니 다.
예제 소스 코드 3:
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
public class HBaseJavaAPIDemo
{
public static Configuration configuration;
public static Connection connection;
public static Admin admin;
// static //Java ,
// {
// configuration = HBaseConfiguration.create();
// configuration.set("hbase.zookeeper.quorum", "hadoop");
// try
// {
// connection = ConnectionFactory.createConnection(configuration);
// admin = connection.getAdmin();
// }
// catch(IOException e)
// {
// e.printStackTrace();
// }
// }
public static void init() // , configuration, Connection, Admin init()
{
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "hadoop");
try
{
connection = ConnectionFactory.createConnection(configuration);
admin = connection.getAdmin();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void close() // , close()
{
try
{
admin.close();
connection.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static boolean isTableExist(String strTableName) throws IOException
{
// Connection connection = ConnectionFactory.createConnection(configuration);
TableName tableName = TableName.valueOf(strTableName);
// Admin admin = connection.getAdmin();
boolean isTableExists = admin.tableExists(tableName);
System.out.println(isTableExists);
return isTableExists;
}
public static void main(String args[]) throws IOException
{
init();
boolean isExists = isTableExist("students");
if(isExists)
{
System.out.println("Table exists");
}
else
{
System.out.println("Table dose not exists");
}
close();
}
}
STEP 7: 데이터 베 이 스 를 초기 화하 고 각종 데이터 베 이 스 를 조작 하 는 방법, 연결 을 닫 는 방법 을 하나의 통 일 된 HBase Java API 도구 류 에 밀봉 하여 코드 의 재 활용 성 을 향상 시 키 고 코드 결합 성 을 낮 추 며 코드 의 유지 가능성 을 높 인 다.
예시 원본 4:
class HBaseJavaAPIUtils // , , HBase , , ,
{
public static Configuration configuration;
public static Connection connection;
public static Admin admin;
public static void init() // , configuration, Connection, Admin init()
{
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "hadoop");
try
{
connection = ConnectionFactory.createConnection(configuration);
admin = connection.getAdmin();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void close() // , close()
{
try
{
admin.close();
connection.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static boolean isTableExist(String strTableName) throws IOException
{
TableName tableName = TableName.valueOf(strTableName);
boolean isTableExists = admin.tableExists(tableName);
System.out.println(isTableExists);
return isTableExists;
}
}
8 단계: 데이터베이스 접근 작업 과 관련 된 모든 코드 를 HBase 도구 류 인 HBaseJavaAPIUtils 로 봉 하고 자바 소스 파일 에 따로 넣 어 유지 합 니 다.한편, HBaseJavaAPIDemo 류 는 도구 류 가 제공 하 는 데이터 베 이 스 를 호출 하 는 방법 만 담당 하고 HBase Java API 를 구체 적 으로 어떻게 호출 하 는 지 에 관심 을 가지 지 않 고 상부 업무 논리 개발 에 초점 을 맞 출 필요 가 없다.소프트웨어 공학 의 코드 결합, 코드 재 활용 등 사상 을 나타 내 고 코드 의 유지 가능성 을 한층 향상 시 켜 bug 가 쉽게 발생 하지 않 습 니 다.
HBase 도구 류 파일 HBaseJavaAPIUtils. java 의 원본 코드 는 다음 과 같 습 니 다. 작성 한 모든 HBase Java API 의 DDL 동작 방법 을 여기에 놓 습 니 다.
예시 원본 5:
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
public class HBaseJavaAPIUtils //HBase
{
public static Configuration configuration;
public static Connection connection;
public static Admin admin;
/**
* , configuration, Connection, Admin init()
* @parameter
* @return void
*/
public static void init() throws IOException
{
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "hadoop");
connection = ConnectionFactory.createConnection(configuration); // Connection HConnectionImplementation
admin = connection.getAdmin();// Admin HBaseAdmin
}
/**
* , close()
* @parameter
* @return
*/
public static void close() throws IOException
{
connection.close();
admin.close();
}
/**
* ,
* , TableName( default ) NameSpace:TableName , true, fase
* @parameter String strTableName
* @return boolean
*/
public static boolean isTableNameFormatCorrect(String strTableName)
{
System.out.println(strTableName.indexOf(":"));
System.out.println(strTableName.lastIndexOf(":"));
System.out.println(strTableName.length());
// ,
// 1 || ||
if(strTableName.indexOf(":") != strTableName.lastIndexOf(":") ||
strTableName.indexOf(":")==0 ||
strTableName.indexOf(":")==strTableName.length()-1)// 1 || ||
{
System.out.println("Input parameter format incorrect");
return false;
}
return true;
}
/**
* , TableName( default ) NameSpace:TableName , true, fase
* @parameter String strTableName
* @return boolean
*/
public static boolean isTableExist(String strTableName) throws IOException//
{
if(!isTableNameFormatCorrect(strTableName))//
{
return false;
}
TableName tableName = TableName.valueOf(strTableName);
boolean isTableExists = admin.tableExists(tableName); // meta
// System.out.println(isTableExists);
return isTableExists;
}
/**
* default , 1
* @parameter void
* @return void
*/
public static void listTables() throws IOException//
{
// TableDesciptors
// HTableDescriptor[] tableDescriptors = admin.listTables();
// for(HTableDescriptor tableDescriptor : tableDescriptors)
// {
// System.out.println(tableDescriptor.getTableName());//
// }
// TableName
TableName[] tableNames = admin.listTableNames();
for(TableName tableName : tableNames)
{
System.out.println(new String(tableName.getName()));// byte[] String
}
}
/**
* default , 2
* @parameter HTableDescriptor[] tableDescriptors
* @return void
*/
public static void listTables(HTableDescriptor[] tableDescriptors) throws IOException//
{
for(HTableDescriptor tableDescriptor : tableDescriptors)
{
System.out.println(tableDescriptor.getTableName());//
}
}
/**
* default , 3
* @parameter TableName[] tableNames
* @return void
*/
public static void listTables(TableName[] tableNames) throws IOException//
{
for(TableName tableName : tableNames)
{
// System.out.println(new String(tableName.getName()));
System.out.println(tableName.getNameAsString());
}
}
/**
* , 4
* @parameter String strNameSpace
* @return void
*/
// public static void listTables(String strNameSpace) throws IOException//
// {
// TableName[] tableNames = admin.listTableNamesByNamespace(strNameSpace);
// for(TableName tableName : tableNames)
// {
// System.out.println(new String(tableName.getName()));
// }
// }
public static void listTables(String strNameSpace) throws IOException//
{
// 、 ,
if(!isNameSpacesExists(strNameSpace))//
{
System.out.println("NameSpace does not exists");
return;
}
TableName[] tableNames = admin.listTableNamesByNamespace(strNameSpace);
listTables(tableNames);// ,
// HTableDescriptor[] tableDescriptors = admin.listTableDescriptorsByNamespace(strNameSpace);
// listTables(tableDescriptors);// ,
}
/**
* default , 5
* @parameter Admin admin Admin ,
* @return void
*/
public static void listTables(Admin admin) throws IOException//
{
// TableDesciptors
// HTableDescriptor[] tableDescriptors = admin.listTables();
// for(HTableDescriptor tableDescriptor : tableDescriptors)
// {
// System.out.println(tableDescriptor.getTableName());//
// }
// TableName
TableName[] tableNames = admin.listTableNames();
for(TableName tableName : tableNames)
{
System.out.println(new String(tableName.getName()));// byte[] String
}
}
/**
* , 6
* @parameter String strNameSpace ; Admin admin Admin ,
* @return void
*/
public static void listTables(String strNameSpace, Admin admin) throws IOException//
{
//
if(!isNameSpacesExists(strNameSpace)) //
{
return;
}
TableName[] tableNames = admin.listTableNamesByNamespace(strNameSpace);
listTables(tableNames);
}
/**
* , TableName( default ) NameSpace:TableName , true, false
* @parameter String strTableName
* @return boolean
*/
public static boolean isTableAllowCreate(String strTableName) throws IOException//
{
if(!isTableNameFormatCorrect(strTableName)) //
{
return false;
}
//
if(strTableName.indexOf(":") != -1) // , NameSpace:TableName
{
String strNameSpace = strTableName.substring(0, strTableName.indexOf(":"));// , NameSpace
System.out.println(strNameSpace);
if(!isNameSpacesExists(strNameSpace))//
{
return false;
}
}
TableName tableName = TableName.valueOf(strTableName);
if(admin.tableExists(tableName)) // , true, ,
{
System.out.println("Table already exists");
return false;
}
return true;
}
/**
* , , ( , ), 1
* @parameter String strTableName , String strColumnFamilyName
* @return void
*/
public static void createTable(String strTableName, String strColumnFamilyName) throws IOException
{
if(!isTableAllowCreate(strTableName)) //
{
return;
}
TableName tableName = TableName.valueOf(strTableName);
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
HColumnDescriptor columnDescriptor = new HColumnDescriptor(strColumnFamilyName);
tableDescriptor.addFamily(columnDescriptor);
admin.createTable(tableDescriptor);
}
/**
* , , , 2
* TableName( default ) NameSpace:TableName , NameSpace
* @parameter String strTableName , String[] strColumnFamilyNames
* @return void
*/
public static void createTable(String strTableName, String[] strColumnFamilyNames) throws IOException
{
if(!isTableAllowCreate(strTableName)) //
{
return;
}
TableName tableName = TableName.valueOf(strTableName);
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
for(String strColumnFamilyName:strColumnFamilyNames)
{
HColumnDescriptor columnDescriptor = new HColumnDescriptor(strColumnFamilyName);
tableDescriptor.addFamily(columnDescriptor);
}
admin.createTable(tableDescriptor);
}
/**
* , TableName( default ) NameSpace:TableName , true, false
* @parameter String strTableName
* @return boolean
*/
public static boolean isTableAllowDrop(String strTableName) throws IOException//
{
if(!isTableExist(strTableName)) // false
{
System.out.println("Table dose not exists");
return false;
}
TableName tableName = TableName.valueOf(strTableName);
if(admin.isTableEnabled(tableName)) // , enabled, true
{
admin.disableTable(tableName);// , off-line
}
return true;
}
/**
* ,
* TableName( default ) NameSpace:TableName , drop 't1' drop 'ns1:t1'
* @parameter String strTableName
* @return void
*/
public static void dropTable(String strTableName) throws IOException
{
if(!isTableAllowDrop(strTableName)) // false,
{
System.out.println("Table dose not allow to be dropped");
return;
}
TableName tableName = TableName.valueOf(strTableName);
admin.deleteTable(tableName);
System.out.println("Table deleted successfully");
}
/**
* HBase
* @parameter void
* @return void
*/
public static void listNameSpaces() throws IOException//
{
NamespaceDescriptor[] namespaceDescriptors = admin.listNamespaceDescriptors();
for(NamespaceDescriptor namespaceDescriptor: namespaceDescriptors)
{
System.out.println(namespaceDescriptor.getName());//
}
}
/**
* HBase ,
* @parameter String strNameSpace
* @return boolean true
*/
public static boolean isNameSpacesExists(String strNameSpace) throws IOException//
{
NamespaceDescriptor[] namespaceDescriptors = admin.listNamespaceDescriptors();
for(NamespaceDescriptor namespaceDescriptor: namespaceDescriptors)
{
if(namespaceDescriptor.getName().equals(strNameSpace))//
{
return true;
}
}
return false;
}
/**
* ,
* @parameter String strNameSpace
* @return boolean true false
*/
public static boolean isNameSpacesHasTable(String strNameSpace) throws IOException//
{
TableName[] tableNames = admin.listTableNamesByNamespace(strNameSpace);
if(tableNames.length <1)
{
System.out.println("The namespace has no tables");
return false;
}
return true;
}
/**
* ,
* @parameter String strNameSpace
* @return void
*/
public static void createNameSpace(String strNameSpace) throws IOException//
{
if(isNameSpacesExists(strNameSpace))//
{
System.out.println("NameSpace already exists");
return;
}
// NamespaceDescriptor namespaceDescriptor = new NamespaceDescriptor();// ,
NamespaceDescriptor namespaceDescriptor = NamespaceDescriptor.create(strNameSpace).build();
admin.createNamespace(namespaceDescriptor);
}
/**
* ,
* @parameter String strNameSpace
* @return void
*/
public static void dropNameSpace(String strNameSpace) throws IOException//
{
if(!isNameSpacesExists(strNameSpace))//
{
return;
}
if(isNameSpacesHasTable(strNameSpace))
{
System.out.println("Only empty namespaces can be removed. The namespace has one or more tables");
return;
}
admin.deleteNamespace(strNameSpace);
}
/**
* ,
* @parameter String strTableName , String newColumnFamily
* @return void
*/
public static void alterTable(String strTableName, String newColumnFamily) throws IOException
{
if(!isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName);//
HTableDescriptor tableDescriptor = admin.getTableDescriptor(tableName);//
if(isColumnFamilyExists(tableDescriptor, newColumnFamily)) // ,
{
return;
}
HColumnDescriptor columnDescriptor = new HColumnDescriptor(newColumnFamily);//
tableDescriptor.addFamily(columnDescriptor);//
admin.modifyTable(tableName, tableDescriptor); //
}
/**
* , , ,
* @parameter String strTableName , String delColumnFamily , String method
* @return void
*/
public static void alterTable(String strTableName, String delColumnFamily, String method) throws IOException
{
if(!isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
HTableDescriptor tableDescriptor = admin.getTableDescriptor(tableName); //
if(isTableHasOnlyOneFamily(tableDescriptor)) // ,
{
return;
}
tableDescriptor.removeFamily(Bytes.toBytes(delColumnFamily));//
admin.modifyTable(tableName, tableDescriptor); //
}
/**
* , , , ,
* @parameter String strTableName , String delColumnFamily ,int maxVersion ,,int minVersion
* @return void
*/
public static void alterTable(String strTableName, String columnFamily, int maxVersion, int minVersion) throws IOException
{
if(!isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
if(maxVersion < 1 ||minVersion < 0 || maxVersion < minVersion) // : 1, 0,
{
System.out.println("max versions or min versions is illegal" );
return;
}
TableName tableName = TableName.valueOf(strTableName);//
HTableDescriptor tableDescriptor = admin.getTableDescriptor(tableName);//
if(!isColumnFamilyExists(tableDescriptor, columnFamily)) // ,
{
System.out.println("column family dose not exists");
return;
}
// HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamily);// ,
HColumnDescriptor columnDescriptor = tableDescriptor.getFamily(Bytes.toBytes(columnFamily));// ,
System.out.println("Max Versions: " + columnDescriptor.getMaxVersions());// ,
System.out.println("Min Versions: " + columnDescriptor.getMinVersions());// ,
// if(maxVersion < columnDescriptor.getMinVersions()) //
// {
// System.out.println("Maximum versions to be set must be equal or more than current minimum versions" );
// return;
// }
columnDescriptor.setMinVersions(minVersion);// ,
columnDescriptor.setMaxVersions(maxVersion);//
tableDescriptor.modifyFamily(columnDescriptor);//
admin.modifyTable(tableName, tableDescriptor);//
System.out.println("Max Versions: " + columnDescriptor.getMaxVersions());// ,
System.out.println("Min Versions: " + columnDescriptor.getMinVersions());// ,
}
/**
* , , ,
* @parameter String strTableName , String delColumnFamily ,Algorithm compression
* @return void
*/
public static void alterTable(String strTableName, String columnFamily, Algorithm compression) throws IOException
{
if(!isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName);//
HTableDescriptor tableDescriptor = admin.getTableDescriptor(tableName);//
if(!isColumnFamilyExists(tableDescriptor, columnFamily)) // ,
{
System.out.println("column family dose not exists");
return;
}
// HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamily);// ,
HColumnDescriptor columnDescriptor = tableDescriptor.getFamily(Bytes.toBytes(columnFamily));// ,
columnDescriptor.setCompressionType(compression);//
tableDescriptor.modifyFamily(columnDescriptor);//
admin.modifyTable(tableName, tableDescriptor);//
}
/**
* HBase ,
* @parameter HTableDescriptor tableDescriptor, String strNameSpace
* @return boolean true
*/
public static boolean isColumnFamilyExists(HTableDescriptor tableDescriptor, String strFamiliyName) throws IOException//
{
HColumnDescriptor[] hColumnDescriptors = tableDescriptor.getColumnFamilies();
for(HColumnDescriptor hColumnDescriptor: hColumnDescriptors)
{
if(hColumnDescriptor.getNameAsString().equals(strFamiliyName))
{
System.out.println("Column Family already exists");
return true;
}
}
return false;
}
/**
* ,
* @parameter HTableDescriptor tableDescriptor
* @return boolean true false
*/
public static boolean isTableHasOnlyOneFamily(HTableDescriptor tableDescriptor) throws IOException//
{
HColumnDescriptor[] hColumnDescriptors = tableDescriptor.getColumnFamilies();
if(hColumnDescriptors.length <=1)
{
System.out.println("Table has only one Column Family");
return true;
}
return false;
}
}
예제 소스 코드 6:
비 즈 니스 논 리 를 작성 하 는 데 사용 되 는 HBaseJavaAPIDemo. java 파일 원본 코드 는 다음 과 같 습 니 다.
import java.io.IOException;
import org.apache.hadoop.hbase.HConstants;
public class HBaseJavaAPIDemo//
{
public static void main(String args[]) throws IOException
{
HBaseJavaAPIUtils.init();// , , ,
//Demo1 , hbase shell exists
// TableName( default ) NameSpace:TableName , exists 't1' exists 'ns1:t1'
// System.out.println("Is Table exists? " + HBaseJavaAPIUtils.isTableExist("students"));
// System.out.println("Is Table exists? " + HBaseJavaAPIUtils.isTableExist("default:students"));
// System.out.println("Is Table exists? " + HBaseJavaAPIUtils.isTableExist("hbase:meta"));
//Demo2: HBase , ListTable , hbase shell list
//Demo2.1: default ,listTables 1
// HBaseJavaAPIUtils.listTables();
//Demo2.2: ( ) listTables 2
// HTableDescriptor[] tableDescriptors = HBaseJavaAPIUtils.admin.listTables();
// HBaseJavaAPIUtils.listTables(tableDescriptors);
//Demo2.3: ( ) listTables 3
// TableName[] tableNames = HBaseJavaAPIUtils.admin.listTableNames();
// HBaseJavaAPIUtils.listTables(tableNames);
//Demo2.4: listTables 4
// String strNameSpace = "hbase";
// HBaseJavaAPIUtils.listTables(strNameSpace);
//Demo2.5: default ,listTables 5
// HBaseJavaAPIUtils.listTables(HBaseJavaAPIUtils.admin);
//Demo2.6: default ,listTables 5
// String strNameSpace = "hbase";
// HBaseJavaAPIUtils.listTables(strNameSpace, HBaseJavaAPIUtils.admin);
//Demo3: , hbase shell create
//Demo3.1: ,
// HBaseJavaAPIUtils.createTable("teachers", "baseinfo");
// HBaseJavaAPIUtils.createTable("my_namespace:teachers", "baseinfo");
//Demo3.2: ,
// TableName( default ) NameSpace:TableName , create 't1' create 'ns1:t1'
// String[] strFamilies = new String[]{"family1", "family2", "family3"};
// HBaseJavaAPIUtils.createTable("teachers", strFamilies);
// HBaseJavaAPIUtils.createTable("my_namespace:teachers", strFamilies);
//Demo4: , hbase shell drop
// TableName( default ) NameSpace:TableName , drop 't1' drop 'ns1:t1'
// HBaseJavaAPIUtils.dropTable("table1");// drop ,
// HBaseJavaAPIUtils.dropTable("default:table1");
//Demo5: HBase
//Demo5.1: HBase
// HBaseJavaAPIUtils.listNameSpaces();
//Demo5.2: HBase
// System.out.println(HBaseJavaAPIUtils.isNameSpacesExists("hbase"));
//Demo5.3:
// HBaseJavaAPIUtils.createNameSpace("my_namespace1");
//Demo5.4:
// HBaseJavaAPIUtils.dropNameSpace("my_namespace1");
//Demo5: , hbase shell alter
//Demo5.1:
// HBaseJavaAPIUtils.alterTable("newtable_1", "newFamily_1");
//Demo5.2:
// HBaseJavaAPIUtils.alterTable("newtable_2", "newFamily_2", "");
//Demo5.3:
// HBaseJavaAPIUtils.alterTable("students", "info", 3, 0);
// HBaseJavaAPIUtils.alterTable("students", "info", HConstants.ALL_VERSIONS, 0);//
//Demo5.4:
// HBaseJavaAPIUtils.alterTable("students", "info", Algorithm.GZ);// GZ
// HBaseJavaAPIUtils.alterTable("students", "info", Algorithm.NONE);//
//Demo6: , hbase shell put
//Demo6.1: , , 、 , hbase shell put 't1', 'r1', 'c1', 'value'
// HBaseDMLUtils.putACellValue("students", "001", "info", "name", "Jack");
// HBaseDMLUtils.putACellValue("my_namespace:teachers", "001", "baseinfo", "name", "Mr.Zhang");
//Demo6.2: , , 、 、 , hbase shell put 't1', 'r1', 'c1', 'value', ts1
// HBaseDMLUtils.putACellValue("students", "001", "info", "name", "Jack", 1000000000);
// HBaseDMLUtils.putACellValue("students", "001", "info", "name", "Jack", 1000000001);
// HBaseDMLUtils.putACellValue("students", "001", "info", "name", "Jack", 1000000002);
//Demo7: , hbase shell get
//Demo7.1: 、 , hbase shell get 't1', 'r1'
// HBaseDMLUtils.getCellValue("students", "001");
// HBaseDMLUtils.getCellValue("my_namespace:teachers", "001");
//Demo7.2: 、 , , hbase shell get 't1', 'r1'
// HBaseDMLUtils.getCellValue("students", "001", "scores");
//Demo7.3: 、 、 , , hbase shell get 't1', 'r1'
// HBaseDMLUtils.getCellValue("students", "001", "scores", "Hadoop");
//Demo8: , hbase shell scan
//Demo8.1: , hbase shell scan 'ns1:t1'
// HBaseDMLUtils.scanTable("students");
// HBaseDMLUtils.scanTable("hbase:meta");
//Demo8.2: , hbase shell scan 'hbase:meta', {COLUMNS => 'info'}
// HBaseDMLUtils.scanTable("students", "info");
// HBaseDMLUtils.scanTable("hbase:meta", "info");
//Demo8.3: , hbase shell scan 'hbase:meta', {COLUMNS => 'info:regioninfo'}
// HBaseDMLUtils.scanTable("students", "info", "name");
// HBaseDMLUtils.scanTable("hbase:meta", "info", "regioninfo");
//Demo8.4: , hbase shell scan 'students', { STARTROW => '002', STOPROW =>'005'}
// HBaseDMLUtils.scanTable("students", new String[]{"002", "005"});// 002 004
// HBaseDMLUtils.scanTable("students", new String[]{"002", ""});// 002
// HBaseDMLUtils.scanTable("students", new String[]{"", "005"});// 004
// HBaseDMLUtils.scanTable("students", new String[]{"", ""});// ,
// HBaseDMLUtils.scanTable("students", new String[]{"001", "005"});// 001 004
// HBaseDMLUtils.scanTable("students", new String[]{"000", "005"});// 001 004
// HBaseDMLUtils.scanTable("students", new String[]{"00-1", "005"});// 001 004
// HBaseDMLUtils.scanTable("students", new String[]{"00a", "005"});// ,
//Demo8.5: , hbase shell scan 'students', { TIMERANGE => [1587898000000, 1587898500000]}
// HBaseDMLUtils.scanTable("students", new long[]{1587898000000l, 1587898500000l});// 1587898000000l 1587898500000l
//Demo9: , hbase shell delete
//Demo9.1: , 、 、 , hbase shell delete 'students', '001', 'info:name'
// HBaseDMLUtils.deleteCellValue("students", "001", "info", "name");
//Demo9.2: , 、 , hbase shell deleteall "students", '001'
// HBaseDMLUtils.deleteCellValue("students", "001");
//Demo9.3: , 、 , hbase shell delete
// HBaseDMLUtils.deleteCellValue("students", "001", 1591532065401l);
//Demo9.4: , 、 、 、 , hbase shell delete
// HBaseDMLUtils.deleteCellValue("students", "003", "scores", "Hadoop", 1592137954352l);
HBaseJavaAPIUtils.close();// , ,
}
}
HBase 도구 류 파일 HBaseDMLUtils. java 의 원본 코드 는 다음 과 같 습 니 다. 작성 한 모든 HBase Java API 의 DML 동작 방법 을 여기에 놓 습 니 다.
예제 소스 코드 7: 표 의 데이터 에 삽입, 조회, 삭제 등 DML 작업 을 수행 합 니 다.
import java.io.IOException;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseDMLUtils //HBase , DML
{
/**
* , , 、
* @parameter String strTableName , String rowKey ,String columnFamily ,String column ,String value
* @return void
*/
public static void putACellValue(String strTableName, String rowKey, String columnFamily, String column, String value) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName);//
if(!HBaseJavaAPIUtils.isColumnFamilyExists(HBaseJavaAPIUtils.admin.getTableDescriptor(tableName), columnFamily)) //
{
System.out.println("Column Family does not exists");
return;
}
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Put put = new Put(Bytes.toBytes(rowKey));// Put , rowKey
put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));// , 、 、
table.put(put); // put ,
}
/**
* , , 、 、
* @parameter String strTableName , String rowKey ,String columnFamily ,String column ,String value ,long timeStamp
* @return void
*/
public static void putACellValue(String strTableName, String rowKey, String columnFamily, String column, String value, long timeStamp) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName);//
if(!HBaseJavaAPIUtils.isColumnFamilyExists(HBaseJavaAPIUtils.admin.getTableDescriptor(tableName), columnFamily)) //
{
System.out.println("Column Family does not exists");
return;
}
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Put put = new Put(Bytes.toBytes(rowKey));// Put , rowKey
put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), timeStamp, Bytes.toBytes(value)); // , 、 、 、
table.put(put);// put ,
}
/**
* 、 , ,
* @parameter String strTableName , String rowKey
* @return void
*/
public static void getCellValue(String strTableName, String rowKey) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Get get = new Get(Bytes.toBytes(rowKey));// Get , rowKey
Result result = table.get(get);// get , ,
Cell[] cells = result.rawCells();//
printCellValue(cells);//
}
/**
* 、 , ,
* @parameter String strTableName , String rowKey ,String columnFamily
* @return void
*/
public static void getCellValue(String strTableName, String rowKey, String columnFamily) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName);//
if(!HBaseJavaAPIUtils.isColumnFamilyExists(HBaseJavaAPIUtils.admin.getTableDescriptor(tableName), columnFamily)) //
{
System.out.println("Column Family does not exists");
return;
}
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Get get = new Get(Bytes.toBytes(rowKey));// Get , rowKey
get.addFamily(Bytes.toBytes(columnFamily));//
Result result = table.get(get);// get , ,
Cell[] cells = result.rawCells();//
printCellValue(cells);//
}
/**
* 、 , , ,
* @parameter String strTableName , String rowKey ,String columnFamily
* @return void
*/
public static void getCellValue(String strTableName, String rowKey, String columnFamily, String column) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
if(!HBaseJavaAPIUtils.isColumnFamilyExists(HBaseJavaAPIUtils.admin.getTableDescriptor(tableName), columnFamily)) //
{
System.out.println("Column Family does not exists");
return;
}
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Get get = new Get(Bytes.toBytes(rowKey));// Get , rowKey
get.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column));//
Result result = table.get(get);// get , ,
Cell[] cells = result.rawCells();//
printCellValue(cells);//
}
/**
* ,
* @parameter Cell[] cells
* @return void
*/
public static void printCellValue(Cell[] cells) throws IOException//
{
for (Cell cell : cells)
{
System.out.println("rowkey:" + Bytes.toString(CellUtil.cloneRow(cell)) +
" | column family:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
" | column:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
" | timestamp:" + cell.getTimestamp() +
" | cell value:" + Bytes.toString(CellUtil.cloneValue(cell)));
}
}
/**
* ,
* @parameter String strTableName
* @return void
*/
public static void scanTable(String strTableName) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Scan scan = new Scan(); //
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
ResultScanner resultScanner = table.getScanner(scan);// ResultScanner
printScanResult(resultScanner);//
}
/**
* ,
* @parameter String strTableName , String columnFamily
* @return void
*/
public static void scanTable(String strTableName, String columnFamily) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Scan scan = new Scan(); //
scan.addFamily(Bytes.toBytes(columnFamily));//
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
ResultScanner resultScanner = table.getScanner(scan);// ResultScanner
printScanResult(resultScanner);//
}
/**
* , ,
* @parameter String strTableName , String columnFamily , String column
* @return void
*/
public static void scanTable(String strTableName, String columnFamily, String column) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Scan scan = new Scan(); //
scan.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column));//
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
ResultScanner resultScanner = table.getScanner(scan);// ResultScanner
printScanResult(resultScanner);//
}
/**
* ,
* @parameter String strTableName , String [] rowKeyRange ,
* @return void
*/
public static void scanTable(String strTableName, String [] rowKeyRange) throws IOException
{
if(rowKeyRange.length !=2)
{
System.out.println("Input rowkey range incorrect");
return;
}
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Scan scan = new Scan(); //
scan.setStartRow(Bytes.toBytes(rowKeyRange[0]));//
scan.setStopRow(Bytes.toBytes(rowKeyRange[1]));//
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
ResultScanner resultScanner = table.getScanner(scan);// ResultScanner
printScanResult(resultScanner);//
}
/**
* ,
* @parameter String strTableName , String [] timeRange ,
* @return void
*/
public static void scanTable(String strTableName, long [] timeRange) throws IOException
{
if(timeRange.length !=2 || timeRange[0] > timeRange[1]) //
{
System.out.println("Input time range incorrect");
return;
}
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Scan scan = new Scan(); //
scan.setTimeRange(timeRange[0], timeRange[1]);//
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
ResultScanner resultScanner = table.getScanner(scan);// ResultScanner
printScanResult(resultScanner);//
}
/**
* , ResultScanner
* @parameter ResultScanner resultScanner
* @return void
*/
public static void printScanResult(ResultScanner resultScanner) throws IOException
{
for (Result result : resultScanner)
{
// System.out.println(result);
Cell[] cells = result.rawCells();// Cell
printCellValue(cells);// Cell
}
}
/**
* , 、 、
* @parameter String strTableName , String rowKey , String columnFamily , String column
* @return void
*/
public static void deleteCellValue(String strTableName, String rowKey, String columnFamily, String column) throws IOException
{
TableName tableName = TableName.valueOf(strTableName); //
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Delete delete = new Delete(Bytes.toBytes(rowKey));// Delete , rowKey
delete.addColumns(Bytes.toBytes(columnFamily), Bytes.toBytes(column));// Delete ,
table.delete(delete);// delete ,
}
/**
* , 、
* @parameter String strTableName , String rowKey , long timeStamp
* @return void
*/
public static void deleteCellValue(String strTableName, String rowKey, long timeStamp) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
// Delete delete = new Delete(Bytes.toBytes(rowKey));// Delete , rowKey
Delete delete = new Delete(Bytes.toBytes(rowKey), timeStamp); // Delete , rowKey
// delete.setTimestamp(timeStamp);//
table.delete(delete);// delete ,
}
/**
* , 、 、 、
* @parameter String strTableName , String rowKey , String columnFamily , String column ,long timeStamp
* @return void
*/
public static void deleteCellValue(String strTableName, String rowKey, String columnFamily, String column, long timeStamp) throws IOException
{
if(!HBaseJavaAPIUtils.isTableExist(strTableName)) //
{
System.out.println("Table dose not exists");
return;
}
TableName tableName = TableName.valueOf(strTableName); //
if(!HBaseJavaAPIUtils.isColumnFamilyExists(HBaseJavaAPIUtils.admin.getTableDescriptor(tableName), columnFamily)) //
{
System.out.println("Column Family does not exists");
return;
}
Table table = HBaseJavaAPIUtils.connection.getTable(tableName);// Table
Delete delete = new Delete(Bytes.toBytes(rowKey));// Delete , rowKey
delete.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), timeStamp);// Delete , ,
table.delete(delete);// delete ,
}
}
9 단계: HBaseJavaAPIUtils. java, HBaseJavaAPIDemo. java 와 HBaseDMLUtils. java 의 원본 코드 를 계속 교체 하고 업그레이드 하 며 새로운 방법, 새로운 기능 의 실현 을 증가 하고 코드 재 구성 을 하 며 방법 을 다시 불 러 오고 합 법성 검 사 를 입력 하여 bug 복 구 를 하고 중복 되 는 공공 코드 블록 을 추출 하 는 방법.........................................................발전, 최적화, 수정, 버 전 업그레이드, 소프트웨어 개발 의 길 은 길 고 끊임없이 찾 고 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.