当前位置:网站首页>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

边栏推荐
- How navicate modifies the database name
- Source code analysis of scripy spider
- mmo及时战斗游戏中的场景线程分配
- Overcome the "fear of looking at teeth", and we use technology to change the industry
- Stories of Party members | Li qingai uses cartoons to drive farmers to increase income and become rich
- Rand function generates pseudo-random numbers
- Return and job management of saltstack
- Token verification program index.php when configuring wechat official account server
- [C language] function
- 5. Difference between break and continue (easy to understand version)
猜你喜欢

Prometheus deployment

9. Pointer of C language (5) how many bytes does the pointer variable occupy

3、 Are formal and actual parameters in a programming language variables?
![[C language] step jumping problem [recursion]](/img/0c/32870484e89b494e41068f7c38b08e.png)
[C language] step jumping problem [recursion]

English Translation Spanish - batch English Translation Spanish tools free of charge

认识中小型局域网WLAN

Circular linked list OJ question

Article translation software - batch free translation software supports major translation interfaces

NetCoreAPI操作Excel表格

Rand function generates pseudo-random numbers
随机推荐
Leetcode day3 find duplicate email addresses
Leetcode Day1 score ranking
Idea properties file display \u solution of not displaying Chinese
利用STM32的HAL库驱动1.54寸 TFT屏(240*240 ST7789V)
9. Pointer of C language (2) wild pointer, what is wild pointer, and the disadvantages of wild pointer
C+ + core programming
河北邯郸:拓展基层就业空间 助力高校毕业生就业
Implementation of strstr in C language
6. Functions of C language, why functions are needed, how functions are defined, and the classification of functions
Design of air combat game based on qtgui image interface
[C language] print pattern summary
克服“看牙恐惧”,我们用技术改变行业
云计算笔记part.2——应用管理
Netcoreapi operation excel table
[C language] simulation implementation of strlen (recursive and non recursive)
JVM(二十四) -- 性能监控与调优(五) -- 分析GC日志
数字图像理论知识(一)(个人浅析)
[C language] header file of complex number four operations and complex number operations
[C language] guessing numbers game [function]
党员故事|李青艾用漫画带动农民增收致富