Hbase API高级特性-计数器

来源:互联网 发布:怎么取消淘宝运费险 编辑:程序博客网 时间:2024/06/10 11:41

1.  许多收集统计信息的应用有点击流或在线广告意见,这些应用需要收集到日志文件用作后续的分析,用户可以使用计数器做实时统计,从而放弃延时较高的批量处理操作。

2.  原子操作检查并修改:将当前列当作计数器。

即把一个 column 当作 一个 counter,这样便于给某些在线应用提供实时统计功能。(PS:比如帖子的实时浏览量:PV)

3.  如果没有计数器特性:用户需要对一行数据加锁,然后读取数据,再对当前数据做加法,最后写回Hbase并释放该行锁。这样会引起大量的资源竞争,有其是当客户端进程崩溃之后,尚未释放的锁需要等待超时恢复,这会是一个高负载的系统中引起灾难性的后果。

4.   计数器的增量可以是正数负数,正数代表加,负数代表减。

hbase(main):006:0> create'counters','daily','weekly','monthly'

0 row(s) in 2.2260 seconds

hbase(main):007:0> incr 'counters','201031003100','daily:hites',1

COUNTER VALUE = 1

hbase(main):008:0> incr'counters','201031003100','daily:hites',1

COUNTER VALUE = 2

hbase(main):009:0> get_counter  'counters','201031003100','daily:hites'

COUNTER VALUE = 2

5.  计数器就是一个与其他列类似的简单的列。

6.  单计数器:

    public void oneCounter(long num) throws IOException{
long cnt1 = table.incrementColumnValue(Bytes.toBytes("3100"), 
Bytes.toBytes("info"), Bytes.toBytes("name"), num);
}

7.  多计数器:

public void moreCounter() throws IOException{
Increment increment1 = new Increment(Bytes.toBytes("3100"));

increment1.addColumn(Bytes.toBytes("info"), Bytes.toBytes("clicks"), 20);
increment1.addColumn(Bytes.toBytes("info"), Bytes.toBytes("hits"), 1);
increment1.addColumn(Bytes.toBytes("class"), Bytes.toBytes("clicks"), 10);
increment1.addColumn(Bytes.toBytes("class"), Bytes.toBytes("hits"), 10);

Result result1 = table.increment(increment1);
for(KeyValue kv:result1.raw()){
System.out.println("KV1: "+kv +"value: "+Bytes.toLong(kv.getValue()));
}

/*Increment increment2 = new Increment(Bytes.toBytes("3102"));
increment1.addColumn(Bytes.toBytes("info"), Bytes.toBytes("clicks"), 5);
increment1.addColumn(Bytes.toBytes("info"), Bytes.toBytes("hits"), 1);
increment1.addColumn(Bytes.toBytes("class"), Bytes.toBytes("clicks"), 0);
increment1.addColumn(Bytes.toBytes("class"), Bytes.toBytes("hits"), -5);
Result result2 = table.increment(increment2);
for(KeyValue kv:result2.raw()){
System.out.println("KV2: "+kv +"value: "+Bytes.toLong(kv.getValue()));
}*/
}

 

原创粉丝点击