java - 如何在 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());
}
解决方案
客户的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;
}
}
推荐阅读
- javascript - Next.js 纱线构建因 plotly.js 失败(发生构建错误 ReferenceError: self is not defined)
- node.js - 了解异步 javascript 方法的参数
- sql-server - 如何在 TOAD for SQL Server 上使用绑定变量创建表
- python - 是否可以使用 Pulumi 创建 Azure 服务主体?
- gradle - 如何从不同的工作目录中查找 gradle 子项目任务
- javascript - 有没有其他方法可以一次声明 addEventListener 并在不重新声明的情况下使用它?
- python - 将熊猫数据框转换为所需的选择字典
- ruby - Ruby Watir 表单下拉未找到
- python - 如何摆脱情节线图中的潦草线条?
- arrays - Ansible playbook 从 dict 获取值