Skip to content

Instantly share code, notes, and snippets.

@olim7t
Created September 12, 2019 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/4c524ae7554dde21111dfcab8ed9a372 to your computer and use it in GitHub Desktop.
Save olim7t/4c524ae7554dde21111dfcab8ed9a372 to your computer and use it in GitHub Desktop.

For example, let's say you wrote a custom NettyOptions implementation (maybe you have multiple sessions, and want to reuse the event loop groups instead of recreating them every time):

public class CustomNettyOptions implements NettyOptions {
  ...
} 

In the default context, here's how the component is managed:

public class DefaultDriverContext {
  
  // some content omitted for brevity
  
  private final LazyReference<NettyOptions> nettyOptionsRef =
      new LazyReference<>("nettyOptions", this::buildNettyOptions, cycleDetector);

  protected NettyOptions buildNettyOptions() {
    return new DefaultNettyOptions(this);
  }

  @NonNull
  @Override
  public NettyOptions getNettyOptions() {
    return nettyOptionsRef.get();
  }
}

To switch in your implementation, you only need to override the build method:

public class CustomContext extends DefaultDriverContext {

  public CustomContext(DriverConfigLoader configLoader, ProgrammaticArguments programmaticArguments) {
    super(configLoader, programmaticArguments);
  }

  @Override
  protected NettyOptions buildNettyOptions() {
    return new CustomNettyOptions(this);
  }
}

Then you need a way to create a session that uses your custom context. The session builder is extensible as well:

public class CustomBuilder extends SessionBuilder<CustomBuilder, CqlSession> {

  @Override
  protected DriverContext buildContext(
      DriverConfigLoader configLoader, ProgrammaticArguments programmaticArguments) {
    return new CustomContext(configLoader, programmaticArguments);
  }

  @Override
  protected CqlSession wrap(@NonNull CqlSession defaultSession) {
    // Nothing to do here, nothing changes on the session type
    return defaultSession;
  }
}

Finally, you can use your custom builder like the regular CqlSession.builder(), it inherits all the methods:

CqlSession session = new CustomBuilder()
    .addContactPoint(new InetSocketAddress("1.2.3.4", 9042))
    .withLocalDatacenter("datacenter1")
    .build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment