相关环境:
虚拟机:Centos7
hadoop版本:3.1.3 hbase版本:2.4.11 zookeeper版本:3.5.7
Java IDE:IDEA JDK:8
步骤
步骤一:在idea创建一个maven项目
步骤二:在虚拟机里找到core-site.xml和hbase-site.xml这两个文件
我的core-site.xml文件是在hadoop安装目录下的etc/hadoop中
hbase-site.xml文件在hbase安装目录下的conf中
找到后下载下来,然后放到idea的src/main/resources中
步骤三:导入相关依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-server -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.4.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>2.4.17</version>
</dependency>
</dependencies>
步骤四:写一个测试类测试一下
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;
import java.io.IOException;
public class connect_test
{
public static Connection connection = null;
public static Admin admin = null;
static
{
try
{
//1、获取配置信息
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.rootdir", "hdfs://hadoop102:8020/hbase");
configuration.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
//2、创建连接对象
connection = ConnectionFactory.createConnection(configuration);
//3、创建Admin对象
admin = connection.getAdmin();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//判断表是否存在
public static boolean isTableExist(String tableName) throws IOException
{
boolean exists = admin.tableExists(TableName.valueOf(tableName));
return exists;
}
public static void close()
{
if (admin != null)
{
try
{
admin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (connection != null)
{
try
{
connection.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException
{
//测试hbase是否存在名为test的表
System.out.println(isTableExist("test"));
//关闭资源
close();
}
}
比较关键的是下面这两个配置信息
configuration.set("hbase.rootdir", "hdfs://hadoop102:8020/hbase");
configuration.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
这两个信息可以在hbase-site.xml中可以找到
然后运行测试,结果为true,说明hbase中存在表为test的表。测试成功,成功连接hbase