1、解壓hbase安裝包
2、將大數據環境得hadoop安裝包拷貝到windows(這里以d:/hadoop為例)
3、打開C:\Windows\System32\drivers\etc目錄下的hosts並添加如下代碼
127.0.0.1 localhost
192.168.48.134 master
192.168.48.133 slaver
注:這里你配置了幾台服務器就寫幾台,這里我只配置192.168.48.134 master和192.168.48.133 slaver兩台
4、使用Eclipse創建一個java工程,引進第一步驟中解壓Hbase文件夾下的lib里面的全部jar
5、最好也在src下面創建一個文件夾,並把集群環境中hbase的hbase-site.xml放入文件文件夾中,並添加到class path中(其實新版本的都可省略這步了,因為我的hadoop是2.7.3,hbase用的是1.2.4算是比較高度版本了)
6、在步驟二的文件夾的bin文件夾下是否有winutils.exe文件,如果沒有的話,就下載一個放在該目錄
7、示例代碼:
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; 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; import org.apache.hadoop.hbase.io.compress.Compression.Algorithm; public class TestHbase { private static final String TABLE_NAME = "test"; private static final String CF_DEFAULT = "info"; public static void createOrOverwrite(Admin admin, HTableDescriptor table) throws IOException { if (admin.tableExists(table.getTableName())) { admin.disableTable(table.getTableName()); admin.deleteTable(table.getTableName()); } admin.createTable(table); } public static void createSchemaTables(Configuration config) throws IOException { try (Connection connection = ConnectionFactory.createConnection(config); Admin admin = connection.getAdmin()) { HTableDescriptor table = new HTableDescriptor(TableName.valueOf(TABLE_NAME)); table.addFamily(new HColumnDescriptor(CF_DEFAULT).setCompressionType(Algorithm.NONE)); System.out.print("Creating table. "); createOrOverwrite(admin, table); System.out.println(" Done."); } } public static void main(String[] args) throws IOException { Configuration config = HBaseConfiguration.create(); /* * 默認會從項目編譯后的calss文件的根目錄尋找文件,可以不指定 * 添加資源文件有以下幾種方式: * */ /** * config.addResource(input); */ //InputStream input = HBaseOper.class.getResourceAsStream("/core-site.xml"); //config.addResource(input); /** * 官網給出的例子程序使用的是這種方法 * config.addResource(Path); * Path可以為絕對路徑,例如:D:\\Program Files\\hbase\\conf\\hbase-site.xml */
//這里就是步驟二從集群環境拷過來的hadoop放在window上的路徑,注意都是用的絕對路徑 System.setProperty("hadoop.home.dir", "D:\\Users\\zml\\Eclipse\\hadoop-2.7.3"); //Add any necessary configuration files (hbase-site.xml, core-site.xml)
//這些文件都是從集群環境上拷過來的
config.addResource(new Path("D:\\Users\\zml\\Eclipse\\workspace\\HbaseDemo\\hbase_conf\\hbase-site.xml")); config.addResource(new Path("D:\\Users\\zml\\Eclipse\\workspace\\HbaseDemo\\hbase_conf\\core-site.xml")); createSchemaTables(config); //modifySchema(config); } }