1. 使用检查写(check and put)可以保证操作的原子性。即执行put前先检查数值是否与提供的value一致,如果检查通过就执行put,否则就放弃。如果需要put前该字段值不存在,将value设置成null即可。
@Test public void testCheckPut() throws Exception{ Table table = conn.getTable(TableName.valueOf("t1")); Put put = new Put(Bytes.toBytes("row2")); put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes("terry2")); put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("job"), Bytes.toBytes("manager2")); boolean res = table.checkAndPut(Bytes.toBytes("row2"), Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes("terry"), put); if(res) System.out.println("update success"); else System.out.println("update failure"); table.close(); }