Hbase API高级特性-计数器

本文介绍HBase计数器的使用方法,包括单计数器和多计数器的操作方式,展示了如何通过HBase实现在线应用的实时统计功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()));
}*/
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值