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