首页 > 解决方案 > 如何在 SpringBoot 中获取 Rsocket 连接的远程 IP 地址

问题描述

我正在尝试获取连接到 RSocket+SpringBoot 网络服务器的浏览器的远程 IP。连接是基于 WebSocket 的 RSocket。

网络服务器是 Java-8,SpringBoot-2,使用 RSocket over WebSocket 并将 RequestStreams 发送到浏览器。我将 SpringBoot 自动配置用于 RSocket 设置,因此服务器端的代码非常少 - 见下文。

@Headers and MessageHeader在下面的代码中只是为了看看他们是否有任何可能导致远程 IP 的东西,没有其他原因他们在那里。

我在网上搜索了一个答案 - http 很多,websockets 有一些, RSocket为零。这 - https://github.com/rsocket/rsocket-java/issues/735 - 看起来很有希望,但无法处理 DuplexConnection,所以那里没有雪茄。

有任何想法吗 ?谢谢 !

应用程序.yml:

spring.rsocket.server:
  mapping-path: /rsocket-test
  transport: websocket

server.port: 8080

测试控制器.java

 /**
     * TODO: get the remote IP address and log.
     * Options:
     * 1. @see <a href="https://github.com/rsocket/rsocket-java/issues/735">Ability to intercept requests and access channel information such as remote address</a>.
     * 2. Inject IP in header by nginx. See if it shows up in the @Headers param here.
     * 3. Browser gets its public IP and adds it to the request object. Doable, but lame
     * 4. (Unlikely) Find a way to access thru this chain of private members: headers.req.rsocket().source.connection.source.connection.connection.channel.remoteAddress
     */
    @MessageMapping("subscribe-topic")
    public Flux<StreamingEvent> subscribeToEventStream(
                @Headers Map<String,Object> hdrs,
                MessageHeaders mh,
                testRequest request) {
        return testService.subscribeTopic(request.getRequestId(), request.getTopic());
    }

标签: javaspring-bootspring-webfluxrsocket

解决方案


客户的IP地址在DuplexConnection课堂上可用。您可以RSocketServer像这样添加拦截器:

@Bean
public RSocketServerCustomizer ipCustomizer() {
    return rSocketServer -> rSocketServer.interceptors(registry -> registry.forConnection(new ConnectionInterceptor()));
}

哪里ConnectionInterceptor是:

static class ConnectionInterceptor implements DuplexConnectionInterceptor {
    @Override
    public DuplexConnection apply(Type type, DuplexConnection duplexConnection) {
        SocketAddress socketAddress = duplexConnection.remoteAddress();
        if (socketAddress instanceof InetSocketAddress) {
            InetSocketAddress iso = (InetSocketAddress) socketAddress;
            // Here is the ip: iso.getHostString()
        }
        return duplexConnection;
    }
}


推荐阅读