在默认情况情况,我们使用hbase的java api去访问hbase的服务时,使用的hbase的服务的用户名为启动java程序的系统用户名。
在有些情况下,我们要指定用户。如何指定呢,就是本文的内容。
//指定用户名为hbase的用户去访问hbase服务
UserGroupInformation userGroupInformation = UserGroupInformation.createRemoteUser("hbase");
connection = ConnectionFactory.createConnection(configuration, User.create(userGroupInformation));
全文代码:
HBaseTest.java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.security.UserGroupInformation;
public class HBaseTest {
private org.apache.hadoop.hbase.client.Connection connection = null;
public void init() throws Exception {
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "192.168.13.133,192.168.13.134,192.168.13.135");//zookeeper的ip
configuration.set("hbase.zookeeper.property.clientPort", "2181");// zookeeper端口
configuration.set("zookeeper.znode.parent", "/hbase-unsecure");
configuration.set("hbase.rpc.timeout", "2000");
configuration.set("hbase.client.scanner.timeout.period", "3000");
// configuration.set("hadoop.home.dir","F:\\hadoop");
//默认使用的是启动该java程序的系统用户名去连接hbase,
// connection = ConnectionFactory.createConnection(configuration);
//指定用户名为hbase的用户去访问hbase服务
UserGroupInformation userGroupInformation = UserGroupInformation.createRemoteUser("hbase");
connection = ConnectionFactory.createConnection(configuration, User.create(userGroupInformation));
}
public void doScan() {
try {
Table table = connection.getTable(TableName.valueOf("student"));
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes("001"));
scan.setStopRow(Bytes.toBytes("002"));//不包含这条
ResultScanner rs = table.getScanner(scan);
int num = 0;
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
num++;
}
System.out.print(num);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HBaseTest hBaseTest = new HBaseTest();
try {
hBaseTest.init();
hBaseTest.doScan();
} catch (Exception e) {
e.printStackTrace();
}
}
}