Jayendra Singh
Jayendra Singh

Reputation: 147

How to make grpc StreamObserver object serializable in Java

I am using gprc bidirectional streaming for chat application in Spring boot and since StreamObserver<T> object is used to send message back from sever to client. So, I want to serialize StreamObserver<T> object and convert it into stream of bytes to store it in redis or some other database. But since, StreamObserver<T> is a interface which doesn't implement or extend serializable. So, I am looking for a solution to how to serialize it since there would be around thousands of user which be using the chat application and storing StreamObserver <T> in some Map<String, StreamObserver<T>> won't be good idea.

Currently, I am storing StreamObserver<T> objects in map. Map<String, StreamObserver<T>> Here, key of map is chat application's user's id and value of is StreamObserver object which contains onNext, onError, onCompleted functions to send message from server to client

// Storing StreamObserver object with user Id
public static Map<String, StreamObserver<Chat.ChatMessageFromServer>> observersMap = new HashMap<String, StreamObserver<Chat.ChatMessageFromServer>>();


 @Override
public StreamObserver<Chat.ChatMessage> chat(final StreamObserver<Chat.ChatMessageFromServer> responseObserver) {

// responseObserver -> Storing it into a map. So, server could send message back to the client

        String user = grpcServerInterceptor.contextKey.get();
        System.out.println("");
        System.out.println("User : " + user);

        if (observersMap.get(user) == null) {

            System.out.println("New User : " + user);
            System.out.println("Adding User to observers map");
            System.out.println("");

            observersMap.put(user, responseObserver);
        } else {

            System.out.println("This User already exists in observersMap : " + user);
            System.out.println("By the way, Updating it");

            observersMap.put(user, responseObserver);
        }


  // This function sends message to client from Server
  public void sendMessageFromServerToClient(String user, String message) {

// Fetching StreamObserver from observersMap as defined above
 observersMap.get(user).onNext(Chat.ChatMessageFromServer.newBuilder().setMessage(Chat.ChatMessage.newBuilder().setTo(user).setFrom("Server").setMessage(message)).build());

            System.out.println("Pushed message to user : " + user);
            System.out.println("");

}


Upvotes: 1

Views: 1577

Answers (1)

Eric Anderson
Eric Anderson

Reputation: 26464

StreamObserver corresponds to a stream on a real TCP connection. That resource can't be transferred to a DB. There's no way to serialize it to a DB to reduce memory usage.

Upvotes: 0

Related Questions