static Session connect() { String contactPoint = "localhost"; String keySpace = "ks1"; if(session == null) { DCAwareRoundRobinPolicy dcAwarePolicy = new DCAwareRoundRobinPolicy.Builder().build(); LoadBalancingPolicy policy = new TokenAwarePolicy(dcAwarePolicy); cluster = Cluster.builder().addContactPoint(contactPoint) .withLoadBalancingPolicy(policy).build(); cluster.init(); for (Host host : cluster.getMetadata().getAllHosts()) { System.out.printf("Address: %s, Rack: %s, Datacenter: %s, Tokens: %s\n", host.getAddress(), host.getDatacenter(), host.getRack(), host.getTokens()); } } return session; }
/** * Parse the load balancing policy. */ public static LoadBalancingPolicy parseLbPolicy(String loadBalancingPolicyString) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { String lb_regex = "([a-zA-Z]*Policy)(\\()(.*)(\\))"; Pattern lb_pattern = Pattern.compile(lb_regex); if (!loadBalancingPolicyString.contains("(")) { loadBalancingPolicyString += "()"; } Matcher lb_matcher = lb_pattern.matcher(loadBalancingPolicyString); if (lb_matcher.matches()) { if (lb_matcher.groupCount() > 0) { // Primary LB policy has been specified String primaryLoadBalancingPolicy = lb_matcher.group(1); String loadBalancingPolicyParams = lb_matcher.group(3); return getLbPolicy(primaryLoadBalancingPolicy, loadBalancingPolicyParams); } } return null; }
/** * Connect to a cassandra cluster at a given host/port */ public void connect() { try { lock.lock(); } catch (IOException e) { throw new IllegalStateException("There appears to be another health check running", e); } final List<InetSocketAddress> whiteList= new ArrayList<>(); whiteList.add(new InetSocketAddress(host, port)); final LoadBalancingPolicy loadBalancingPolicy = new WhiteListPolicy(new RoundRobinPolicy(), whiteList); final Cluster.Builder cb = Cluster.builder() .addContactPoint(host) .withPort(port) .withLoadBalancingPolicy(loadBalancingPolicy) .withRetryPolicy(retryPolicy); if (username != null) { cb.withCredentials(username, password); } cluster = cb.build(); session = cluster.connect(); hosts = cluster.getMetadata().getAllHosts(); }
@Override public LoadBalancingPolicy build() { LatencyAwarePolicy.Builder builder = LatencyAwarePolicy.builder(subPolicy.build()); if (exclusionThreshold != null) { builder.withExclusionThreshold(exclusionThreshold); } if (minimumMeasurements != null) { builder.withMininumMeasurements(minimumMeasurements); } if (retryPeriod != null) { builder.withRetryPeriod(retryPeriod.getQuantity(), retryPeriod.getUnit()); } if (scale != null) { builder.withScale(scale.getQuantity(), scale.getUnit()); } if (updateRate != null) { builder.withUpdateRate(updateRate.getQuantity(), updateRate.getUnit()); } return builder.build(); }
@Override public LoadBalancingPolicy build() { DCAwareRoundRobinPolicy.Builder builder = DCAwareRoundRobinPolicy.builder(); if (allowRemoteDCsForLocalConsistencyLevel == Boolean.TRUE) { builder.allowRemoteDCsForLocalConsistencyLevel(); } if (localDC != null) { builder.withLocalDc(localDC); } if (usedHostsPerRemoteDC != null) { builder.withUsedHostsPerRemoteDc(usedHostsPerRemoteDC); } return builder.build(); }
@Test public void buildsPolicyWithNoParams() throws Exception { final LatencyAwarePolicyFactory factory = new LatencyAwarePolicyFactory(); factory.setSubPolicy(subPolicyFactory); final LoadBalancingPolicy policy = factory.build(); assertThat(policy).isSameAs(resultingPolicy); verify(subPolicyFactory).build(); verify(policyBuilder, never()).withExclusionThreshold(anyDouble()); verify(policyBuilder, never()).withMininumMeasurements(anyInt()); verify(policyBuilder, never()).withRetryPeriod(anyLong(), any(TimeUnit.class)); verify(policyBuilder, never()).withScale(anyLong(), any(TimeUnit.class)); verify(policyBuilder, never()).withUpdateRate(anyLong(), any(TimeUnit.class)); verify(policyBuilder).build(); }
@Test public void buildsPolicyWithAllParams() throws Exception { final LatencyAwarePolicyFactory factory = new LatencyAwarePolicyFactory(); factory.setSubPolicy(subPolicyFactory); factory.setExclusionThreshold(1.0d); factory.setMinimumMeasurements(2); factory.setRetryPeriod(Duration.minutes(3)); factory.setScale(Duration.milliseconds(100)); factory.setUpdateRate(Duration.seconds(5)); final LoadBalancingPolicy policy = factory.build(); assertThat(policy).isSameAs(resultingPolicy); verify(subPolicyFactory).build(); InOrder inOrder = inOrder(policyBuilder); inOrder.verify(policyBuilder).withExclusionThreshold(1.0d); inOrder.verify(policyBuilder).withMininumMeasurements(2); inOrder.verify(policyBuilder).withRetryPeriod(3L, TimeUnit.MINUTES); inOrder.verify(policyBuilder).withScale(100L, TimeUnit.MILLISECONDS); inOrder.verify(policyBuilder).withUpdateRate(5L, TimeUnit.SECONDS); inOrder.verify(policyBuilder).build(); }
public static Cluster getInputCluster(String[] hosts, Configuration conf) { int port = getInputNativePort(conf); Optional<AuthProvider> authProvider = getAuthProvider(conf); Optional<SSLOptions> sslOptions = getSSLOptions(conf); Optional<Integer> protocolVersion = getProtocolVersion(conf); LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(conf, hosts); SocketOptions socketOptions = getReadSocketOptions(conf); QueryOptions queryOptions = getReadQueryOptions(conf); PoolingOptions poolingOptions = getReadPoolingOptions(conf); Cluster.Builder builder = Cluster.builder() .addContactPoints(hosts) .withPort(port) .withCompression(ProtocolOptions.Compression.NONE); if (authProvider.isPresent()) builder.withAuthProvider(authProvider.get()); if (sslOptions.isPresent()) builder.withSSL(sslOptions.get()); if (protocolVersion.isPresent()) { builder.withProtocolVersion(protocolVersion.get()); } builder.withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withQueryOptions(queryOptions) .withPoolingOptions(poolingOptions); return builder.build(); }
private void configureLoadBalancingPolicy() { final String dataCenterNameConfiguration = (String) configuration.get(TRIDENT_CASSANDRA_LOCAL_DATA_CENTER_NAME); if (StringUtils.isNotEmpty(dataCenterNameConfiguration)) { final LoadBalancingPolicy loadBalancingPolicy = new DCAwareRoundRobinPolicy(dataCenterNameConfiguration); builder = builder.withLoadBalancingPolicy(loadBalancingPolicy); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { fetchSize = (Integer)in.readObject(); readConsistency = (ConsistencyLevel)in.readObject(); writeConsistency = (ConsistencyLevel)in.readObject(); user = U.readString(in); pwd = U.readString(in); port = (Integer)in.readObject(); contactPoints = (List<InetAddress>)in.readObject(); contactPointsWithPorts = (List<InetSocketAddress>)in.readObject(); maxSchemaAgreementWaitSeconds = (Integer)in.readObject(); protoVer = (Integer)in.readObject(); compression = U.readString(in); useSSL = (Boolean)in.readObject(); collectMetrix = (Boolean)in.readObject(); jmxReporting = (Boolean)in.readObject(); creds = (Credentials)in.readObject(); loadBalancingPlc = (LoadBalancingPolicy)readObject(in); reconnectionPlc = (ReconnectionPolicy)readObject(in); addrTranslator = (AddressTranslator)readObject(in); speculativeExecutionPlc = (SpeculativeExecutionPolicy)readObject(in); authProvider = (AuthProvider)readObject(in); sslOptions = (SSLOptions)readObject(in); poolingOptions = (PoolingOptions)readObject(in); sockOptions = (SocketOptions)readObject(in); nettyOptions = (NettyOptions)readObject(in); }
/** * Serialization test. */ @Test public void serializationTest() { DataSource src = new DataSource(); Credentials cred = new CassandraAdminCredentials(); String[] points = new String[]{"127.0.0.1", "10.0.0.2", "10.0.0.3"}; LoadBalancingPolicy plc = new MyLoadBalancingPolicy(); src.setCredentials(cred); src.setContactPoints(points); src.setReadConsistency("ONE"); src.setWriteConsistency("QUORUM"); src.setLoadBalancingPolicy(plc); JavaSerializer serializer = new JavaSerializer(); ByteBuffer buff = serializer.serialize(src); DataSource _src = (DataSource)serializer.deserialize(buff); Credentials _cred = (Credentials)getFieldValue(_src, "creds"); List<InetAddress> _points = (List<InetAddress>)getFieldValue(_src, "contactPoints"); ConsistencyLevel _readCons = (ConsistencyLevel)getFieldValue(_src, "readConsistency"); ConsistencyLevel _writeCons = (ConsistencyLevel)getFieldValue(_src, "writeConsistency"); LoadBalancingPolicy _plc = (LoadBalancingPolicy)getFieldValue(_src, "loadBalancingPlc"); assertTrue("Incorrectly serialized/deserialized credentials for Cassandra DataSource", cred.getPassword().equals(_cred.getPassword()) && cred.getUser().equals(_cred.getUser())); assertTrue("Incorrectly serialized/deserialized contact points for Cassandra DataSource", "/127.0.0.1".equals(_points.get(0).toString()) && "/10.0.0.2".equals(_points.get(1).toString()) && "/10.0.0.3".equals(_points.get(2).toString())); assertTrue("Incorrectly serialized/deserialized consistency levels for Cassandra DataSource", ConsistencyLevel.ONE == _readCons && ConsistencyLevel.QUORUM == _writeCons); assertTrue("Incorrectly serialized/deserialized load balancing policy for Cassandra DataSource", _plc instanceof MyLoadBalancingPolicy); }
public static Cluster getCluster(String[] hosts, Configuration conf, int port) { Optional<AuthProvider> authProvider = getAuthProvider(conf); Optional<SSLOptions> sslOptions = getSSLOptions(conf); Optional<Integer> protocolVersion = getProtocolVersion(conf); LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(hosts); SocketOptions socketOptions = getReadSocketOptions(conf); QueryOptions queryOptions = getReadQueryOptions(conf); PoolingOptions poolingOptions = getReadPoolingOptions(conf); Cluster.Builder builder = Cluster.builder() .addContactPoints(hosts) .withPort(port) .withCompression(ProtocolOptions.Compression.NONE); if (authProvider.isPresent()) builder.withAuthProvider(authProvider.get()); if (sslOptions.isPresent()) builder.withSSL(sslOptions.get()); if (protocolVersion.isPresent()) { builder.withProtocolVersion(ProtocolVersion.fromInt(protocolVersion.get())); } builder.withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withQueryOptions(queryOptions) .withPoolingOptions(poolingOptions); return builder.build(); }
@Override public LoadBalancingPolicy build() { ErrorAwarePolicy.Builder builder = ErrorAwarePolicy.builder(subPolicy.build()); if (maxErrorsPerMinute != null) { builder.withMaxErrorsPerMinute(maxErrorsPerMinute); } if (retryPeriod != null) { builder.withRetryPeriod(retryPeriod.getQuantity(), retryPeriod.getUnit()); } return builder.build(); }
@Test public void buildsPolicyWithNoParams() throws Exception { final DCAwareRoundRobinPolicyFactory factory = new DCAwareRoundRobinPolicyFactory(); final LoadBalancingPolicy policy = factory.build(); assertThat(policy).isExactlyInstanceOf(DCAwareRoundRobinPolicy.class); }
@Test public void buildsPolicyWithAllParams() throws Exception { final DCAwareRoundRobinPolicyFactory factory = new DCAwareRoundRobinPolicyFactory(); factory.setLocalDC("dc1"); factory.setUsedHostsPerRemoteDC(1); factory.setAllowRemoteDCsForLocalConsistencyLevel(true); final LoadBalancingPolicy policy = factory.build(); assertThat(policy).isExactlyInstanceOf(DCAwareRoundRobinPolicy.class); }
@Test public void buildsPolicy() throws Exception { final RoundRobinPolicyFactory factory = new RoundRobinPolicyFactory(); final LoadBalancingPolicy policy = factory.build(); assertThat(policy).isExactlyInstanceOf(RoundRobinPolicy.class); }
public static Cluster getInputCluster(String[] hosts, Configuration conf) { int port = getInputNativePort(conf); Optional<AuthProvider> authProvider = getAuthProvider(conf); Optional<SSLOptions> sslOptions = getSSLOptions(conf); LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(conf, hosts); SocketOptions socketOptions = getReadSocketOptions(conf); QueryOptions queryOptions = getReadQueryOptions(conf); PoolingOptions poolingOptions = getReadPoolingOptions(conf); Cluster.Builder builder = Cluster.builder() .addContactPoints(hosts) .withPort(port) .withCompression(ProtocolOptions.Compression.NONE); if (authProvider.isPresent()) builder.withAuthProvider(authProvider.get()); if (sslOptions.isPresent()) builder.withSSL(sslOptions.get()); builder.withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withQueryOptions(queryOptions) .withPoolingOptions(poolingOptions); return builder.build(); }
public static synchronized Session createSession(String sessionKey, Set<InetAddress> host, String keyspace, String username, String password, LoadBalancingPolicy loadBalancingPolicy) { instance = getInstance(); Session session = instance.sessions.get(sessionKey); if (session == null) { Cluster.Builder cb = Cluster.builder() .addContactPoints(host) .withReconnectionPolicy(new ConstantReconnectionPolicy(10000)) ; if (loadBalancingPolicy != null ) { cb = cb.withLoadBalancingPolicy(loadBalancingPolicy); } if ( username != null && ! username.isEmpty()) { cb = cb.withCredentials(username, password); } Cluster cluster = cb.build(); if (keyspace != null && !keyspace.isEmpty()) session = cluster.connect(keyspace); else session = cluster.connect(); instance.sessions.put(sessionKey, session); } return session; }
public CqlSession(final String nodes, final int port, final String keyspace, final SocketOptions socketOptions, final RetryPolicy retryPolicy, final QueryOptions queryOptions, final LoadBalancingPolicy loadBalancingPolicy, final int maxConnectionsPerHost, final MetricFactory metricFactory) { // this is temp. to reuse current hosts properties: final Iterable<String> nodesIter = Splitter.on(",").split(nodes); final String[] nodesArr = Iterables.toArray( StreamSupport.stream(nodesIter.spliterator(), false).map(input -> { if (input == null) return null; final int idx = input.lastIndexOf(":"); return input.substring(0, idx); }).collect(Collectors.toList()), String.class); /*PoolingOptions poolingOptions = new PoolingOptions(); poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnectionsPerHost); poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnectionsPerHost);*/ final Cluster cluster = Cluster.builder(). withPort(port). withSocketOptions(socketOptions). withQueryOptions(queryOptions). withLoadBalancingPolicy(loadBalancingPolicy). // withPoolingOptions(poolingOptions). addContactPoints(nodesArr).build(); //cluster.init(); this.session = cluster.connect(keyspace); this.retryPolicy = Preconditions.checkNotNull(retryPolicy); this.metricFactory = Preconditions.checkNotNull(metricFactory); }
public static Cluster getInputCluster(String host, Configuration conf) { int port = getInputNativePort(conf); Optional<AuthProvider> authProvider = getAuthProvider(conf); Optional<SSLOptions> sslOptions = getSSLOptions(conf); LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(conf, host); SocketOptions socketOptions = getReadSocketOptions(conf); QueryOptions queryOptions = getReadQueryOptions(conf); PoolingOptions poolingOptions = getReadPoolingOptions(conf); Cluster.Builder builder = Cluster.builder() .addContactPoint(host) .withPort(port) .withCompression(ProtocolOptions.Compression.NONE); if (authProvider.isPresent()) builder.withAuthProvider(authProvider.get()); if (sslOptions.isPresent()) builder.withSSL(sslOptions.get()); builder.withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withQueryOptions(queryOptions) .withPoolingOptions(poolingOptions); return builder.build(); }
public static LoadBalancingPolicy getLoadBalancingPolicy() { LoadBalancingPolicy loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy()); return loadBalancingPolicy; }
public Class<? extends LoadBalancingPolicy> getLoadBalancingPolicy() { return this.loadBalancingPolicy; }
public void setLoadBalancingPolicy( Class<? extends LoadBalancingPolicy> loadBalancingPolicy) { this.loadBalancingPolicy = loadBalancingPolicy; }
private static LoadBalancingPolicy getReadLoadBalancingPolicy(Configuration conf, final String[] stickHosts) { return new LimitedLocalNodeFirstLocalBalancingPolicy(stickHosts); }
/** * Sets load balancing policy. * * @param plc Load balancing policy. */ public void setLoadBalancingPolicy(LoadBalancingPolicy plc) { loadBalancingPlc = plc; invalidate(); }
private static LoadBalancingPolicy getReadLoadBalancingPolicy(final String[] stickHosts) { return new LimitedLocalNodeFirstLocalBalancingPolicy(stickHosts); }
@Override public LoadBalancingPolicy build() { return new WhiteListPolicy(subPolicy.build(), whiteList); }
@Override public LoadBalancingPolicy build() { return new RoundRobinPolicy(); }
@Override public LoadBalancingPolicy build() { return (shuffleReplicas == null) ? new TokenAwarePolicy(subPolicy.build()) : new TokenAwarePolicy(subPolicy.build(), shuffleReplicas); }
/** * @return the loadBalancingPolicy */ public LoadBalancingPolicy getLoadBalancingPolicy() { return loadBalancingPolicy; }
public LoadBalancingPolicy getLoadBalancingPolicy() { return loadBalancingPolicy; }
public void setLoadBalancingPolicy(LoadBalancingPolicy loadBalancingPolicy) { this.loadBalancingPolicy = loadBalancingPolicy; }