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地址,然后在服務提供方獲取。
服務提供方代碼 (YwcxServiceImpl):
@Slf4j @HsfProvider(serviceInterface = YwcxService.class, serviceVersion = "1.0.0") public class YwcxServiceImpl implements YwcxService { @Override public String inster(List<YwcxQuery> 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的邏輯。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END