Hbase計數器可以用於統計用戶數,點擊量等信息
基本操作
可以使用incr操作計數器,incr語法格式如下:
incr '<table>', '<row>', '<column>', |<increment-value>|
然后使用get_counter可以獲取對應的計數器的值
不用初始化計數器,第一次使用計數器時,計數器被自動設置為0
eg:
對於wishTest1表
incr 'wishTest1','2','score:Math',1 incr 'wishTest1','2','score:Math',1 get_counter 'wishTest1','2','score:Math'
結果如下:
hbase(main):004:0> incr 'wishTest1','2','score:Math',1 COUNTER VALUE = 1 hbase(main):005:0> incr 'wishTest1','2','score:Math',1 COUNTER VALUE = 2 hbase(main):007:0> get_counter 'wishTest1','2','score:Math' COUNTER VALUE = 2 hbase(main):008:0>
增大計數的遞增值:
hbase(main):001:0> incr 'wishTest1','2','score:Math',10 COUNTER VALUE = 12 hbase(main):002:0> incr 'wishTest1','2','score:Math',10 COUNTER VALUE = 22 hbase(main):003:0> get_counter 'wishTest1','2','score:Math' COUNTER VALUE = 22
使用API操作計數器
使用table.incrementColumnValue()
eg:
String tableName = "wishTest1"; HTablePool pool = new HTablePool(cfg, 1000); try { long count1 = pool.getTable(tableName).incrementColumnValue(Bytes.toBytes("2"),Bytes.toBytes("score"),Bytes.toBytes("Math"),1); long count2 = pool.getTable(tableName).incrementColumnValue(Bytes.toBytes("2"),Bytes.toBytes("score"),Bytes.toBytes("Math"),1); long currentCount = pool.getTable(tableName).incrementColumnValue(Bytes.toBytes("2"),Bytes.toBytes("score"),Bytes.toBytes("Math"),0); System.out.println("count1: "+count1); System.out.println("count2: "+count2); System.out.println("currentCount: "+currentCount); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
輸出:
count1: 23 count2: 24 currentCount: 24

