Skip to content

Instantly share code, notes, and snippets.

@olim7t
Created Sep 12, 2019
Embed
What would you like to do?

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