com.neko233.virtualRouter.server.strategy.impl.ServerHeartBeatStrategy.kt Maven / Gradle / Ivy
package com.neko233.virtualRouter.server.strategy.impl
import com.neko233.virtualRouter.core.RouteMessage
import com.neko233.virtualRouter.core.RouterSessionManager
import com.neko233.virtualRouter.core.RpcServerInfo
import com.neko233.virtualRouter.core.businessHandler.HandleRouteStrategy
import com.neko233.virtualRouter.core.constant.RouteMessageTypeEnum
import com.neko233.virtualRouter.core.utils.JsonUtils
import com.neko233.virtualRouter.server.constant.NettyAttrConstant
import io.netty.channel.Channel
/**
* 注册
*/
class ServerHeartBeatStrategy : HandleRouteStrategy {
override fun type(): RouteMessageTypeEnum {
return RouteMessageTypeEnum.HeartBeat
}
override fun handleReq(
routeMessage: RouteMessage,
channel: Channel,
) {
val fromRouteId = routeMessage.fromRouteId
val json = routeMessage.data!!
val rpcServerInfo = JsonUtils.deserialize(json, RpcServerInfo::class.java)!!
setNettyAttrForRouteId(channel, fromRouteId)
// 添加 session
val routerSession = RouterSessionManager.Instance.upsertSession(
fromRouteId,
channel,
rpcServerInfo
)
val routeInfoList = RouterSessionManager.Instance.getAllRouteNodeList()
// 发送给目标 session
val msg = routeMessage.apply {
data = JsonUtils.serialize(routeInfoList)
}
val outputBytes = msg.encode()
routerSession.writeAndFlush(outputBytes)
}
private fun setNettyAttrForRouteId(
channel: Channel,
fromRouteId: String?,
) {
val attr = channel.attr(NettyAttrConstant.NETTY_ATTR_ROUTE_ID)
attr.set(fromRouteId)
}
}