001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.client.example; 019 020import java.util.concurrent.CompletableFuture; 021import java.util.concurrent.CountDownLatch; 022import java.util.concurrent.ExecutorService; 023import java.util.concurrent.Executors; 024import java.util.concurrent.atomic.AtomicReference; 025import java.util.stream.IntStream; 026import org.apache.commons.io.IOUtils; 027import org.apache.hadoop.conf.Configured; 028import org.apache.hadoop.hbase.TableName; 029import org.apache.hadoop.hbase.client.AsyncConnection; 030import org.apache.hadoop.hbase.client.AsyncTable; 031import org.apache.hadoop.hbase.client.ConnectionFactory; 032import org.apache.hadoop.hbase.client.Get; 033import org.apache.hadoop.hbase.client.Put; 034import org.apache.hadoop.hbase.util.Bytes; 035import org.apache.hadoop.hbase.util.Threads; 036import org.apache.hadoop.util.Tool; 037import org.apache.hadoop.util.ToolRunner; 038import org.apache.yetus.audience.InterfaceAudience; 039import org.slf4j.Logger; 040import org.slf4j.LoggerFactory; 041 042/** 043 * A simple example shows how to use asynchronous client. 044 */ 045@InterfaceAudience.Private 046public class AsyncClientExample extends Configured implements Tool { 047 048 private static final Logger LOG = LoggerFactory.getLogger(AsyncClientExample.class); 049 050 /** 051 * The size for thread pool. 052 */ 053 private static final int THREAD_POOL_SIZE = 16; 054 055 /** 056 * The default number of operations. 057 */ 058 private static final int DEFAULT_NUM_OPS = 100; 059 060 /** 061 * The name of the column family. d for default. 062 */ 063 private static final byte[] FAMILY = Bytes.toBytes("d"); 064 065 /** 066 * For the example we're just using one qualifier. 067 */ 068 private static final byte[] QUAL = Bytes.toBytes("test"); 069 070 private final AtomicReference<CompletableFuture<AsyncConnection>> future = 071 new AtomicReference<>(); 072 073 private CompletableFuture<AsyncConnection> getConn() { 074 CompletableFuture<AsyncConnection> f = future.get(); 075 if (f != null) { 076 return f; 077 } 078 for (;;) { 079 if (future.compareAndSet(null, new CompletableFuture<>())) { 080 CompletableFuture<AsyncConnection> toComplete = future.get(); 081 ConnectionFactory.createAsyncConnection(getConf()).whenComplete((conn, error) -> { 082 if (error != null) { 083 toComplete.completeExceptionally(error); 084 // we need to reset the future holder so we will get a chance to recreate an async 085 // connection at next try. 086 future.set(null); 087 return; 088 } 089 toComplete.complete(conn); 090 }); 091 return toComplete; 092 } else { 093 f = future.get(); 094 if (f != null) { 095 return f; 096 } 097 } 098 } 099 } 100 101 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NONNULL_PARAM_VIOLATION", 102 justification="it is valid to pass NULL to CompletableFuture#completedFuture") 103 private CompletableFuture<Void> closeConn() { 104 CompletableFuture<AsyncConnection> f = future.get(); 105 if (f == null) { 106 return CompletableFuture.completedFuture(null); 107 } 108 CompletableFuture<Void> closeFuture = new CompletableFuture<>(); 109 f.whenComplete((conn, error) -> { 110 if (error == null) { 111 IOUtils.closeQuietly(conn); 112 } 113 closeFuture.complete(null); 114 }); 115 return closeFuture; 116 } 117 118 private byte[] getKey(int i) { 119 return Bytes.toBytes(String.format("%08x", i)); 120 } 121 122 @Override 123 public int run(String[] args) throws Exception { 124 if (args.length < 1 || args.length > 2) { 125 System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]"); 126 return -1; 127 } 128 TableName tableName = TableName.valueOf(args[0]); 129 int numOps = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_NUM_OPS; 130 ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE, 131 Threads.newDaemonThreadFactory("AsyncClientExample")); 132 // We use AsyncTable here so we need to provide a separated thread pool. RawAsyncTable does not 133 // need a thread pool and may have a better performance if you use it correctly as it can save 134 // some context switches. But if you use RawAsyncTable incorrectly, you may have a very bad 135 // impact on performance so use it with caution. 136 CountDownLatch latch = new CountDownLatch(numOps); 137 IntStream.range(0, numOps).forEach(i -> { 138 CompletableFuture<AsyncConnection> future = getConn(); 139 future.whenComplete((conn, error) -> { 140 if (error != null) { 141 LOG.warn("failed to get async connection for " + i, error); 142 latch.countDown(); 143 return; 144 } 145 AsyncTable<?> table = conn.getTable(tableName, threadPool); 146 table.put(new Put(getKey(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(i))) 147 .whenComplete((putResp, putErr) -> { 148 if (putErr != null) { 149 LOG.warn("put failed for " + i, putErr); 150 latch.countDown(); 151 return; 152 } 153 LOG.info("put for " + i + " succeeded, try getting"); 154 table.get(new Get(getKey(i))).whenComplete((result, getErr) -> { 155 if (getErr != null) { 156 LOG.warn("get failed for " + i); 157 latch.countDown(); 158 return; 159 } 160 if (result.isEmpty()) { 161 LOG.warn("get failed for " + i + ", server returns empty result"); 162 } else if (!result.containsColumn(FAMILY, QUAL)) { 163 LOG.warn("get failed for " + i + ", the result does not contain " + 164 Bytes.toString(FAMILY) + ":" + Bytes.toString(QUAL)); 165 } else { 166 int v = Bytes.toInt(result.getValue(FAMILY, QUAL)); 167 if (v != i) { 168 LOG.warn("get failed for " + i + ", the value of " + Bytes.toString(FAMILY) + 169 ":" + Bytes.toString(QUAL) + " is " + v + ", exected " + i); 170 } else { 171 LOG.info("get for " + i + " succeeded"); 172 } 173 } 174 latch.countDown(); 175 }); 176 }); 177 }); 178 }); 179 latch.await(); 180 closeConn().get(); 181 return 0; 182 } 183 184 public static void main(String[] args) throws Exception { 185 ToolRunner.run(new AsyncClientExample(), args); 186 } 187}