Cómo conectarse a HBase remoto en Java?


Tengo un servidor HBase standlone. Este es mi sitio de hbase.xml:

<configuration>
 <property>
    <name>hbase.rootdir</name>
    <value>file:///hbase_data</value>
  </property>
</configuration>

Estoy tratando de escribir un programa Java para manipular los datos en la HBase.

Si corro el programa en el servidor HBase, funciona bien. Pero no se como configurarlo para acceso remoto.

  Configuration config = HBaseConfiguration.create();
   HTable table = new HTable(config, "test");
   Scan s = new Scan();

He intentado agregar IP y Puerto, no funciona:

config.set("hbase.master", "146.169.35.28:60000")

¿alguien Puede decirme cómo hacerlo?

Gracias!

 36
Author: leon, 2011-07-07

5 answers

Aquí hay un fragmento de un sistema que usamos para crear una HTable que usamos para conectarnos a HBase

Configuration hConf = HBaseConfiguration.create(conf);
hConf.set(Constants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM, hbaseZookeeperQuorum);
hConf.setInt(Constants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT, hbaseZookeeperClientPort);

HTable hTable = new HTable(hConf, tableName);

HTH

EDITAR: Valores de ejemplo:

public static final String HBASE_CONFIGURATION_ZOOKEEPER_QUORUM                     = "hbase.zookeeper.quorum";
public static final String HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT                 = "hbase.zookeeper.property.clientPort";
...
hbaseZookeeperQuorum="PDHadoop1.corp.CompanyName.com,PDHadoop2.corp.CompanyName.com";
hbaseZookeeperClientPort=10000;
tableName="HBaseTableName";
 27
Author: QuinnG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-21 15:13:12

hbase.master es @ obsoleto. Los clientes usan Zookeeper para obtener el nombre de host/puerto actual de sus servidores HBase.

@Deprecated
config.set("hbase.master", "146.169.35.28:60000")

Hadoop y HBase son muy sensibles a la configuración DNS y /etc/hosts. Asegúrese de que su nombre de host no apunte a 127.0.0.1 de lo contrario, comenzará a escuchar muchos servicios solo en localhost. Intente no usar direcciones IP en ningún lugar de la configuración.

Mi /etc/hosts:

192.168.2.3     cloudera-vm     # Added by NetworkManager
127.0.0.1       localhost.localdomain   localhost
127.0.1.1       cloudera-vm-local localhost

/etc/hbase/hbase-site.xml debe tener settings set distributed=false (ya que está usando esto para probar solamente):

<property>
  <name>hbase.cluster.distributed</name>
  <value>false</value>
</property>

/etc/zookeeper/zoo.cfg

# the port at which the clients will connect
clientPort=2181
server.0=cloudera-vm:2888:3888

Lista de mis procesos Java:

root@cloudera-vm:~# jps
1643 TaskTracker
1305 JobTracker
1544 SecondaryNameNode
2037 Bootstrap
9622 DataNode
10144 Jps
9468 NameNode
1948 RunJar
9746 HMaster
 11
Author: vladaman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 05:08:36

En pocas palabras esto es lo que uso:

    Configuration hBaseConfig =  HBaseConfiguration.create();
    hBaseConfig.setInt("timeout", 120000);
    hBaseConfig.set("hbase.master", "*" + hbaseHost + ":9000*");
    hBaseConfig.set("hbase.zookeeper.quorum",zookeeperHost);
    hBaseConfig.set("hbase.zookeeper.property.clientPort", "2181");

Para hBaseHost y zookeeperHost simplemente paso la dirección ip de un equipo de clúster que tiene zookeeper instalado. Por supuesto, también puede parametizar los números de puerto. No estoy 100% seguro de que esta sea la mejor manera de garantizar una conexión exitosa, pero hasta ahora funciona sin problemas.

 7
Author: Marquez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-02 14:44:13

Por lo que sé, si desea conectarse a un servidor remoto hbase el cliente java normal no funciona, en el que solo declaramos la configuración e intentamos conectarnos a la hbase remota como se menciona en precious answers.

He intentado esto de arriba, pero nunca lo he conseguido. En su lugar, utilicé Thrift API para conectarme a un servidor remoto,

Este enlace es el mejor ejemplo de uso de la API de ahorro java client.It seguramente funciona.Estoy usando lo mismo. Pero antes de usarlo con cuidado ir a través del código y emitir los elementos que no necesita. También estoy dando el código de ejemplo para el mismo que funciona con éxito.

public class ThriftClient 
{

    port = 9090;
    //Connection to hbase
    TTransport transport = new TSocket(hostname, port);
    TProtocol protocol = new TBinaryProtocol(transport, true, true);
    Hbase.Client client = new Hbase.Client(protocol);

    transport.open();

    int z=Link.length();
    byte[] tablename = bytes("YOUR TABLE NAME");

    // Create the demo table with two column families, entry: and unused:
    ArrayList<ColumnDescriptor> columns = new ArrayList<ColumnDescriptor>();
    ColumnDescriptor col = null;
    col = new ColumnDescriptor();
    col.name = ByteBuffer.wrap(bytes("YOUR_COLUMN_FAMILY_NAME"));
    col.maxVersions = 10;
    columns.add(col);

    System.out.println("creating table: " + utf8(tablename));
    try 
    {
        client.createTable(ByteBuffer.wrap(tablename), columns);
    } 
    catch (AlreadyExists ae) 
    {
        System.out.println("WARN: " + ae.message);
    }

    Map<ByteBuffer, ByteBuffer> dummyAttributes = null;
    boolean writeToWal = false;
    // Test UTF-8 handling
    byte[] invalid = {(byte) 'f', (byte) 'o', (byte) 'o', (byte) '-',
        (byte) 0xfc, (byte) 0xa1, (byte) 0xa1, (byte) 0xa1, (byte) 0xa1};
    byte[] valid = {(byte) 'f', (byte) 'o', (byte) 'o', (byte) '-',
        (byte) 0xE7, (byte) 0x94, (byte) 0x9F, (byte) 0xE3, (byte) 0x83,
        (byte) 0x93, (byte) 0xE3, (byte) 0x83, (byte) 0xBC, (byte) 0xE3,
        (byte) 0x83, (byte) 0xAB};


    ArrayList<Mutation> mutations;

    // Run some operations on a bunch of rows

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumIntegerDigits(10);
    nf.setGroupingUsed(false);
    byte[] row=bytes("YOUR ROW NAME");

    mutations = new ArrayList<Mutation>();
    mutations.add(new Mutation(false, ByteBuffer.wrap(bytes("YOUR_COLUMN_FAMILY_NAME:YOUR_COLUMN_NAME")), ByteBuffer.wrap(bytes("YOUR_ROW_VALUE")), writeToWal));
    client.mutateRow(ByteBuffer.wrap(tablename), ByteBuffer.wrap(row), mutations, dummyAttributes);

    transport.close();

    // Helper to translate byte[]'s to UTF8 strings
private static String utf8(byte[] buf) {
    try {
        return decoder.decode(ByteBuffer.wrap(buf)).toString();
    } catch (CharacterCodingException e) {
        return "[INVALID UTF-8]";
    }
}

// Helper to translate strings to UTF8 bytes
private static byte[] bytes(String s) {
    try {
        return s.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}
}
 1
Author: ashubhargave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-04 12:00:42

En mi caso después de jugar mucho con /etc/hosts terminé encontrando en el archivo de registro "hbase-bgi-master-servername.log" la siguiente línea:

"2017-11-21 19:56:32,999 INFO [RS :0; servername: 45553] regionserver.HRegionServer: Sirve como servername.local.lan, 45553, 1511290584538, RpcServer en servername.local.lan / 172.0.1.2: 45553, sessionid = 0x15fdff039790002 "

Siempre asegúrese de que el nombre de host completo ("servername.local.lan" en mi caso) en realidad apunta a la IP del servidor tanto en el lado del cliente como del servidor.

 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 17:05:41