跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

在HSF框架中如何解决RpcContext.getContext().getRemoteAddress()返回空的问题?

HSF框架下获取调用方IP地址的有效方法 在使用HSF框架提供服务时,直接使用
RpcContext.getContext().getRemoteAddress()
获取调用方IP地址经常返回空值。这是因为HSF框架在服务提供方默认不记录调用方IP。本文将提供解决此问题的有效方案。 问题分析: 提供的代码片段展示了服务提供方尝试使用
RpcContext.getContext().getRemoteAddress()
获取IP,但结果为空。
RpcContext
类来自
edas-sdk-1.8.3.jar
,其
getRemoteAddress()
方法返回
InetSocketAddress
对象,在服务提供方通常未被自动填充。 解决方案:通过自定义Attachment传递IP地址 最可靠的方案是通过HSF框架的
Attachment
机制在调用方设置IP地址,然后在服务提供方获取。 腾讯qq登陆php类 腾讯qq登陆php类 下载 服务提供方代码 (YwcxServiceImpl):
@Slf4j @HsfProvider(serviceInterface = YwcxService.class, serviceVersion = "1.0.0") public class YwcxServiceImpl implements YwcxService { @Override public String inster(List ywcxquerylist) { String remoteIp = RpcContext.getContext().getAttachment("remoteIp"); log.info("Remote IP: {}", remoteIp); // 业务逻辑... return "success"; // or other return value } }
服务调用方代码 (服务B):
@Scheduled(cron = "${task.cron.runTaskHuayu}") public String dsrw() { // 获取调用方IP地址 (需要根据实际情况替换获取IP的方法) String callerIp = getCallerIpAddress(); RpcContext.getContext().setAttachment("remoteIp", callerIp); return ywcxService.inster(fqxcsqquerylist); } // 获取调用方IP地址的方法,需要根据实际环境实现 private String getCallerIpAddress() { // 例如,使用HttpServletRequest获取IP // 或者使用其他方法获取本机IP // 这里需要根据你的具体应用场景来实现 return "127.0.0.1"; // 替换为实际获取IP地址的代码 }
关键改进: 明确使用Attachment: 服务调用方使用
RpcContext.getContext().setAttachment("remoteIp", callerIp);
将调用方IP地址作为Attachment添加到上下文。 获取Attachment: 服务提供方使用
RpcContext.getContext().getAttachment("remoteIp");
从上下文获取附加的IP地址。 获取调用方IP地址的实现:
getCallerIpAddress()
方法需要根据实际应用场景实现,例如,在Web应用中,可以使用
HttpServletRequest
对象获取客户端IP地址;在其他环境中,可能需要使用不同的方法获取本机IP地址。 通过这种方法,即使
RpcContext.getContext().getRemoteAddress()
返回空,也能可靠地获取调用方的IP地址。 记住替换
getCallerIpAddress()
方法中的占位符代码为实际获取IP的逻辑。

相关文章