@Override public void init() throws DBException { insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY; updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY; Properties props = getProperties(); namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE); String host = props.getProperty("as.host", DEFAULT_HOST); String user = props.getProperty("as.user"); String password = props.getProperty("as.password"); int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT)); int timeout = Integer.parseInt(props.getProperty("as.timeout", DEFAULT_TIMEOUT)); readPolicy.timeout = timeout; insertPolicy.timeout = timeout; updatePolicy.timeout = timeout; deletePolicy.timeout = timeout; ClientPolicy clientPolicy = new ClientPolicy(); if (user != null && password != null) { clientPolicy.user = user; clientPolicy.password = password; } try { client = new com.aerospike.client.AerospikeClient(clientPolicy, host, port); } catch (AerospikeException e) { throw new DBException(String.format("Error while creating Aerospike " + "client for %s:%d.", host, port), e); } }
private Status write(String table, String key, WritePolicy writePolicy, Map<String, ByteIterator> values) { Bin[] bins = new Bin[values.size()]; int index = 0; for (Map.Entry<String, ByteIterator> entry: values.entrySet()) { bins[index] = new Bin(entry.getKey(), entry.getValue().toArray()); ++index; } Key keyObj = new Key(namespace, table, key); try { client.put(writePolicy, keyObj, bins); return Status.OK; } catch (AerospikeException e) { System.err.println("Error while writing key " + key + ": " + e); return Status.ERROR; } }
@Override public void cleanup() throws DBException { client.close(); }
static void cleanMetaTable() { AerospikeClient client = null; try { client = new AerospikeClient(NODE, PORT); Statement stmnt = new Statement(); stmnt.setNamespace(NAMESPACE); stmnt.setSetName(AerospikeTransactionalStore.DEFAULT_META_SET); RecordSet rs = client.query(null, stmnt); while (rs.next()) { client.delete(null, rs.getKey()); } } catch (AerospikeException e) { LOG.error("cleanMetaTable failed: {}", e); throw e; } finally { if (null != client) { client.close(); } } }
static long getNumOfEventsInStore() { AerospikeClient client = null; try { long count = 0; client = new AerospikeClient(NODE, PORT); Statement stmnt = new Statement(); stmnt.setNamespace(NAMESPACE); stmnt.setSetName(SET_NAME); RecordSet rs = client.query(null, stmnt); while (rs.next()) { count++; } return count; } catch (AerospikeException e) { LOG.error("getNumOfEventsInStore failed: {}", e); throw e; } finally { if (null != client) { client.close(); } } }
public void insertEventsInTable(int numEvents) { AerospikeClient client = null; try { client = new AerospikeClient(NODE, PORT); Key key; Bin bin; for (int i = 0; i < numEvents; i++) { key = new Key(NAMESPACE,SET_NAME,String.valueOf(i)); bin = new Bin("ID",i); client.put(null, key, bin); } } catch (AerospikeException e) { throw e; } finally { if (null != client) { client.close(); } } }
@Override public Status delete(String table, String key) { try { if (!client.delete(deletePolicy, new Key(namespace, table, key))) { System.err.println("Record key " + key + " not found (delete)"); return Status.ERROR; } return Status.OK; } catch (AerospikeException e) { System.err.println("Error while deleting key " + key + ": " + e); return Status.ERROR; } } }
public static void main(String args[]) throws Exception { AerospikeClient client = new AerospikeClient(args[0], 3000); String skey = "accountingsystem"; Key key = new Key("test", "cache", skey); while(true) { Record record = null; record = client.get(null, key); String value = (String)record.bins.get("value"); System.out.println(value); Thread.sleep(1000); } } }
/** * Connect and run one or more client examples. */ public static void runExamples(Console console, Parameters params, List<String> examples) throws Exception { ClientPolicy policy = new ClientPolicy(); policy.user = params.user; policy.password = params.password; policy.authMode = params.authMode; policy.tlsPolicy = params.tlsPolicy; params.policy = policy.readPolicyDefault; params.writePolicy = policy.writePolicyDefault; Host[] hosts = Host.parseHosts(params.host, params.port); AerospikeClient client = new AerospikeClient(policy, hosts); try { params.setServerSpecific(client); for (String exampleName : examples) { runExample(exampleName, client, params, console); } } finally { client.close(); } }
@Override public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { try { Record record; if (fields != null) { record = client.get(readPolicy, new Key(namespace, table, key), fields.toArray(new String[fields.size()])); } else { record = client.get(readPolicy, new Key(namespace, table, key)); } if (record == null) { System.err.println("Record key " + key + " not found (read)"); return Status.ERROR; } for (Map.Entry<String, Object> entry: record.bins.entrySet()) { result.put(entry.getKey(), new ByteArrayByteIterator((byte[])entry.getValue())); } return Status.OK; } catch (AerospikeException e) { System.err.println("Error while reading key " + key + ": " + e); return Status.ERROR; } }
private static AerospikeClient getAerospikeClient(CommandLine cl) { ClientPolicy clientPolicy = new ClientPolicy(); initClientPolicy(cl, clientPolicy); AerospikeClient client = new AerospikeClient(clientPolicy, params.hosts); if (!client.isConnected()) { log.error("Client is not able to connect:" + params.hosts); return null; } try { // Check read-write role is given to user. if (!client.queryUser(null, clientPolicy.user).roles.contains(Role.ReadWrite)) { log.error("User role:" + client.queryUser(null, clientPolicy.user).roles.toString() + " Expected:" + Role.ReadWrite); return null; } } catch (AerospikeException e) { // Ignore if security is not enabled. } return client; }
private void writeIfGenerationNotChanged(AerospikeClient client, Parameters params) throws Exception { Key key = new Key(params.namespace, params.set, "udfkey2"); Bin bin = new Bin(params.getBinName("udfbin2"), "string value"); // Seed record. client.put(params.writePolicy, key, bin); // Get record generation. long gen = (Long)client.execute(params.writePolicy, key, "record_example", "getGeneration"); // Write record if generation has not changed. client.execute(params.writePolicy, key, "record_example", "writeIfGenerationNotChanged", Value.get(bin.name), bin.value, Value.get(gen)); console.info("Record written."); }
/** * Issues an "Info" request to all nodes in the cluster. * @param client * @param infoString * @return */ public static String[] infoAll(AerospikeClient client, String infoString) { String[] messages = new String[client.getNodes().length]; int index = 0; for (Node node : client.getNodes()){ messages[index] = Info.request(node, infoString); } return messages; } /**
private void writeUsingUdf(AerospikeClient client, Parameters params) throws Exception { Key key = new Key(params.namespace, params.set, "udfkey1"); Bin bin = new Bin(params.getBinName("udfbin1"), "string value"); client.execute(params.writePolicy, key, "record_example", "writeBin", Value.get(bin.name), bin.value); Record record = client.get(params.policy, key, bin.name); String expected = bin.value.toString(); String received = record.getString(bin.name); if (received != null && received.equals(expected)) { console.info("Data matched: namespace=%s set=%s key=%s bin=%s value=%s", key.namespace, key.setName, key.userKey, bin.name, received); } else { console.error("Data mismatch: Expected %s. Received %s.", expected, received); } }
@Override protected boolean isReady() { String containerId = waitStrategyTarget.getContainerId(); log.debug("Check Aerospike container {} status", containerId); InspectContainerResponse containerInfo = waitStrategyTarget.getContainerInfo(); if (containerInfo == null) { log.debug("Aerospike container[{}] doesn't contain info. Abnormal situation, should not happen.", containerId); return false; } int port = getMappedPort(containerInfo.getNetworkSettings(), properties.port); String host = DockerClientFactory.instance().dockerHostIpAddress(); //TODO: Remove dependency to client https://www.aerospike.com/docs/tools/asmonitor/common_tasks.html try (AerospikeClient client = new AerospikeClient(host, port)) { return client.isConnected(); } catch (AerospikeException.Connection e) { log.debug("Aerospike container: {} not yet started. {}", containerId, e.getMessage()); } return false; }
RecordSet recordSet = client.query(null, statement);
/** * Deletes the records specified by the Statement and Qualifiers * * @param stmt A Statement object containing Namespace and Set * @param qualifiers Zero or more Qualifiers for the update query * @return returns a Map containing a number of successful updates. The Map will contain 2 keys "read" and "write", the values will be the count of successful operations */ public Map<String, Long> delete(Statement stmt, Qualifier... qualifiers) { if (qualifiers == null || qualifiers.length == 0) { /* * There are no qualifiers, so delete every record in the set * using Scan UDF delete */ ExecuteTask task = client.execute(null, stmt, QUERY_MODULE, "delete_record"); task.waitTillComplete(); return null; } if (qualifiers.length == 1 && qualifiers[0] instanceof KeyQualifier) { KeyQualifier keyQualifier = (KeyQualifier) qualifiers[0]; Key key = keyQualifier.makeKey(stmt.getNamespace(), stmt.getSetName()); this.client.delete(null, key); Map<String, Long> map = new HashMap<String, Long>(); map.put("read", 1L); map.put("write", 1L); return map; } KeyRecordIterator results = select(stmt, true, null, qualifiers); return delete(results); }
private void createIndexes() { IndexTask task; try { task = client.createIndex(null, namespace, metaSet, "operatorIdIndex", metaTableOperatorIdColumn, IndexType.NUMERIC); task.waitTillComplete(); task = client.createIndex(null, namespace, metaSet, "appIdIndex", metaTableAppIdColumn, IndexType.STRING); task.waitTillComplete(); } catch (AerospikeException ex) { throw new RuntimeException(ex); } }
/** * Select records filtered by Qualifiers * * @param stmt A Statement object containing Namespace, Set and the Bins to be returned. * @param sortMap <STRONG>NOT IMPLEMENTED</STRONG> * @param qualifiers Zero or more Qualifiers for the update query * @return A KeyRecordIterator to iterate over the results */ public KeyRecordIterator select(Statement stmt, Map<String, String> sortMap, Qualifier... qualifiers) { KeyRecordIterator results = null; if (qualifiers != null && qualifiers.length > 0) { Map<String, Object> originArgs = new HashMap<String, Object>(); originArgs.put("includeAllFields", 1); String filterFuncStr = buildFilterFunction(qualifiers); originArgs.put("filterFuncStr", filterFuncStr); String sortFuncStr = buildSortFunction(sortMap); originArgs.put("sortFuncStr", sortFuncStr); stmt.setAggregateFunction(this.getClass().getClassLoader(), AS_UTILITY_PATH, QUERY_MODULE, "select_records", Value.get(originArgs)); ResultSet resultSet = this.client.queryAggregate(queryPolicy, stmt); results = new KeyRecordIterator(stmt.getNamespace(), resultSet); } else { RecordSet recordSet = this.client.query(queryPolicy, stmt); results = new KeyRecordIterator(stmt.getNamespace(), recordSet); } return results; }
@Override protected void get(Key key, String udfPackageName, String udfFunctionName, Value[] udfValues) { Object udfReturnObj; if (counters.read.latency != null) { long begin = System.nanoTime(); udfReturnObj = client.execute(args.writePolicy, key, udfPackageName, udfFunctionName, udfValues); long elapsed = System.nanoTime() - begin; counters.read.latency.add(elapsed); } else { udfReturnObj = client.execute(args.writePolicy, key, udfPackageName, udfFunctionName, udfValues); } processRead(key, udfReturnObj); }