10.3 WeiUtil 类
package com.atguigu.weibo;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.Map;
public class WeiboUtil {
public static Configuration conf;
static {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "hadoop201:2181,hadoop202:2181,hadoop203:2181");
}
public static void createNameSpace(String nameSpace) throws IOException {
if (nameSpaceExists(nameSpace)) return;
Admin admin = getAdmin();
NamespaceDescriptor descriptor = NamespaceDescriptor.create(nameSpace).build();
admin.createNamespace(descriptor);
admin.close();
}
public static void createTable(String tableName, int versions, String... cfs) throws IOException {
if (tableExists(tableName)) return;
Admin admin = getAdmin();
HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
for (String cf : cfs) {
HColumnDescriptor cDescriptor = new HColumnDescriptor(Bytes.toBytes(cf));
cDescriptor.setMaxVersions(versions);
descriptor.addFamily(cDescriptor);
}
admin.createTable(descriptor);
admin.close();
}
public static Admin getAdmin() throws IOException {
Connection conn = ConnectionFactory.createConnection(conf);
Admin admin = conn.getAdmin();
return admin;
}
public static boolean tableExists(String tableName) throws IOException {
Admin admin = getAdmin();
boolean exists = admin.tableExists(TableName.valueOf(tableName));
admin.close();
return exists;
}
public static boolean nameSpaceExists(String nameSpace) {
Admin admin = null;
try {
admin = getAdmin();
NamespaceDescriptor descriptor = admin.getNamespaceDescriptor(nameSpace);
Map<String, String> conf = descriptor.getConfiguration();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}