HBase原子性保证

HBase提供基于单数据操作的原子性保证

即:对同一行的变更操作(包括针对一列/多列/多column family的操作),要么完全成功,要么完全失败,不会有其他状态
示例:
A客户端针对rowkey=10的行发起操作:dim1:a = 1  dim2:b=1
B客户端针对rowkey=10的行发起操作:dim1:a = 2  dim2:b=2
dim1、dim2为column family, a、b为column

A客户端和B客户端同时发起请求,最终rowkey=10的行各个列的值可能是dim1:a = 1  dim2:b=1,也可能是dim1:a = 2  dim2:b=2
但绝对不会是dim1:a = 1  dim2:b=2

HBase基于行锁来保证单行操作的原子性,可以看下HRegion put的代码(base: HBase 0.94.20)::
org.apache.hadoop.hbase.regionserver.HRegion:

[java] view plain copy

  1.   /** 
  2.    * @param put 
  3.    * @param lockid 
  4.    * @param writeToWAL 
  5.    * @throws IOException 
  6.    * @deprecated row locks (lockId) held outside the extent of the operation are deprecated. 
  7.    */  
  8.   public void put(Put put, Integer lockid, boolean writeToWAL)  
  9.   throws IOException {  
  10.     checkReadOnly();  
  11.   
  12.   
  13.     // Do a rough check that we have resources to accept a write.  The check is  
  14.     // 'rough' in that between the resource check and the call to obtain a  
  15.     // read lock, resources may run out.  For now, the thought is that this  
  16.     // will be extremely rare; we'll deal with it when it happens.  
  17.     checkResources();  
  18.     startRegionOperation();  
  19.     this.writeRequestsCount.increment();  
  20.     this.opMetrics.setWriteRequestCountMetrics(this.writeRequestsCount.get());  
  21.     try {  
  22.       // We obtain a per-row lock, so other clients will block while one client  
  23.       // performs an update. The read lock is released by the client calling  
  24.       // #commit or #abort or if the HRegionServer lease on the lock expires.  
  25.       // See HRegionServer#RegionListener for how the expire on HRegionServer  
  26.       // invokes a HRegion#abort.  
  27.       byte [] row = put.getRow();  
  28.       // If we did not pass an existing row lock, obtain a new one  
  29.       Integer lid = getLock(lockid, row, true);  
  30.   
  31.   
  32.       try {  
  33.         // All edits for the given row (across all column families) must happen atomically.  
  34.         internalPut(put, put.getClusterId(), writeToWAL);  
  35.       } finally {  
  36.         if(lockid == null) releaseRowLock(lid);  
  37.       }  
  38.     } finally {  
  39.       closeRegionOperation();  
  40.     }  
  41.   }  

getLock调用了internalObtainRowLock:

[java] view plain copy

  1. private Integer internalObtainRowLock(final HashedBytes rowKey, boolean waitForLock)  
  2.      throws IOException {  
  3.    checkRow(rowKey.getBytes(), "row lock");  
  4.    startRegionOperation();  
  5.    try {  
  6.      CountDownLatch rowLatch = new CountDownLatch(1);  
  7.   
  8.      // loop until we acquire the row lock (unless !waitForLock)  
  9.      while (true) {  
  10.        CountDownLatch existingLatch = lockedRows.putIfAbsent(rowKey, rowLatch);  
  11.        if (existingLatch == null) {  
  12.          break;  
  13.        } else {  
  14.          // row already locked  
  15.          if (!waitForLock) {  
  16.            return null;  
  17.          }  
  18.          try {  
  19.            if (!existingLatch.await(this.rowLockWaitDuration,  
  20.                            TimeUnit.MILLISECONDS)) {  
  21.              throw new IOException("Timed out on getting lock for row=" + rowKey);  
  22.            }  
  23.          } catch (InterruptedException ie) {  
  24.            // Empty  
  25.          }  
  26.        }  
  27.      }  
  28.   
  29.      // loop until we generate an unused lock id  
  30.      while (true) {  
  31.        Integer lockId = lockIdGenerator.incrementAndGet();  
  32.        HashedBytes existingRowKey = lockIds.putIfAbsent(lockId, rowKey);  
  33.        if (existingRowKey == null) {  
  34.          return lockId;  
  35.        } else {  
  36.          // lockId already in use, jump generator to a new spot  
  37.          lockIdGenerator.set(rand.nextInt());  
  38.        }  
  39.      }  
  40.    } finally {  
  41.      closeRegionOperation();  
  42.    }  
  43.  }  

HBase行锁的实现细节推荐下:hbase源码解析之行锁  

HBase也提供API(lockRow/unlockRow)显示的获取行锁,但不推荐使用。原因是两个客户端很可能在拥有对方请求的锁时,又同时请求对方已拥有的锁,这样便形成了死锁,在锁超时前,两个被阻塞的客户端都会占用一个服务端的处理线程,而服务器线程是非常稀缺的资源

HBase提供了几个特别的原子操作接口:
 checkAndPut/checkAndDelete/increment/append,这几个接口非常有用,内部实现也是基于行锁
checkAndPut/checkAndDelete内部调用代码片段:

[java] view plain copy

  1. // Lock row  
  2. Integer lid = getLock(lockId, get.getRow(), true);  
  3. ......  
  4. // get and compare  
  5. try {  
  6.   result = get(get, false);  
  7.   ......  
  8.   //If matches put the new put or delete the new delete  
  9.   if (matches) {  
  10.     if (isPut) {  
  11.       internalPut(((Put) w), HConstants.DEFAULT_CLUSTER_ID, writeToWAL);  
  12.     } else {  
  13.       Delete d = (Delete)w;  
  14.       prepareDelete(d);  
  15.       internalDelete(d, HConstants.DEFAULT_CLUSTER_ID, writeToWAL);  
  16.     }  
  17.     return true;  
  18.   }  
  19.   return false;  
  20. } finally {  
  21.   // release lock  
  22.   if(lockId == null) releaseRowLock(lid);  
  23. }  

实现逻辑:加锁=>get=>比较=>put/delete

checkAndPut在实际应用中非常有价值,我们线上生成Dpid的项目,多个客户端会并行生成DPID,如果有一个客户端已经生成了一个DPID,则其他客户端不能生成新的DPID,只能获取该DPID
代码片段:

[java] view plain copy

  1. ret = hbaseUse.checkAndPut("bi.dpdim_mac_dpid_mapping", mac, "dim",  
  2.         "dpid", null, dpid);  
  3. if(false == ret){  
  4.     String retDpid = hbaseUse.query("bi.dpdim_mac_dpid_mapping", mac, "dim", "dpid");  
  5.     if(!retDpid.equals(ABNORMAL)){  
  6.         return retDpid;  
  7.     }  
  8. }else{  
  9.     columnList.add("mac");  
  10.     valueList.add(mac);  
  11. }  

 

checkAndPut详细试用可以参考: HBaseEveryDay_Atomic_compare_and_set  

Reference:
HBase - Apache HBase (TM) ACID Properties
hbase源码解析之行锁  
Hbase权威指南
HBaseEveryDay_Atomic_compare_and_set  

转载于:https://my.oschina.net/sniperLi/blog/915224

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值