Hbase-API-原子性操作,hbase-api-原子操作
原子性操作compare-and-set:先比较原值,再做修改
有一种特殊的put调用–检查写,
boolean checkAndPut(byte[] row,byte[] familay,byte[] qualifier,byte[] value,Put [ut)
这种检查写能够保证服务器端put操作的原子性。(如果检查成功就通过,否则就彻底放弃)这种方法可用来检查现有相关值,并决定是否进行修改数据操作。
这种方法一般使用于在读取数据时也需要处理数据。
有一种特殊检查通过checkAndPut完成,即只在另外一个值不存在时,才执行修改。要执行这种操作只用将参数value设置为null。
Configuration conf = HBaseConfiguration.create();
HTable table = new HTable(conf,"testtable");
Put put1 = new Put(Bytes.toBytes("testdata"));
put1.add(Bytes.toBytes("colfam1"),
Bytes.toBytes("testqualifier"),Bytes.toBytes("testdata-no1"));
boolean res1 = table.checkAndPut(Bytes.toBytes("testdata"),
Bytes.toBytes("colfam1"), Bytes.toBytes("testqualifier"),
null, put1);
System.out.println("Put applied:"+res1);
boolean res2 = table.checkAndPut(Bytes.toBytes("testdata"),
Bytes.toBytes("colfam1"), Bytes.toBytes("testqualifier"),
null, put1);
System.out.println("Put applied:"+res2);
//必须要表中有这个列族在能够比较加入
Put put2 = new Put(Bytes.toBytes("testdata"));
put1.add(Bytes.toBytes("colfam1"),
Bytes.toBytes("testqualifier"),Bytes.toBytes("testdata-no2"));
boolean res3 = table.checkAndPut(Bytes.toBytes("testdata"),
Bytes.toBytes("colfam1"), Bytes.toBytes("testqualifier"),
Bytes.toBytes("testdata-no1"), put2);
System.out.println("Put applied:"+res3);
//检查表中是否有某行某列族的某值,再绝对将put实例的内容与检查到的值进行修改
CAS操作,只能检查和修改同一行的数据(只提供同一行的原子性保证),如果检查和修改针对的不是同一行数据时(行键不同)会抛出异常
CAS操作很强大,在分布式系统中。有多个客户端同时操作数据时 ,这个方法提供并发修改数据功能。
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。