1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.filter.PageFilter; import java.io.IOException;
public class HBaseClient { private static Connection connection; static { try { connection = ConnectionFactory.createConnection(); } catch (IOException e) { throw new RuntimeException("HBase 连接失败", e); } } public static Table getTable(String tableName) throws IOException { return connection.getTable(TableName.valueOf(tableName)); } public static void putData(String tableName, String rowKey, String family, String qualifier, String value) throws IOException { try (Table table = getTable(tableName)) { Put put = new Put(Bytes.toBytes(rowKey)); put.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value)); table.put(put); } } public static String getData(String tableName, String rowKey, String family, String qualifier) throws IOException { try (Table table = getTable(tableName)) { Get get = new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier)); Result result = table.get(get); byte[] value = result.getValue(Bytes.toBytes(family), Bytes.toBytes(qualifier)); return value == null ? null : Bytes.toString(value); } } public static void deleteData(String tableName, String rowKey, String family, String qualifier) throws IOException { try (Table table = getTable(tableName)) { Delete delete = new Delete(Bytes.toBytes(rowKey)); delete.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier)); table.delete(delete); } } public static long increment(String tableName, String rowKey, String family, String qualifier, long delta) throws IOException { try (Table table = getTable(tableName)) { return table.incrementColumnValue( Bytes.toBytes(rowKey), Bytes.toBytes(family), Bytes.toBytes(qualifier), delta ); } } public static void close() { try { if (connection != null) connection.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { String tableName = "test"; putData(tableName, "user_001", "info", "name", "张三"); String name = getData(tableName, "user_001", "info", "name"); System.out.println("姓名: " + name); long count = increment(tableName, "ad_001", "stats", "impression", 1); System.out.println("计数: " + count); close(); } }
|