'How to intercept websocket messages with spring cloud gateway

I'm running cloud gateway service in front of chat service which handles websocket connection. Do we have some convenient way to log interaction which happens between socket client & chat service on gateway side?

I've noticed that cloud gateway utilizes org.springframework.cloud.gateway.filter.WebsocketRoutingFilter to proxy websockets but not sure how to join its party & if it right place to go



Solution 1:[1]

At the moment I haven't found a way to attach own interceptors with instruments provided by framework. So I've decided to copy pasted WebsocketRoutingFilter implementation, with @Primary annotation & inject own logic this way.

Original WebsocketRoutingFilter creates instance of ProxyWebSocketHandler internally to handle socket session and there is a method handle which could be augmented.

Also be careful with DataBuffer which represents each message. It'controls the amount of data which had been already read. So I've decided to read messages this way:

private String readBufferedMessage(DataBuffer dataBuffer) {
    DataBuffer slice = dataBuffer.slice(0, dataBuffer.capacity());
    byte[] bytes = new byte[slice.readableByteCount()];
    slice.read(bytes);
    return new String(bytes, StandardCharsets.UTF_8);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Silk0vsky