Java developing
Generating gRPC code stubs
To see a guide how the Java code is compiled from the proto files see the gRPC setup project dependencies. To update the protobuf files being used, add the new files to the top level proto directory and then run make proto from the root of the project.
More notes on the asynchronous use of the gRPC API
Up to this point, we were using the blocking version of the generated stub. We can also interact with the Stargate API using the async version of the stub. To do so, we need to pass the StreamObserver that will be called asynchronously when the results are available.
Every StreamObserver needs to implement 3 methods: onNext()
, onError()
and onComplete()
.
For example:
StreamObserver<QueryOuterClass.Response> streamObserver = new StreamObserver<QueryOuterClass.Response>() {
@Override
public void onNext(QueryOuterClass.Response response) {
try {
System.out.println("response:" + response.getResultSet());
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
}
@Override
public void onError(Throwable throwable) {
System.out.println("Error: " + throwable);
}
@Override
public void onCompleted() {
// close resources, finish processing
System.out.println("completed");
}
};
Please note that this is a very simplified version only for demonstration purposes and should not be used on production.
Once we have the Observer, we can pass it to the executeQuery
method on the async stub:
stub.executeQuery(QueryOuterClass.Query
.newBuilder()
.setCql("SELECT k, v FROM ks.test")
.build(), streamObserver);
This query will return immediately because it is non-blocking.
If your program (or test) is progressing to the end, you may not be able to see the results.
Your program may exit before the data arrives.
After some time, when the data arrives, the streamObserver
will be called.
The output of our program will look like this:
response:columns {
type {
basic: VARCHAR
}
name: "k"
}
columns {
type {
basic: INT
}
name: "v"
}
rows {
values {
string: "a"
}
values {
int: 1
}
}
completed
Please note, that at the end we have a completed
emitted.
This is called by the onCompleted
method.