gRPC | Java | How can I reconnect the stream to the server? [Solved]

519 Views Asked by At

Thank you all for your answers. I got it working now!!

I just remade everything and I'm catching Connection losses, which I then use to start a new Thread which uses Thread.sleep(15000) to wait 15 Seconds and then call my GrpcEvent again (which is also called at the start). I'm creating a channel at the beginning of the app runtime and if the stream ends, it just uses the channel from the beginning to start a new stream.

Since the code is a bit too big for here, I can send it to everyone who dms me on twitter ^^ (It's linked to my Stackoverflow profile)




I want to be able to check if the gRPC Server is reachable again and start a new stream connection to the server.

My Code for java is:

public class GrpcEvent {

    public GrpcEvent(@NotNull VCore plugin) {

        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
                .usePlaintext()
                .keepAliveTime(30, TimeUnit.SECONDS)
                .keepAliveTimeout(5, TimeUnit.SECONDS)
                .build();

        GeneralGrpc.GeneralStub nonBlockingStub = GeneralGrpc.newStub(channel);

        nonBlockingStub.connectClient(GeneralProto.ClientMeta.newBuilder()
                        .setGroup("proxy")
                        .setName("proxy-" + createId())
                        .setIp(plugin.server.getBoundAddress().getHostName())
                        .setPort(plugin.server.getBoundAddress().getPort())
                        .build(),
                new GrpcCommandHandler(plugin));


    }

    private @NotNull String createId() {
        UUID uuid = UUID.randomUUID();
        String[] parts = uuid.toString().split("-");

        return String.join("-", parts[0], parts[1]);
    }
}

I tried searching on google for days and even tried (I know it's not recommended and most of the code doesn't really work) ChatGPT.

The result: The Java application didn't recognize the connection loss and couldn't reconnect.

1

There are 1 best solutions below

0
Citrullin On

That sounds to me like something you would like to do with a framework/library any way. You can implement it by yourself, but it's really not worth the struggle and may lead to spaghetti code any way. Akka has a gRPC integration, so I would have a look into it. It has a lot of features that solves what you describe here. Flink would be even more advanced than Akka in the sense you have checkpoints etc. That may help here in case something bigger fails.