如何确保Azure WCF HTTP中继在本地服务运行时持续可用?
Azure中继保持持续可用的解决方法
现有配置信息
端点配置
<endpoint address="https://xxxx.servicebus.windows.net/brokers" binding="basicHttpRelayBinding" contract="Services.WebServices.IBrokerService" behaviorConfiguration="clients" bindingConfiguration="HttpRelayConfiguration"/>
端点行为配置
<endpointBehaviors> <behavior name="clients"> <transportClientEndpointBehavior> <tokenProvider> <sharedAccessSignature keyName="RootManageSharedAccessKey" key="dsfsdfsdfsdfds"/> </tokenProvider> </transportClientEndpointBehavior> </behavior> </endpointBehaviors>
绑定配置
<basicHttpRelayBinding> <binding name="HttpRelayConfiguration"/> </basicHttpRelayBinding>
问题描述
当前中继运行正常,但一段时间未访问底层WCF服务时,Azure会无法识别该中继,需确保WCF服务运行时中继始终可用。
解决方法
要确保底层WCF服务运行时Azure中继始终可用,最简单的方式是保持中继连接有持续的轻量流量,避免因空闲超时被断开,具体操作如下:
- 添加Ping操作到服务契约
在IBrokerService接口中新增一个无业务逻辑的轻量操作,用于触发中继流量:
[ServiceContract] public interface IBrokerService { // 原有服务方法... [OperationContract] void Ping(); }
实现类中空实现即可:
public void Ping() { // 无需业务逻辑,仅用于维持连接活跃 }
- 在服务宿主中添加定时调用
在WCF服务启动时初始化定时器,每隔一段时间(建议设为5分钟,短于Azure中继默认空闲超时)调用本地Ping方法,维持中继连接:
private Timer _keepAliveTimer; protected override void OnStart(string[] args) { // 原有服务启动逻辑... // 设置定时器,每5分钟执行一次保活操作 _keepAliveTimer = new Timer(KeepAliveCallback, null, TimeSpan.Zero, TimeSpan.FromMinutes(5)); } private void KeepAliveCallback(object state) { try { // 创建本地客户端调用Ping方法 var binding = new BasicHttpRelayBinding("HttpRelayConfiguration"); var endpoint = new EndpointAddress("https://xxxx.servicebus.windows.net/brokers"); using (var client = new BrokerServiceClient(binding, endpoint)) { client.Ping(); } } catch (Exception ex) { // 记录异常即可,无需中断服务 // 可根据需求添加日志记录,例如写入系统事件日志 } } protected override void OnStop() { _keepAliveTimer?.Dispose(); // 原有服务停止逻辑... }
- 可选:调整绑定超时参数
可以在basicHttpRelayBinding配置中延长空闲超时相关参数,缓解断开问题,但无法完全替代主动保活:
<basicHttpRelayBinding> <binding name="HttpRelayConfiguration" receiveTimeout="00:30:00" keepAliveInterval="00:05:00"/> </basicHttpRelayBinding>
内容的提问来源于stack exchange,提问作者woggles
相关产品推荐
相关产品推荐

