【使用Java编写Hbase1.4.6的接口】

在pom文件中加载依赖

		<dependency><!-- HBase 客户端依赖包 -->
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.4.6</version>
        </dependency>
        <dependency><!-- HBase 公共依赖包 -->
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-common</artifactId>
            <version>1.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>1.4.6</version>
        </dependency>

Hbase工具类

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class HbaseUtils {
    private static Connection conn;
    private static Configuration configuration;
    private static Admin admin;
    public static void main(String[] args) throws Exception {
    }

    @Before
    public void setup() throws Exception {
        configuration = new Configuration();
        configuration.set("hbase.zookeeper.quorum", "master:2181");
        conn = ConnectionFactory.createConnection(configuration);
        admin = conn.getAdmin();
    }

    /**
     * 结束之后 关闭对象
     */
    @After
    public void End_up() throws Exception {
        if (conn != null) conn.close();
    }

    @Test
    public void create() throws IOException {
        String[] cols = {"phone", "addr", "age"};
        createTable("helloworld", cols);

    }

    /**
     * @param tableName
     * @param columns
     * @throws IOException
     */

    void createTable(String tableName, String[] columns) throws IOException {
        TableName tb = TableName.valueOf(tableName);
        if (admin.tableExists(tb)) {
            System.out.println("已经存在");
        } else {
            System.out.println("不存在");
            HTableDescriptor desc = new HTableDescriptor(tb);
            for (String column : columns) {
                desc.addFamily(new HColumnDescriptor(column));
            }
            admin.createTable(desc);
            System.out.println("create " + tableName + " success");
        }
    }

    @Test
    public void delete() throws IOException {
        deleteTable("tab1");
    }

    /**
     * @param tableName
     * @throws IOException
     */
    void deleteTable(String tableName) throws IOException {
        TableName tb = TableName.valueOf(tableName);
        if (admin.tableExists(tb)) {
            System.out.println("已经存在");
            admin.disableTable(tb);
            admin.deleteTable(tb);
        }
        System.out.println("delete " + tableName + " success");
    }

    @Test
    public void showTable() throws IOException {
        TableName[] tables = admin.listTableNames();
        for (TableName tab : tables) {
            System.out.println("表名:" + tab.getNameAsString());
            HTableDescriptor desc = admin.getTableDescriptor(tab);
            for (HColumnDescriptor column : desc.getColumnFamilies()) {
                System.out.println(column.getNameAsString() + "===" + column.toString());
            }
        }
    }

    @Test
    public void getByRowKey(String tablename, String row) throws IOException {
        //admin.getTableDescriptor(TableName.valueOf("test"));
        Table table = conn.getTable(TableName.valueOf(tablename));
        Get get = new Get(row.getBytes());
        Result rt = table.get(get);
        System.out.println(rt.toString());
        for (Cell cell : rt.rawCells()) {
            System.out.println(
                    Bytes.toString(CellUtil.cloneRow(cell)) + "\t" +
                            Bytes.toString(CellUtil.cloneFamily(cell)) + "\t" +
                            Bytes.toString(CellUtil.cloneQualifier(cell)) + "\t" +
                            Bytes.toString(CellUtil.cloneValue(cell))
            );
        }
    }

    @Test
    public void put(String tablename, String row, String cloums, String[] cloum, String[] value) throws IOException {
        Table tab = conn.getTable(TableName.valueOf(tablename));
        Put put1 = new Put(row.getBytes());
        put1.addColumn(cloums.getBytes(), cloum[0].getBytes(), Bytes.toBytes(value[0]));
        put1.addColumn(cloums.getBytes(), cloum[1].getBytes(), Bytes.toBytes(value[1]));
        //put1.addColumn("info".getBytes(),"username".getBytes(),Bytes.toBytes("hellooww"));
        //Put put2 = new Put("1002".getBytes());
        //put2.addColumn("info".getBytes(),"age".getBytes(),Bytes.toBytes("45"));
        //put2.addColumn("info".getBytes(),"username".getBytes(),Bytes.toBytes("alibaba"));
        List list = new ArrayList();
        list.add(put1);
        //list.add(put2);
        tab.put(list);
        System.out.println("上传到hbase表成功");
    }

    @Test
    public void deletByRowKey(String tablename, String row) throws IOException {
        Table table = conn.getTable(TableName.valueOf(tablename));
        Delete delete = new Delete(Bytes.toBytes(row));
        //如果age列有多个版本的话,这里只删除了最新的一个版本,其他版本的数据还在的,
        // addColumn是删除某一个列簇里的最新时间戳版本。
        // delete.addColumns是删除某个列簇里的所有时间戳版本。
        //delete.addColumn("info".getBytes(),"age".getBytes());
        //测试下删除不存在的列
        // delete.addColumn("info".getBytes(),"hh".getBytes());
        //测试下删除不存在的列簇 会报错 column family info22 does not exist in region test
        //elete.addColumn("info22".getBytes(),"hh".getBytes());
        table.delete(delete);
        System.out.println("删除" + tablename + "的" + row + "成功!");
        table.close();
    }

    @Test
    public void scanTable(String tablename) throws IOException {
        Table table = conn.getTable(TableName.valueOf(tablename));
        Scan scan = new Scan();
        //scan可以加很多条件和范围
        //scan.withStartRow("0002".getBytes());
        //scan.withStopRow("0004".getBytes());//不包含末尾行
        //scan.withStopRow("0004".getBytes(),true);//包含末尾行
        ResultScanner rtScan = table.getScanner(scan);
        // Iterator itor = rtScan.iterator();
        // while(itor.hasNext()){
        // System.out.println( itor.next().toString());
        // }
        for (Result next = rtScan.next(); next != null; next = rtScan.next()) {
            System.out.println(next.toString());
        }
    }
}

Hbase测试类

public class HbaseDemo {
    public static void main(String[] args) throws Exception {
        HbaseUtils demo = new HbaseUtils();
        //加载连接hbase的参数
        demo.setup();

        System.out.println("\n\n\n=======================================delete table==================");
        String[] cols = {"info"};
        demo.deleteTable("tab1");

        System.out.println("\n\n\n=======================================create table==================");
        demo.createTable("tab1",cols);

        System.out.println("\n\n\n=======================================show tables==================");
        demo.showTable();

        System.out.println("\n\n\n=======================================put==================");
        String cloums = "info";
        String[] cloum = {"age","name"};
        String[] values = {"24","lyt"};
        demo.put("tab1","1001",cloums,cloum,values);
        demo.put("tab1","1002",cloums,cloum,values);

        System.out.println("\n\n\n=======================================getByRowKey==================");
        demo.getByRowKey("tab1","1001");

        System.out.println("\n\n\n=======================================deletByRowKey==================");
        demo.deletByRowKey("tab1","1001");


        System.out.println("\n\n\n=======================================scan tables===============================");
        demo.scanTable("tab1");

        //关闭hbase
        demo.End_up();
    }
}

文章参考链接

链接: java操作hbase1.4_JAVA API操作hbase1.4.2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值