mirror of
https://github.com/tiennm99/zfoo.git
synced 2026-10-15 04:19:02 +00:00
perf[protocol]: 优化了clazz和protocol的映射
This commit is contained in:
1 parent
03c02a69c3
commit
55d7139f93
2 files changed
+15
-10
No files matched your search
@@ -30,6 +30,7 @@ import java.util.*;
|
||||
public class ProtocolManager {
|
||||
|
||||
public static final String PROTOCOL_ID = "PROTOCOL_ID";
|
||||
public static final String PROTOCOL_METHOD = "protocolId";
|
||||
public static final short MAX_PROTOCOL_NUM = Short.MAX_VALUE;
|
||||
public static final byte MAX_MODULE_NUM = Byte.MAX_VALUE;
|
||||
|
||||
@@ -46,7 +47,7 @@ public class ProtocolManager {
|
||||
* key:协议class
|
||||
* value:protocolId
|
||||
*/
|
||||
private static final Map<Class<?>, Short> protocolIdMap = new HashMap<>();
|
||||
public static final Map<Class<?>, Short> protocolIdMap = new HashMap<>();
|
||||
|
||||
static {
|
||||
// 初始化默认协议模块
|
||||
@@ -109,16 +110,9 @@ public class ProtocolManager {
|
||||
|
||||
public static short protocolId(Class<?> clazz) {
|
||||
var protocolId = protocolIdMap.get(clazz);
|
||||
if (protocolId == null) {
|
||||
protocolId = ProtocolAnalysis.getProtocolIdByClass(clazz);
|
||||
// 使用懒加载的方式,主要是想节省一点空间,实际运行只有IPacket没有重写protocolId的Response和Answer才会放进去
|
||||
synchronized (protocolIdMap) {
|
||||
protocolIdMap.put(clazz, protocolId);
|
||||
}
|
||||
}
|
||||
return protocolId;
|
||||
}
|
||||
|
||||
|
||||
public static void initProtocol(Set<Class<?>> protocolClassSet) {
|
||||
ProtocolAnalysis.analyze(protocolClassSet, GenerateOperation.NO_OPERATION);
|
||||
}
|
||||
|
||||
@@ -489,12 +489,23 @@ public class ProtocolAnalysis {
|
||||
IPacket packet = (IPacket) constructor.newInstance();
|
||||
var protocolId = (short) protocolIdField.get(null);
|
||||
// 验证protocol()方法的返回是否和PROTOCOL_ID相等
|
||||
AssertionUtils.isTrue(packet.protocolId() == protocolId, "[class:{}]的protocolId返回的值和协议号的静态变量[{}]不相等", clazz.getCanonicalName(), PROTOCOL_ID);
|
||||
Method protocolMethod;
|
||||
try {
|
||||
protocolMethod = clazz.getDeclaredMethod(PROTOCOL_METHOD);
|
||||
} catch (NoSuchMethodException e) {
|
||||
protocolMethod = null;
|
||||
}
|
||||
if (protocolMethod != null) {
|
||||
var methodReturnId = (short) protocolMethod.invoke(packet);
|
||||
AssertionUtils.isTrue(methodReturnId == protocolId, "[class:{}]的protocolId返回的值和协议号的静态变量[{}]不相等", clazz.getCanonicalName(), PROTOCOL_ID);
|
||||
}
|
||||
|
||||
var previous = protocolClassMap.put(protocolId, clazz);
|
||||
if (previous != null) {
|
||||
throw new RunException("[{}][{}]协议号[protocolId:{}]重复", clazz.getCanonicalName(), previous.getCanonicalName(), protocolId);
|
||||
}
|
||||
//存储class和protocolId的映射
|
||||
protocolIdMap.put(clazz, protocolId);
|
||||
}
|
||||
|
||||
private static void checkSubProtocol(Class<?> clazz, short id, Class<?> subClass) {
|
||||
|
||||
Reference in new issue
Block a user