当前位置:网站首页>Zfoo adds routes similar to mydog
Zfoo adds routes similar to mydog
2022-07-28 20:07:00 【zfoo-framework】
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.net.handler;
import com.zfoo.event.manager.EventBus;
import com.zfoo.net.NetContext;
import com.zfoo.net.consumer.balancer.ConsistentHashConsumerLoadBalancer;
import com.zfoo.net.core.gateway.IGatewayLoadBalancer;
import com.zfoo.net.core.gateway.model.GatewaySessionInactiveEvent;
import com.zfoo.net.packet.common.Heartbeat;
import com.zfoo.net.packet.common.Ping;
import com.zfoo.net.packet.common.Pong;
import com.zfoo.net.packet.model.DecodedPacketInfo;
import com.zfoo.net.router.attachment.GatewayAttachment;
import com.zfoo.net.router.attachment.IAttachment;
import com.zfoo.net.router.attachment.SignalAttachment;
import com.zfoo.net.session.model.AttributeType;
import com.zfoo.net.session.model.Session;
import com.zfoo.net.util.SessionUtils;
import com.zfoo.protocol.IPacket;
import com.zfoo.protocol.ProtocolManager;
import com.zfoo.protocol.registration.IProtocolRegistration;
import com.zfoo.protocol.util.JsonUtils;
import com.zfoo.protocol.util.StringUtils;
import com.zfoo.scheduler.util.TimeUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiFunction;
/**
* @author jaysunxiao
* @version 3.0
*/
@ChannelHandler.Sharable
public class GatewayRouteHandler extends ServerRouteHandler {
private static final Logger logger = LoggerFactory.getLogger(GatewayRouteHandler.class);
private final BiFunction<Session, IPacket, Boolean> packetFilter;
private final BiFunction<Session, IPacket, Integer> routerFunc;
public GatewayRouteHandler(BiFunction<Session, IPacket, Boolean> packetFilter) {
this(packetFilter, null);
}
public GatewayRouteHandler(BiFunction<Session, IPacket, Boolean> packetFilter, BiFunction<Session, IPacket, Integer> routerFunc) {
this.packetFilter = packetFilter;
this.routerFunc = routerFunc;
}
// TODO test
public static final BiFunction<Session, IPacket, Integer> routerFunc1 = (session, packet) -> {
var module = ProtocolManager.moduleByProtocolId(packet.protocolId());
var name = module.getName();
switch (name) {
case "game":
return (Integer) session.getAttribute(AttributeType.UID);
case "guild":
return (Integer) session.getAttribute(AttributeType.CONSUMER);
}
return null;
};
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Requestor's session, It's usually serverSession
var session = SessionUtils.getSession(ctx);
if (session == null) {
return;
}
var decodedPacketInfo = (DecodedPacketInfo) msg;
var packet = decodedPacketInfo.getPacket();
if (packet.protocolId() == Heartbeat.PROTOCOL_ID) {
return;
}
if (packet.protocolId() == Ping.PROTOCOL_ID) {
NetContext.getRouter().send(session, Pong.valueOf(TimeUtils.now()), null);
return;
}
// Filter illegal packages
if (packetFilter != null && packetFilter.apply(session, packet)) {
throw new IllegalArgumentException(StringUtils.format("[session:{}] An illegal packet was sent [{}]"
, SessionUtils.sessionInfo(ctx), JsonUtils.object2String(packet)));
}
var signalAttachment = (SignalAttachment) decodedPacketInfo.getAttachment();
// Wrap the client information into a GatewayAttachment, Therefore, through this gateway add-on package, players can get uid、sid Information like that
var gatewayAttachment = new GatewayAttachment(session, signalAttachment);
// Gateway is preferred IGatewayLoadBalancer As consistency hash Calculation parameters of , Then we can use the client session Make parameters
// Example : Take chat services for example , Players know which group they are in groupId in , When sending messages to this group , Will be in Packet Take this with you groupId As consistency hash That's all right. .
if (packet instanceof IGatewayLoadBalancer) {
var loadBalancerConsistentHashObject = ((IGatewayLoadBalancer) packet).loadBalancerConsistentHashObject();
gatewayAttachment.useExecutorConsistentHash(loadBalancerConsistentHashObject);
forwardingPacket(packet, gatewayAttachment, loadBalancerConsistentHashObject);
return;
} else {
// For the current business module , whether session There is routing information bound on , So as to forward directly to provider
if (routerFunc != null) {
Integer hashId = routerFunc.apply(session, packet);
if (hashId != null) {
forwardingPacket(packet, gatewayAttachment, hashId);
return;
}
}
// Use user's uid Do consistency hash
var uid = (Long) session.getAttribute(AttributeType.UID);
if (uid != null) {
forwardingPacket(packet, gatewayAttachment, uid);
return;
}
}
// Reuse session Of sid Do consistency hash, Because every time the client connects sid Will change , Therefore, if the client reconnects, it may be routed to other servers
// If there are special needs , Consider rewriting the forwarding strategy of the gateway
// Take the player's sid Do consistency hash, That must be : Once reconnected sid Will change all the time . therefore : Generally, unless you create it yourself TcpClient, Otherwise logic should not come here . But go up through UID Do consistency hash
var sid = session.getSid();
forwardingPacket(packet, gatewayAttachment, sid);
}
/**
* Forward the packets received by the gateway to Provider
*/
private void forwardingPacket(IPacket packet, IAttachment attachment, Object argument) {
try {
var consumerSession = ConsistentHashConsumerLoadBalancer.getInstance().loadBalancer(packet, argument);
NetContext.getRouter().send(consumerSession, packet, attachment);
} catch (Exception e) {
logger.error(" An exception occurred in the gateway ", e);
} catch (Throwable t) {
logger.error(" Gateway error ", t);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
var session = SessionUtils.getSession(ctx);
if (session == null) {
return;
}
var sid = session.getSid();
var uid = (Long) session.getAttribute(AttributeType.UID);
// The client connected to the gateway is disconnected
EventBus.asyncSubmit(GatewaySessionInactiveEvent.valueOf(sid, uid == null ? 0 : uid.longValue()));
super.channelInactive(ctx);
}
}
zfoo Of gateway Equivalent to mydog Of Connector The server

边栏推荐
- MySQL命令语句(个人总结)
- WPF -- implement websocket server
- [C language] Hanoi Tower problem [recursion]
- JS batch add event listening onclick this event delegate target currenttarget onmouseenter OnMouseOver
- English Translation Spanish - batch English Translation Spanish tools free of charge
- Function fitting based on MATLAB
- Implementation of memcpy in C language
- Leetcode Day2 consecutive numbers
- Common modules of saltstack
- 9. Pointer of C language (5) how many bytes does the pointer variable occupy
猜你喜欢

9. Pointer of C language (4) pointer and one-dimensional array, pointer operation

English translation Italian - batch English translation Italian tools free of charge
![[C language] summary of methods for solving the greatest common divisor](/img/38/3a099948ebf51fd0da3076f71f9dad.png)
[C language] summary of methods for solving the greatest common divisor

Handan, Hebei: expand grassroots employment space and help college graduates obtain employment

数字滤波器设计——Matlab

Longest Palindromic Substring

Digital filter design matlab

Use Hal Library of STM32 to drive 1.54 inch TFT screen (240*240 st7789v)

Know small and medium LAN WLAN

Servlet learning notes
随机推荐
JS batch add event listening onclick this event delegate target currenttarget onmouseenter OnMouseOver
Leetcode Day2 consecutive numbers
Getting started with enterprise distributed crawler framework
河北:稳粮扩豆助力粮油生产提质增效
2. Floating point number, the difference between float and double in C language and how to choose them
Leetcode Day1 score ranking
克服“看牙恐惧”,我们用技术改变行业
Cdga | how can the industrial Internet industry do a good job in data governance?
中国能否在元宇宙的未来发展中取得突破,占领高地?
“中国网事·感动2022”二季度网络感动人物评选结果揭晓
9. Pointer of C language (2) wild pointer, what is wild pointer, and the disadvantages of wild pointer
Read how to deploy highly available k3s with external database
Find the memory occupied by the structure
【NPP安装插件】
Basic usage of docker
[网络]跨区域网络的通信学习路由表的工作原理
Deploy ZABBIX automatically with saltstack
Const pointer of C language and parameter passing of main function
Overcome the "fear of looking at teeth", and we use technology to change the industry
认识中小型局域网WLAN