初步提交

back_recharge
zhangshanxue 2020-11-27 15:26:55 +08:00
parent b9fd7bfdf7
commit b27f4e489c
62 changed files with 11887 additions and 46 deletions

View File

@ -10,4 +10,5 @@ public class ServiceKey {
public static final String GM_CANCLE_SCENE = "GM_CANCLE_SCENE";
public static final String RPC_GLOBAL = "RPC_GGLOBAL";
public static final String RPC_WORLD = "RPC_WORLD";
public static final String RPC_GS= "RPC_GS";
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: gtwprotos/WorldProto.proto
// source: wtgprotos/WorldProto.proto
package rpc.world;
@ -5864,7 +5864,7 @@ public final class WorldProto {
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032gtwprotos/WorldProto.proto\022\trpc.world\032" +
"\n\032wtgprotos/WorldProto.proto\022\trpc.world\032" +
"\021CommonProto.proto\"\032\n\030GetWorldArenaInfoR" +
"equest\"h\n\031GetWorldArenaInfoResponse\022+\n\ta" +
"renaInfo\030\001 \001(\0132\030.rpc.protocols.ArenaInfo" +

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerInvalidOperException extends TException implements org.apache.thrift.TBase<InnerInvalidOperException, InnerInvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InnerInvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerInvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerResult implements org.apache.thrift.TBase<InnerResult, InnerResult._Fields>, java.io.Serializable, Cloneable, Comparable<InnerResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCgTGRequestIFace {
public interface Iface {

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerInvalidOperException extends TException implements org.apache.thrift.TBase<InnerInvalidOperException, InnerInvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InnerInvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerInvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerResult implements org.apache.thrift.TBase<InnerResult, InnerResult._Fields>, java.io.Serializable, Cloneable, Comparable<InnerResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCgTGRequestIFace {
public interface Iface {

View File

@ -66,7 +66,8 @@ public class GameLogicService implements IService {
CoreSettings coreSettings = ConfigurableApplicationContextManager.getBean(CoreSettings.class);
String ip = coreSettings.getIp();
int port = coreSettings.getGmport();
String rpcUrl = ip + ":" + port;
int worldport = coreSettings.getWorldport();
String rpcUrl = ip + ":" + port+ ":" + worldport;
RedisUtil.getInstence().set(RedisKey.LOGIC_SERVER_INFO+RedisKey.Delimiter_colon+GameApplication.serverId,gson.toJson(rpcUrl));
}

View File

@ -12,6 +12,7 @@ public class CoreSettings {
private String ip;
private int port;
private int worldport;
private int gmport;
private int area;
private int id;
@ -27,6 +28,14 @@ public class CoreSettings {
this.ip = ip;
}
public int getWorldport() {
return worldport;
}
public void setWorldport(int worldport) {
this.worldport = worldport;
}
public int getWeight() {
return weight;
}

View File

@ -178,6 +178,7 @@ public class GlobleSystemLogic implements IEventHandler {
}
public static int getGloableWorldLeveCache() {
@ -186,7 +187,7 @@ public class GlobleSystemLogic implements IEventHandler {
private static void setGloableWorldLeveCache(int gloableWorldLeveCache) {
GLOABLE_WORLD_LEVE_CACHE = gloableWorldLeveCache;
RedisUtil.getInstence().putMapEntry(RedisKey.USER_SERVER_INFO,"",String.valueOf(GameApplication.areaId),gloableWorldLeveCache);
RedisUtil.getInstence().putMapEntry(RedisKey.SERVER_WORLDLEVE_INFO,"",String.valueOf(GameApplication.areaId),gloableWorldLeveCache);
}
public static int getGloableWorldLeveCacheLine() {

View File

@ -24,9 +24,6 @@ import com.ljsd.jieling.logic.mission.event.MissionEventDistributor;
import com.ljsd.jieling.logic.player.PlayerLogic;
import com.ljsd.jieling.logic.store.StoreLogic;
import com.ljsd.jieling.network.session.ISession;
import rpc.protocols.CommonProto;
import rpc.protocols.MessageTypeProto;
import rpc.protocols.PlayerInfoProto;
import com.ljsd.jieling.util.InnerMessageUtil;
import com.ljsd.jieling.util.ItemUtil;
import com.ljsd.jieling.util.MessageUtil;
@ -36,6 +33,9 @@ import manager.STableManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ZSetOperations;
import rpc.protocols.CommonProto;
import rpc.protocols.MessageTypeProto;
import rpc.protocols.PlayerInfoProto;
import util.MathUtils;
import util.TimeUtils;

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InvalidOperException extends TException implements org.apache.thrift.TBase<InvalidOperException, InvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCMatchRequestIFace {
public interface Iface {

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCRequestIFace {
public interface Iface {

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RechargeResult implements org.apache.thrift.TBase<RechargeResult, RechargeResult._Fields>, java.io.Serializable, Cloneable, Comparable<RechargeResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RechargeResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class Result implements org.apache.thrift.TBase<Result, Result._Fields>, java.io.Serializable, Cloneable, Comparable<Result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Result");

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerInvalidOperException extends TException implements org.apache.thrift.TBase<InnerInvalidOperException, InnerInvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InnerInvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerInvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerResult implements org.apache.thrift.TBase<InnerResult, InnerResult._Fields>, java.io.Serializable, Cloneable, Comparable<InnerResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCgTwRequestIFace {
public interface Iface {

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerInvalidOperException extends TException implements org.apache.thrift.TBase<InnerInvalidOperException, InnerInvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InnerInvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerInvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerResult implements org.apache.thrift.TBase<InnerResult, InnerResult._Fields>, java.io.Serializable, Cloneable, Comparable<InnerResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCgTGRequestIFace {
public interface Iface {

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InvalidOperException extends TException implements org.apache.thrift.TBase<InvalidOperException, InvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCMatchRequestIFace {
public interface Iface {

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCRequestIFace {
public interface Iface {

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RechargeResult implements org.apache.thrift.TBase<RechargeResult, RechargeResult._Fields>, java.io.Serializable, Cloneable, Comparable<RechargeResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RechargeResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class Result implements org.apache.thrift.TBase<Result, Result._Fields>, java.io.Serializable, Cloneable, Comparable<Result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Result");

View File

@ -21,3 +21,8 @@ service RPCgTwRequestIFace{
}
service RPCwTgRequestIFace{
InnerResult messageRequest(1:i32 uid,2:i32 protpId,3:binary message);
}

View File

@ -0,0 +1,17 @@
package com;
/**
* Description:
* Author: zsx
* CreateDate: 2019/11/6 17:00
*/
public interface IManager {
//manager init
void init() throws Exception;
//manager exit
void exit() throws Exception;
}

View File

@ -1,7 +1,8 @@
package com.world;
package com;
import com.world.config.ConfigurableApplicationContextManager;
import com.world.config.CoreSettings;
import com.world.network.NetManager;
import com.world.redis.RedisUtil;
import com.world.thread.ThreadManager;
import com.world.thrift.idl.pool.RPCServerTask;
@ -16,6 +17,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Description:
*
*
* Author: zsx
* CreateDate: 2020/11/19 11:48
*/
@ -26,7 +29,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
public class WorldServerApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(WorldServerApplication.class);
public static CoreSettings bean;
public static void main(String[] args) {
public static void main(String[] args)throws Exception {
ConfigurableApplicationContextManager.init(args);
@ -40,7 +43,12 @@ public class WorldServerApplication {
}
WorldRpcService.initHandler("com.world.handler",WorldServerApplication.class.getClassLoader());
new RPCServerTask().start();
// new RPCServerTask().start();
//切换netty通信
NetManager.getInstance().init();
RedisUtil.getInstence().init();
bean = ConfigurableApplicationContextManager.getBean(CoreSettings.class);
LOGGER.info("ServerProperties ->{}", bean.toString());

View File

@ -1,6 +1,6 @@
package com.world.config;
import com.world.WorldServerApplication;
import com.WorldServerApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;

View File

@ -0,0 +1,20 @@
package com.world.function;
/**
* Description:
* Author: zsx
* CreateDate: 2020/11/20 11:31
*/
public class ArenaWorldFunction implements FunctionManager {
@Override
public void closeAction ()throws Exception {
// ArenaLogic.getInstance().sendReward(GlobalsDef.ARENA_SEASON_REWARD);
}
@Override
public void startAction(TimeControllerOfFunction timeControllerOfFunction) {
// ArenaLogic.getInstance().updateArenaSeason(timeControllerOfFunction.getTimes());
}
}

View File

@ -0,0 +1,53 @@
package com.world.function;
import rpc.protocols.MessageTypeProto;
import java.util.HashMap;
import java.util.Map;
/**
* 82
*/
public enum FunctionIdEnum {
Arena(82, new ArenaWorldFunction()),
;
private int functionType;
private FunctionManager manager;
private int[] protos;
private static Map<Integer,FunctionIdEnum> functionIdEnumMap = new HashMap<>();
private static Map<Integer,FunctionIdEnum> protoMap = new HashMap<>();
static {
FunctionIdEnum[] values = FunctionIdEnum.values();
for(FunctionIdEnum functionIdEnum : values){
functionIdEnumMap.put(functionIdEnum.getFunctionType(),functionIdEnum);
for(int proto:functionIdEnum.getProtos()){
protoMap.put(proto,functionIdEnum);
}
}
}
FunctionIdEnum(int functionType, FunctionManager manager,int... protos) {
this.manager = manager;
this.functionType = functionType;
this.protos = protos;
}
public int getFunctionType() {
return functionType;
}
public FunctionManager getManager() {
return manager;
}
public int[] getProtos() {
return protos;
}
public static FunctionIdEnum getFunctionIdEnumByProto(int protoId){
return protoMap.get(protoId);
}
public static FunctionIdEnum getFunctionIdEnumByType(int functionType) {
return functionIdEnumMap.get(functionType);
}
}

View File

@ -0,0 +1,14 @@
package com.world.function;
import com.ljsd.jieling.logic.dao.TimeControllerOfFunction;
/**
* @author lvxinran
* @date 2019/11/23
* @discribe
*/
public interface FunctionManager {
void startAction(TimeControllerOfFunction timeControllerOfFunction) throws Exception;
void closeAction() throws Exception;
}

View File

@ -0,0 +1,44 @@
package com.world.function;
public class TimeControllerOfFunction {
private int id;
private int status;
private long startTime;
private long endTime;
private int times; //开了几次
public TimeControllerOfFunction(){}
public TimeControllerOfFunction(int id, int status, long startTime, long endTime) {
this.id = id;
this.status = status;
this.startTime = startTime;
this.endTime = endTime;
}
public int getId() {
return id;
}
public int getStatus() {
return status;
}
public long getStartTime() {
return startTime;
}
public long getEndTime() {
return endTime;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
}

View File

@ -1,12 +1,19 @@
package com.world.handler;
import com.google.protobuf.GeneratedMessage;
import com.world.WorldServerApplication;
import com.WorldServerApplication;
import config.SArenaSetting;
import rpc.global.GlobalProto;
import rpc.net.RpcMessage;
import rpc.net.gtGBaseHandler;
import rpc.protocols.ArenaInfoProto;
import rpc.protocols.CommonProto;
import rpc.world.WorldProto;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Description:
* Author: zsx
@ -18,8 +25,37 @@ public class GetWorldArenaInfoRequestHandler extends gtGBaseHandler<WorldProto.G
public GeneratedMessage processWithProto(RpcMessage rpcMessage, WorldProto.GetWorldArenaInfoRequest proto) throws Exception {
//获取竞技场信息
// int curSeason =ArenaLogic.getInstance().getCurSeason();
// int uid = session.getUid();
// User user = UserManager.getUser(uid);
// ArenaManager arenaManager = user.getArenaManager();
// if(arenaManager.getSeason()!=curSeason){
// arenaManager.resetSeason(curSeason);
// RedisUtil.getInstence().del(RedisKey.ARENA_RRECORD,Integer.toString(uid));
// }
// int score = RedisUtil.getInstence().getZSetScore(RedisKey.ARENA_RANK,Integer.toString(curSeason), Integer.toString(uid)).intValue();
// if(score == -1){
// score = SArenaSetting.getSArenaSetting().getScore();
// }
// if(arenaManager.getFlushNums() == 0){
// List<ArenaEnemy> arenaEnemies = new ArrayList<>();
// Set<Integer> robotIds = ArenaLogic.randomRobot(score, 5);
// ArenaLogic.getInstance().toArenaEnemy(uid,robotIds,arenaEnemies, GlobalsDef.ARENA_ROBOT_TYPE);
// arenaManager.setArenaEnemies(arenaEnemies);
// }
//
// CommonProto.ArenaInfo build = CommonProto.ArenaInfo.newBuilder()
// .setFailNums(arenaManager.getFailNums())
// .setSuccessNums(arenaManager.getSuccessNums())
// .setScore(score)
// .addAllHadTakeBox(arenaManager.getHadTakeReward())
// .addAllArenaEnemys(ArenaLogic.getInstance().getArenaEnemyList(arenaManager.getArenaEnemies()))
// .build();
// ArenaInfoProto.GetArenaInfoResponse getArenaInfoResponse = ArenaInfoProto.GetArenaInfoResponse.newBuilder().setArenaInfo(build).build();
//获取竞技场信息
WorldProto.GetWorldArenaInfoResponse.newBuilder().build();
return GlobalProto.GetWorldServerResponse.newBuilder().setIp(WorldServerApplication.bean.getIp()).setPort(WorldServerApplication.bean.getIp()).setGroup(1).build();
}

View File

@ -0,0 +1,30 @@
package com.world.logic.arean;
public class ArenaEnemy {
private int enemyId;
// 0玩家1机器人
private int enemyType;
// 0未挑战1挑战成功2挑战失败
private int enemyStatus;
public ArenaEnemy(int enemyId, int enemyType, int enemyStatus) {
this.enemyId = enemyId;
this.enemyType = enemyType;
this.enemyStatus = enemyStatus;
}
public int getEnemyId() {
return enemyId;
}
public int getEnemyType() {
return enemyType;
}
public int getEnemyStatus() {
return enemyStatus;
}
}

View File

@ -0,0 +1,548 @@
package com.world.logic.arean;
import com.ljsd.jieling.core.GlobalsDef;
import com.ljsd.jieling.core.VipPrivilegeType;
import com.ljsd.jieling.db.mongo.MongoUtil;
import com.ljsd.jieling.db.redis.RedisKey;
import com.ljsd.jieling.db.redis.RedisUtil;
import com.ljsd.jieling.exception.ErrorCode;
import com.ljsd.jieling.exception.ErrorCodeException;
import com.ljsd.jieling.globals.BIReason;
import com.ljsd.jieling.globals.Global;
import com.ljsd.jieling.handler.map.behavior.BehaviorUtil;
import com.ljsd.jieling.logic.OnlineUserManager;
import com.ljsd.jieling.logic.dao.root.User;
import com.ljsd.jieling.logic.fight.result.FightResult;
import com.ljsd.jieling.logic.hero.HeroLogic;
import com.ljsd.jieling.logic.mail.MailLogic;
import com.ljsd.jieling.logic.mission.GameEvent;
import com.ljsd.jieling.logic.mission.event.MissionEventDistributor;
import com.ljsd.jieling.logic.player.PlayerLogic;
import com.ljsd.jieling.network.session.ISession;
import config.*;
import manager.STableManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ZSetOperations;
import rpc.protocols.ArenaInfoProto;
import rpc.protocols.CommonProto;
import rpc.protocols.FightInfoProto;
import rpc.protocols.MessageTypeProto;
import util.MathUtils;
import util.StringUtil;
import util.TimeUtils;
import java.util.*;
public class ArenaLogic {
private static final Logger LOGGER = LoggerFactory.getLogger(ArenaLogic.class);
private ArenaLogic(){}
public static class Instance {
public final static ArenaLogic instance = new ArenaLogic();
}
public static ArenaLogic getInstance() {
return ArenaLogic.Instance.instance;
}
private int curSeason;
private int viewSeason;
public int getCurSeason() {
return curSeason;
}
public int getViewSeason() {
return viewSeason;
}
public List<CommonProto.ArenaEnemy> getArenaEnemyList(List<ArenaEnemy> arenaEnemies) throws Exception {
List<CommonProto.ArenaEnemy> arenaEnemyList = new ArrayList<>(arenaEnemies.size());
for(ArenaEnemy arenaEnemy : arenaEnemies){
int enemyId = arenaEnemy.getEnemyId();
int enemyType = arenaEnemy.getEnemyType();
arenaEnemyList.add(getArenaEnemy(enemyId,enemyType));
}
return arenaEnemyList;
}
public CommonProto.ArenaEnemy getArenaEnemy( int enemyId ,int enemyType) throws Exception {
if(enemyType == 0){ //机器人
SArenaRobotConfig sArenaRobotConfig = SArenaRobotConfig.getsArenaRobotConfigById(enemyId);
CommonProto.Team teamBuild = CommonProto.Team.newBuilder().addAllHeroTid(sArenaRobotConfig.getHeroList()).build();
CommonProto.ArenaPersonInfo personInfoBuild = CommonProto.ArenaPersonInfo.newBuilder()
.setUid(enemyId)
.setLevel(sArenaRobotConfig.getRobotLevel())
.setName(sArenaRobotConfig.getRobotName())
.setScore(sArenaRobotConfig.getRobotScore())
.setTotalForce(sArenaRobotConfig.getTotalForce())
.build();
return CommonProto.ArenaEnemy.newBuilder()
.setPersonInfo(personInfoBuild)
.setTeam(teamBuild)
.build();
}else{
User user = UserManager.getUser(enemyId);
int totalForce = HeroLogic.getInstance().calTeamTotalForce(user, GlobalsDef.TEAM_ARENA_DEFENSE,false);
List<TeamPosHeroInfo> teamPosHeroInfoList = user.getTeamPosManager().getTeamPosForHero().get(GlobalsDef.TEAM_ARENA_DEFENSE);
Map<String, Hero> heroMap = user.getHeroManager().getHeroMap();
List<Integer> heroTids = new ArrayList<>(teamPosHeroInfoList.size());
for(TeamPosHeroInfo teamPosHeroInfo:teamPosHeroInfoList){
heroTids.add(heroMap.get(teamPosHeroInfo.getHeroId()).getTemplateId());
}
CommonProto.Team teamBuild = CommonProto.Team.newBuilder().addAllHeroTid(heroTids).build();
PlayerManager playerInfoManager = user.getPlayerInfoManager();
int score = RedisUtil.getInstence().getZSetScore(RedisKey.ARENA_RANK, Integer.toString(curSeason), Integer.toString(enemyId)).intValue();
if(score == -1){
score = SArenaSetting.getSArenaSetting().getScore();
}
CommonProto.ArenaPersonInfo personInfoBuild = CommonProto.ArenaPersonInfo.newBuilder()
.setUid(enemyId)
.setLevel(playerInfoManager.getLevel())
.setName(playerInfoManager.getNickName())
.setScore(score)
.setHead(playerInfoManager.getHead())
.setTotalForce(totalForce)
.build();
return CommonProto.ArenaEnemy.newBuilder()
.setPersonInfo(personInfoBuild)
.setTeam(teamBuild)
.build();
}
}
public void setMyArenaEnemys(int uid,User user){
int score = RedisUtil.getInstence().getZSetScore(RedisKey.ARENA_RANK,Integer.toString(curSeason), Integer.toString(uid)).intValue();
if(score == -1){
score = SArenaSetting.getSArenaSetting().getScore();
}
ArenaManager arenaManager = user.getArenaManager();
List<ArenaEnemy> arenaEnemies = new ArrayList<>();
if(curSeason ==1 && arenaManager.getFlushNums()<SArenaSetting.getSArenaSetting().getPveNum()){
Set<Integer> robotIds = randomRobot(score, 5);
toArenaEnemy(uid,robotIds,arenaEnemies,GlobalsDef.ARENA_ROBOT_TYPE);
}else{
Set<Integer> robotIds = randomPerson(uid,score,true);
int type = GlobalsDef.ARENA_PLAYER_TYPE;
toArenaEnemy(uid,robotIds,arenaEnemies,type);
if(robotIds.isEmpty()){
if(curSeason>1){
robotIds = randomPerson(uid,score,false);
}
toArenaEnemy(uid,robotIds,arenaEnemies,type);
}
int size = robotIds.size();
if(size<5){
robotIds = randomRobot(score, 5-size);
type = GlobalsDef.ARENA_ROBOT_TYPE;
toArenaEnemy(uid,robotIds,arenaEnemies,type);
}
}
arenaManager.setArenaEnemies(arenaEnemies);
}
public static int getFightResultByPersonToPerson(User mine, int myteamId, User defUser, int defTeamId, ArenaRecord arenaRecord, ArenaInfoProto.ArenaChallengeResponse.Builder builder) throws Exception {
PVPFightEvent pvpFightEvent = new PVPFightEvent(mine.getId(),myteamId,SArenaSetting.getSArenaSetting().getMostTime(),"", GameFightType.ArenaPersonFight,defUser.getId(),defTeamId);
int myforce = HeroLogic.getInstance().calTeamTotalForce(mine, GlobalsDef.TEAM_ARENA_DEFENSE, false);
int defForce = HeroLogic.getInstance().calTeamTotalForce(defUser, GlobalsDef.TEAM_ARENA_DEFENSE, false);
arenaRecord.setAttackForce(myforce);
if(myforce<defForce){
pvpFightEvent.setRever(true);
}
FightResult fightResult = FightDispatcher.dispatcher(pvpFightEvent);
CommonProto.FightTeamInfo fightTeamInfo =fightResult.getFightTeamInfo();
CommonProto.FightTeamInfo deffightTeamInfo = fightResult.getDefFightTeamInfo();
//设置战斗随机种子
int seed = fightResult.getSeed();
CommonProto.FightData build = CommonProto.FightData.newBuilder()
.setFightMaxTime(SArenaSetting.getSArenaSetting().getMostTime())
.setFightSeed(seed)
.setHeroFightInfos(fightTeamInfo)
.addMonsterList(deffightTeamInfo)
.build();
builder.setFightData(build);
//数据互换
byte[] snapRecord = build.toByteArray();
arenaRecord.setFightData(snapRecord);
return fightResult.getCheckResult()[0];
}
public int getFightResultByPersonToRobot(User mine, int myteamId, int challengeUid,ArenaInfoProto.ArenaChallengeResponse.Builder builder) throws Exception {
PVPFightEvent pvpFightEvent = new PVPFightEvent(mine.getId(),myteamId,SArenaSetting.getSArenaSetting().getMostTime(),"", GameFightType.ArenaRobotFight,challengeUid,-1);
int myforce = HeroLogic.getInstance().calTeamTotalForce(mine, GlobalsDef.TEAM_ARENA_DEFENSE, false);
SArenaRobotConfig sArenaRobotConfig = SArenaRobotConfig.getsArenaRobotConfigById(myteamId);
if(sArenaRobotConfig!=null&&myforce<sArenaRobotConfig.getTotalForce()){
pvpFightEvent.setRever(true);
}
FightResult fightResult = FightDispatcher.dispatcher(pvpFightEvent);
CommonProto.FightTeamInfo fightTeamInfo =fightResult.getFightTeamInfo();
CommonProto.FightTeamInfo deffightTeamInfo = fightResult.getDefFightTeamInfo();
//设置战斗随机种子
int seed = fightResult.getSeed();
builder.setFightData(CommonProto.FightData.newBuilder()
.setFightMaxTime(SArenaSetting.getSArenaSetting().getMostTime())
.setFightSeed(seed)
.setHeroFightInfos(fightTeamInfo)
.addMonsterList(deffightTeamInfo)
.build());
return fightResult.getCheckResult()[0];
}
public String checkChallenge(User user,int skipFight, ArenaEnemy enemyInfo) throws Exception {
if( null == enemyInfo ){
return "对手错误";
}
if(skipFight == 1){
boolean allowed = user.getPlayerInfoManager().checkFunctionIsAllowed(VipPrivilegeType.UNLOCK_SKIP_ARENA);
if(!allowed){
return "not allowed";
}
}
if(!user.getTeamPosManager().getTeamPosForHero().containsKey(GlobalsDef.TEAM_ARENA_DEFENSE)){
return "未设置防守阵容";
}
SArenaSetting sArenaSetting = SArenaSetting.getSArenaSetting();
int battleFree = sArenaSetting.getBattleFree();
if(!PlayerLogic.getInstance().checkAndUpdate(user,battleFree,1)){
//校验消耗
boolean enough = ItemUtil.itemCost(user, new int[][]{sArenaSetting.getCost()}, BIReason.ARENA_CHALLENGE_CONSUME,enemyInfo.getEnemyId());
if(!enough){
throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH);
}
}
return "";
}
public ArenaEnemy getEnemyInList(int challengeUid, List<ArenaEnemy> enemys) {
for (ArenaEnemy data : enemys) {
if (data.getEnemyId() == challengeUid) {
return data;
}
}
return null;
}
//
// public void randomEnemys(ISession session) throws Exception {
// if(curSeason == 0){
// throw new ErrorCodeException(ErrorCode.newDefineCode("season_close"));
// }
// int uid = session.getUid();
// SArenaSetting sArenaSetting = SArenaSetting.getSArenaSetting();
// if(sArenaSetting == null){
// throw new ErrorCodeException(ErrorCode.CFG_NULL);
// }
// User user = UserManager.getUser(uid);
// ArenaManager arenaManager = user.getArenaManager();
// int flushEnenyTime = arenaManager.getFlushTime();
// int coldTime = sArenaSetting.getColdTime();
// int now = (int)(TimeUtils.now()/1000);
// if( now - flushEnenyTime < coldTime-1 ){
// throw new ErrorCodeException(ErrorCode.ARENA_RANDOM_ENEMY_CODE_TIME);
// }
// //刷新选手
// setMyArenaEnemys(uid,user);
// arenaManager.setFlushTime(now);
// ArenaInfoProto.ArenaRandomResponse build = ArenaInfoProto.ArenaRandomResponse.newBuilder().addAllArenaEnemys(getArenaEnemyList(arenaManager.getArenaEnemies())).build();
// MessageUtil.sendMessage(session,1, MessageTypeProto.MessageType.ARENA_RANDOM_ENEMY_RESPONSE_VALUE,build,true);
// }
public static Set<Integer> randomRobot(int userSscore,int nums){
Set<Integer> robotIds = new HashSet<>(5);
Map<Integer, SArenaRobotSetting> config = STableManager.getConfig(SArenaRobotSetting.class);
for(SArenaRobotSetting sArenaRobotSetting : config.values()){
int playerLevelMin = sArenaRobotSetting.getPlayerScoreMin();
int playerLevelMax = sArenaRobotSetting.getPlayerScoreMax();
if(userSscore>=playerLevelMin && userSscore<=playerLevelMax){
int poolId = sArenaRobotSetting.getPool();
List<SArenaRobotConfig> sArenaRobotConfigsByPool = SArenaRobotConfig.getSArenaRobotConfigsByPool(poolId);
int size = sArenaRobotConfigsByPool.size();
while (robotIds.size() < nums){
robotIds.add(sArenaRobotConfigsByPool.get(MathUtils.randomInt(size)).getId());
}
}
}
return robotIds;
}
public Set<Integer> randomPerson(int uid,int myScore,boolean useCurSeason){
Set<Integer> result = new HashSet<>(5);
int[][] interval = SArenaSetting.getSArenaSetting().getInterval();
int matchSeason = curSeason;
if(!useCurSeason){
matchSeason = curSeason - 1;
}
for(int[] item: interval){
int low = item[0];
int high = item[1];
Set<String> arenaRank = RedisUtil.getInstence().getZsetRange(RedisKey.ARENA_RANK,Integer.toString(matchSeason), myScore * low / 10000.0f-1, myScore * high / 10000.0f +1);
LOGGER.info("curSeason={},matchSeason={},the uid={},the myscore={},the low={},the high={},mylow={},myhigh={},",curSeason,matchSeason,uid,myScore,low,high,myScore * low / 10000.0f-1,myScore * high / 10000.0f +1);
if(arenaRank!=null && !arenaRank.isEmpty()){
arenaRank.remove(Integer.toString(uid));
String s = randomSet(arenaRank);
if(!StringUtil.isEmpty(s)){
result.add(Integer.parseInt(s));
}
}
}
return result;
}
private String randomSet(Set<String> infos){
if(infos == null || infos.isEmpty()){
return null;
}
int num = MathUtils.randomInt(infos.size());
for(String id : infos){
if(num-- == 0){
return id;
}
}
return null;
}
public void toArenaEnemy(int uid,Set<Integer> enemyList,List<ArenaEnemy> arenaEnemies,int type){
for(Integer enemyId: enemyList){
if(1 == type && enemyId == uid){
continue;
}
arenaEnemies.add(new ArenaEnemy(enemyId,type,type));
}
}
public void getWorldRankByPage(ISession session,int page) throws Exception {
if (page == 0) {
page = 1;
}
int start = (page - 1) * 20, end = page * 20 - 1;
List<CommonProto.ArenaEnemy> arenaRankMemberInfo = new ArrayList<>(20);
int rankEndLine = SSpecialConfig.getIntegerValue(SSpecialConfig.ARENA_RANKINGSHOWNUM);
if(end<rankEndLine) {
Set<ZSetOperations.TypedTuple<String>> arenaRankInfo = RedisUtil.getInstence().getZsetreverseRangeWithScores(RedisKey.ARENA_RANK, Integer.toString(viewSeason), start, end);
for (ZSetOperations.TypedTuple<String> item : arenaRankInfo) {
String value = item.getValue();
int score = item.getScore().intValue();
int uid = Integer.parseInt(value);
User user = UserManager.getUser(uid,true);
if (null == user) {
continue;
}
int totalForce = HeroLogic.getInstance().calTeamTotalForce(user, GlobalsDef.TEAM_ARENA_DEFENSE, false);
List<TeamPosHeroInfo> teamPosHeroInfoList = user.getTeamPosManager().getTeamPosForHero().get(GlobalsDef.TEAM_ARENA_DEFENSE);
Map<String, Hero> heroMap = user.getHeroManager().getHeroMap();
List<Integer> heroTids = new ArrayList<>(teamPosHeroInfoList.size());
for (TeamPosHeroInfo teamPosHeroInfo : teamPosHeroInfoList) {
heroTids.add(heroMap.get(teamPosHeroInfo.getHeroId()).getTemplateId());
}
CommonProto.Team teamBuild = CommonProto.Team.newBuilder().addAllHeroTid(heroTids).build();
PlayerManager playerInfoManager = user.getPlayerInfoManager();
CommonProto.ArenaPersonInfo personInfoBuild = CommonProto.ArenaPersonInfo.newBuilder()
.setUid(uid)
.setLevel(playerInfoManager.getLevel())
.setName(playerInfoManager.getNickName())
.setScore(score)
.setHead(playerInfoManager.getHead())
.setRank(++start)
.setTotalForce(totalForce)
.setHeadFrame(playerInfoManager.getHeadFrame())
.build();
arenaRankMemberInfo.add(CommonProto.ArenaEnemy.newBuilder()
.setPersonInfo(personInfoBuild)
.setTeam(teamBuild)
.build());
}
}
int uid = session.getUid();
int score = RedisUtil.getInstence().getZSetScore(RedisKey.ARENA_RANK,Integer.toString(viewSeason), Integer.toString(uid)).intValue();
int myRank =-1;
if(score == -1){
score = SArenaSetting.getSArenaSetting().getScore();
}else{
myRank= RedisUtil.getInstence().getZSetreverseRank(RedisKey.ARENA_RANK,Integer.toString(viewSeason),Integer.toString(uid)).intValue();
}
ArenaInfoProto.GetArenaRankInfoResponse buildResponse = ArenaInfoProto.GetArenaRankInfoResponse.newBuilder()
.addAllRankInfos(arenaRankMemberInfo)
.setMyRank(myRank)
.setMyscore(score)
.build();
MessageUtil.sendMessage(session,1, MessageTypeProto.MessageType.ARENA_RANK_RESPONSE_VALUE,buildResponse,true);
}
/**
*
Sa: = 1 =0
Ra: A Rb B
R'a: A R'b B
EaEA = 1/(1+10^[(Rb-Ra)/400])
Eb: EB = 1/(1+10^[(Ra-Rb)/400])
R'a = Ra + K(Sa-Ea)
R'b = Rb + K(Sb-Eb)
*
*/
public int calScore(int myScore,int defScore,int result){
SArenaSetting sArenaSetting = SArenaSetting.getSArenaSetting();
int k = sArenaSetting.getK();
double ea = 1.0/(1 + Math.pow(10,(defScore - myScore)/400.0f));
int parm = result == 1?1:-1;
return (int)(k*(result-ea) + 0.5*parm);
}
public void getFightReplayData(ISession iSession,int type,String fightId) throws Exception {
int uid = iSession.getUid();
ArenaRecord arenaRecord=null;
if(type == 2){
arenaRecord = RedisUtil.getInstence().getMapEntry(RedisKey.CHAMPION_ARENA_RECORD,"", fightId, ArenaRecord.class);
}else if(type == 1){
arenaRecord = RedisUtil.getInstence().getMapEntry(RedisKey.ARENA_RRECORD, Integer.toString(uid), fightId, ArenaRecord.class);
}else if(type == 3){
arenaRecord = RedisUtil.getInstence().get(RedisKey.GUILDBOSS_ARENA_RECORD, fightId, ArenaRecord.class);
}
if(arenaRecord == null){
throw new ErrorCodeException(ErrorCode.newDefineCode("arena_rrecord null"));
}
byte[] fightData = arenaRecord.getFightData();
CommonProto.FightData fightDataProto = CommonProto.FightData.parseFrom(fightData);
FightInfoProto.FightRePlayResponse build = FightInfoProto.FightRePlayResponse.newBuilder().setFightData(fightDataProto).build();
MessageUtil.sendMessage(iSession,1, MessageTypeProto.MessageType.VIEW_FIGHTREPLAY_RESPONSE_VALUE,build,true);
}
/**
*
* @param type
* @throws Exception
*/
public void sendReward(int type) throws Exception {
if(curSeason == 0){
return;
}
String title;
String content;
if(type == GlobalsDef.ARENA_DAILY_REWARD){
title = SErrorCodeEerverConfig.getI18NMessage("arena_daily_reward_title");
}else{
title = SErrorCodeEerverConfig.getI18NMessage("arena_season_reward_title");
}
Set<ZSetOperations.TypedTuple<String>> arenaRankInfo = RedisUtil.getInstence().getZsetreverseRangeWithScores(RedisKey.ARENA_RANK,Integer.toString(curSeason), 0, -1);
if(type == GlobalsDef.ARENA_SEASON_REWARD){
curSeason=0;
}
int rank = 1;
int nowTime =(int) (TimeUtils.now()/1000);
for(ZSetOperations.TypedTuple<String> item : arenaRankInfo){
String value = item.getValue();
int uid = Integer.parseInt(value);
User user = UserManager.getUser(uid, true);
if (null == user) {
continue;
}
if(type == GlobalsDef.ARENA_DAILY_REWARD){
MissionEventDistributor.requestStart();
user.getUserMissionManager().onGameEvent(user,GameEvent.ARENA_UPDATE_RANK,rank);
ISession sessionByUid = OnlineUserManager.getSessionByUid(uid);
if(sessionByUid!=null){
MissionEventDistributor.requestEnd(sessionByUid,true);
}
}
if(type == GlobalsDef.ARENA_DAILY_REWARD){
content = SErrorCodeEerverConfig.getI18NMessage("arena_daily_reward_txt",new Object[]{rank});
}else{
content = SErrorCodeEerverConfig.getI18NMessage("arena_season_reward_txt",new Object[]{rank});
user.getPlayerInfoManager().removeRed(GlobalsDef.ARENA_CHALLENGE_TYPE);
String key = RedisUtil.getInstence().getKey(RedisKey.ARENA_RRECORD, Integer.toString(uid));
RedisUtil.getInstence().del(key);
}
String rewardByRank = getRewardByRank(rank++, type);
if(!"".equals(rewardByRank)){
MailLogic.getInstance().sendMail(user.getId(),title,content,rewardByRank,nowTime, Global.MAIL_EFFECTIVE_TIME);
}
}
MongoUtil.getInstence().lastUpdate();
}
public String getRewardByRank(int rank,int type){
Map<Integer, SArenaReward> config = STableManager.getConfig(SArenaReward.class);
for(SArenaReward sArenaReward : config.values()){
int minRank = sArenaReward.getMinRank();
int maxRank = sArenaReward.getMaxRank();
if(rank>=minRank && rank<=maxRank){
if(type == GlobalsDef.ARENA_DAILY_REWARD){
int[][] dailyReward = sArenaReward.getDailyReward();
return StringUtil.parseArrayToString(dailyReward);
}else{
int[][] seasonReward = sArenaReward.getSeasonReward();
return StringUtil.parseArrayToString(seasonReward);
}
}
}
return "";
}
public void updateArenaSeason(int curSeason){
this.curSeason = curSeason;
if(this.curSeason!=0){
viewSeason = this.curSeason;
}
}
public void playWithSb(ISession session,int challengeUid,int myteamId) throws Exception {
User mine = UserManager.getUser(session.getUid());
User defUser = UserManager.getUser(challengeUid);
if(!defUser.getTeamPosManager().getTeamPosForHero().containsKey(1)){
throw new ErrorCodeException(ErrorCode.newDefineCode("对方未设置阵容"));
}
int myforce = HeroLogic.getInstance().calTeamTotalForce(mine, myteamId, false);
int deforce = HeroLogic.getInstance().calTeamTotalForce(defUser, 1, false);
CommonProto.FightTeamInfo fightTeamInfo = BehaviorUtil.getFightTeamInfo(mine,myteamId,true);
CommonProto.FightTeamInfo deffightTeamInfo = BehaviorUtil.getFightTeamInfo(defUser,1,false);
if(myforce<deforce){
deffightTeamInfo = CommonProto.FightTeamInfo.newBuilder().mergeFrom(deffightTeamInfo).setFirstCamp(1).build();
}
//设置战斗随机种子
int seed = (int)(System.currentTimeMillis()/1000);
CommonProto.FightData build = CommonProto.FightData.newBuilder()
.setFightMaxTime(SArenaSetting.getSArenaSetting().getMostTime())
.setFightSeed(seed)
.setHeroFightInfos(fightTeamInfo)
.addMonsterList(deffightTeamInfo)
.build();
ArenaInfoProto.PlayWithSbResponse response = ArenaInfoProto.PlayWithSbResponse.newBuilder().setFightData(build).build();
MessageUtil.sendMessage(session,1, MessageTypeProto.MessageType.PLAY_WITH_SB_RESPONSE_VALUE,response,true);
}
}

View File

@ -0,0 +1,194 @@
package com.world.logic.dao;
import com.ljsd.jieling.config.clazzStaticCfg.CommonStaticConfig;
import com.ljsd.jieling.core.GlobalsDef;
import com.ljsd.jieling.db.mongo.MongoUtil;
import com.ljsd.jieling.globals.BIReason;
import com.ljsd.jieling.ktbeans.ReportEventEnum;
import com.ljsd.jieling.ktbeans.ReportUtil;
import com.ljsd.jieling.logic.OnlineUserManager;
import com.ljsd.jieling.logic.activity.ActivityLogic;
import com.ljsd.jieling.logic.activity.event.NewWelfareEvent;
import com.ljsd.jieling.logic.activity.event.NewWelfareTypeEnum;
import com.ljsd.jieling.logic.activity.event.Poster;
import com.ljsd.jieling.logic.dao.root.User;
import com.ljsd.jieling.logic.hero.HeroLogic;
import com.ljsd.jieling.logic.mission.GameEvent;
import com.ljsd.jieling.logic.player.PlayerLogic;
import com.ljsd.jieling.util.ItemUtil;
import config.SGameSetting;
import config.SPlayerLevelConfig;
import manager.STableManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.TimeUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class UserManager {
private static final Logger LOGGER = LoggerFactory.getLogger(UserManager.class);
private static Map<Integer, User> userMap = new ConcurrentHashMap<>();
private static Map<Integer,Long> userMapPutTime = new ConcurrentHashMap<>(); //离线读入
public static void addUser(User user) {
userMap.put(user.getId(), user);
userMapPutTime.put(user.getId(),TimeUtils.now());
}
public static boolean isUserExist(int uid) {
return userMap.containsKey(uid);
}
//离线清除逻辑
public static void checkOffline(){
try {
Set<User> collect = userMap.entrySet().stream().filter(integerUserEntry -> !OnlineUserManager.checkUidOnline(integerUserEntry.getKey())).map(Map.Entry::getValue).collect(Collectors.toSet());
long l = System.currentTimeMillis();
collect.forEach(integerUserEntry -> {
long offLineTime = integerUserEntry.getPlayerInfoManager().getOffLineTime();
if(offLineTime<integerUserEntry.getPlayerInfoManager().getOnlineTime()){
return;
}
if(l-offLineTime>12*60*60*1000&& userMapPutTime.getOrDefault(integerUserEntry.getId(),0L)>12*60*60*1000){
userMap.remove(integerUserEntry.getId());
userMapPutTime.remove(integerUserEntry.getId());
}
});
}catch (Exception e){
LOGGER.error("Exception离线清除逻辑err={}",e.toString());
}
}
public static User userLogin(int uid,String openId,String channel,int pid,int gid,String platform,String ip,String channle_id,String bundle_id) throws Exception {
User user = null;
if (!UserManager.isUserExist(uid)){
user = MongoUtil.getInstence().getMyMongoTemplate().findById(User.getCollectionName(), uid, User.class);
if (user == null) {
user = registerUser(uid,openId,channel,pid,gid,platform,ip,channle_id,bundle_id);
}
UserManager.addUser(user);
}else{
user = getUser(uid);
user.getPlayerInfoManager().setGid(gid);
user.getPlayerInfoManager().setPid(pid);
}
return user;
}
private static User registerUser(int uid,String openId,String channel,int pid,int gid,String platform,String ip,String channle_id,String bundle_id) throws Exception {
User user = new User(uid);
UserManager.addUser(user);
initPlayer(user,openId,channel,pid,gid,platform,ip,channle_id,bundle_id);
MongoUtil.getInstence().getMyMongoTemplate().save(user.getId(),user);
PlayerLogic.getInstance().sendTestWelfareMail(user,1,1);
return user;
}
private static void initPlayer(User user,String openId,String channel,int pid,int gid,String platform,String ip,String channle_id,String bundle_id) throws Exception {
SGameSetting gameSetting = STableManager.getFigureConfig(CommonStaticConfig.class).getGameSetting();
PlayerManager playerManager = user.getPlayerInfoManager();
long now = TimeUtils.now();
playerManager.setNickName(Integer.toString(user.getId()));
playerManager.setOpenId(openId);
playerManager.setLevel(1);
playerManager.setExp(0);
//todo 改默认
playerManager.setHead(STableManager.getFigureConfig(CommonStaticConfig.class).getGameSetting().getDefaultHead());
playerManager.updateGuidePoint(1,1);
playerManager.setCreateTime(now);
playerManager.setLoginTime(now);
playerManager.setSendDays(1);
playerManager.updateVipInfo(GlobalsDef.LEVEL_UNLOCK_PRIVILEGE,1);
playerManager.updateVipInfo(GlobalsDef.VIP_UNLOCK_PRIVILEGE,0);
playerManager.setRechargeInfo(new RechargeInfo());
playerManager.setPhoneBindInfo(new PhoneBindInfo(""));
playerManager.setChannel(channel);
playerManager.setPid(pid);
playerManager.setGid(gid);
playerManager.setPlatform(platform);
playerManager.setIp(ip);
playerManager.setChannel_id(channle_id);
playerManager.setBundle_id(bundle_id);
playerManager.setHeadFrame(STableManager.getFigureConfig(CommonStaticConfig.class).getGameSetting().getDefaultPicture());
SPlayerLevelConfig sPlayerLevelConfig = SPlayerLevelConfig.getsPlayerLevelConfigMap().get(1);
playerManager.setMaxStamina(sPlayerLevelConfig.getMaxEnergy());
playerManager.setRideLevel(1);
PlayerLogic.getInstance().vipflushEveryDay(user,null);
ActivityLogic.getInstance().newPlayerOpenActivityMission(user);
PlayerLogic.getInstance().playerInfoUpdate(user);
user.getMainLevelManager().init();
user.getUserMissionManager().onGameEvent(user, GameEvent.USER_LEVELUP,0,1);
user.getUserMissionManager().onGameEvent(user, GameEvent.DAILY_REFRESH,0);
user.getUserMissionManager().onGameEvent(user, GameEvent.BLOODY_REFRESH,0);
user.getUserMissionManager().onGameEvent(user, GameEvent.MISSING_ROOM_REFRESH,0);
user.getUserMissionManager().onGameEvent(user, GameEvent.ACHIEVE_REFRESH, 0);
user.getUserMissionManager().onGameEvent(user, GameEvent.BEGINNER);
user.getUserMissionManager().onGameEvent(user, GameEvent.VIP_LEVLUP,0);
Poster.getPoster().dispatchEvent(new NewWelfareEvent(user, NewWelfareTypeEnum.LOGIN_TIMES.getType(),1));
ReportUtil.onReportEvent(user, ReportEventEnum.CREATE_ROLE.getType());//先发送注册事件
ItemUtil.drop(user,gameSetting.getBornItem(), BIReason.USER_BORN_REWARD);
HeroManager heroManager = user.getHeroManager();
Map<String, Hero> heroMap = heroManager.getHeroMap();
TeamPosManager teamPosManager = user.getTeamPosManager();
List<Hero> teamHeros = new ArrayList<>(1);
teamHeros.add(heroMap.values().iterator().next());
teamPosManager.addTeamOfInitPlayer(teamHeros);
int force = HeroLogic.getInstance().calTeamTotalForce(user, 1, true);
playerManager.setMaxForce(force);
user.getExpeditionManager().setExpeditionLeve(1);
// user.getExpeditionManager().setForceSnap(force);
// KtEventUtils.onKtEvent(user, ParamEventBean.UserRegister);
}
public static User getUser(int uid) throws Exception {
return getUser(uid,false);
}
public static User getUser(int uid,boolean canNull) throws Exception {
User user = userMap.get(uid);
if (user != null) {
return user;
}
user = MongoUtil.getInstence().getMyMongoTemplate().findById(User.getCollectionName(), uid, User.class);
if (null == user) {
if(canNull){
return null;
}
throw new Exception("UserManager::getUser null exception"+uid);
}
UserManager.addUser(user);
return user;
}
public static User getUserInMem(int uid) {
// User user = userMap.get(uid);
try {
return getUser(uid,true);
}catch (Exception e){
LOGGER.error("UserManager::getUser null exception"+uid);
}
return null;
}
public static void removeUser(int uid) {
userMap.remove(uid);
}
public static String getNewToken(int userId) {
return "33521";
}
}

View File

@ -0,0 +1,204 @@
package com.world.network;
import com.google.protobuf.GeneratedMessage;
import com.googlecode.protobuf.format.JsonFormat;
import com.ljsd.jieling.netty.PackageConstant;
import com.ljsd.jieling.netty.cocdex.Tea;
import com.world.network.session.ISession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.protocols.CommonProto;
import rpc.protocols.MessageTypeProto;
import java.util.ArrayList;
import java.util.List;
/**
* netty使
* thrift访
*/
public class MessageUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(MessageUtil.class);
public static byte[] wrappedBuffer(int uid, int token, int index, int result, int msgId, GeneratedMessage generatedMessage) {
byte[] backMessage;
if (generatedMessage == null) {
backMessage = new byte[0];
} else {
backMessage = generatedMessage.toByteArray();
if (backMessage.length != 0)
LOGGER.info("wrappedBuffer uid=>{}, generatedMessage=>{}", uid, JsonFormat.printToString(generatedMessage));
}
return wrappedBuffer(uid, token, index, result, msgId, backMessage);
}
public static byte[] wrappedBuffer(int uid, int token, int index, int result, int msgId,byte[] backMessage) {
int length = PackageConstant.UID_FIELD_LEN + PackageConstant.TOKEN_LEN
+ PackageConstant.MSG_ID_FIELD_LEN + PackageConstant.INDEX_FIELD_LEN
+ PackageConstant.RESULT_LEN + backMessage.length;
byte[] bytes = new byte[length];
int pos = 0;
Tea.intToByte(bytes, pos, uid);
pos += PackageConstant.UID_FIELD_LEN;
Tea.intToByte(bytes, pos, token);
pos += PackageConstant.TOKEN_LEN;
Tea.intToByte(bytes, pos, msgId);
pos += PackageConstant.MSG_ID_FIELD_LEN;
Tea.intToByte(bytes, pos, index);
pos += PackageConstant.INDEX_FIELD_LEN;
Tea.intToByte(bytes, pos, result);
pos += PackageConstant.RESULT_LEN;
if (backMessage.length != 0) {
System.arraycopy(backMessage, 0, bytes, pos, backMessage.length);
}
int[] secretKey = Tea.KEY;
byte[] bytes1 = Tea.encrypt2(bytes, secretKey);
// if (backMessage.length != 0) {
// LOGGER.info("wrappedBuffer uid=>{} sendbyte=>{}", uid, bytes1.length);
// }
return bytes1;
}
public static void sendMessage(int[] uids, int result, int msgId, GeneratedMessage generatedMessage, boolean flush) {
for(int i=0; i<uids.length; i++){
sendMessage(uids[i], result, msgId, generatedMessage, flush);
}
}
public static void sendMessage(int uid, int result, int msgId, GeneratedMessage generatedMessage, boolean flush) {
ISession sessionByUid = OnlineServerManager.getSessionByUid(uid);
sendMessage(sessionByUid, result, msgId, generatedMessage, flush);
}
public static void sendMessage(ISession session, int result, int msgId, GeneratedMessage generatedMessage, boolean flush) {
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(), result, msgId, generatedMessage);
session.write(byteBuf,flush);
session.putBackMassageToMap(byteBuf);
}
public static void sendMessage(ISession session, int result, int msgId, GeneratedMessage generatedMessage) {
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(), result, msgId, generatedMessage);
session.writeAndFlush(byteBuf);
session.putBackMassageToMap(byteBuf);
}
public static void sendMessageWithoutBack(ISession session, int result, int msgId, GeneratedMessage generatedMessage, boolean flush) {
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(), result, msgId, generatedMessage);
session.write(byteBuf,flush);
}
public static void sendIndicationMessage(ISession session, int result, int msgId, GeneratedMessage generatedMessage, boolean flush) {
if(null == session){
return;
}
if(session.getFiveReady() == 0){
return;
}
int indicationIndex = session.getIndicationIndex();
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), indicationIndex,result, msgId, generatedMessage);
session.write(byteBuf,flush);
session.putBackIndicationToMap(indicationIndex,byteBuf);
}
/**
* 30000
* @param generatedMessage
*/
public static void sendIndicationMessage(int uid, GeneratedMessage generatedMessage) {
ISession session = OnlineServerManager.getSessionByUid(uid);
// sendIndicationMessage(session,generatedMessage);
}
public static void sendIndicationMessage(int uid ,int msgId ,byte[] byteBuf) {
ISession session = OnlineServerManager.getSessionByUid(uid);
if(null == session){
return;
}
byte[] byteBuf2 = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(), 1, msgId, byteBuf);
session.write(byteBuf2,true);
session.putBackMassageToMap(byteBuf2);
}
public static void retrySendIndication( ISession session, byte[] byteBuf){
session.writeAndFlush(byteBuf);
}
public static void sendHeartBeat(ISession session) {
int now = (int)(System.currentTimeMillis()/1000);
int length = PackageConstant.UID_FIELD_LEN + PackageConstant.TOKEN_LEN
+ PackageConstant.MSG_ID_FIELD_LEN + 4 ;
byte[] bytes = new byte[length];
int pos = 0;
Tea.intToByte(bytes, pos, session.getUid());
pos += PackageConstant.UID_FIELD_LEN;
Tea.intToByte(bytes, pos, session.getToken());
pos += PackageConstant.TOKEN_LEN;
Tea.intToByte(bytes, pos, MessageTypeProto.MessageType.HEART_BEAT_RESPONSE_VALUE);
pos +=4;
Tea.intToByte(bytes, pos, now);
byte[] byteBuf = Tea.encrypt2(bytes, Tea.KEY);
session.writeAndFlush(byteBuf);
}
public static void sendAck(ISession session,int ackId) {
int length = PackageConstant.UID_FIELD_LEN + PackageConstant.TOKEN_LEN
+ PackageConstant.MSG_ID_FIELD_LEN + PackageConstant.INDEX_FIELD_LEN+4;
byte[] bytes = new byte[length];
int pos = 0;
Tea.intToByte(bytes, pos, session.getUid());
pos += PackageConstant.UID_FIELD_LEN;
Tea.intToByte(bytes, pos, session.getToken());
pos += PackageConstant.TOKEN_LEN;
Tea.intToByte(bytes, pos, MessageTypeProto.MessageType.ACK_INDICATION_RESPONSE_VALUE);
pos += PackageConstant.MSG_ID_FIELD_LEN;
Tea.intToByte(bytes, pos, ackId);
pos += PackageConstant.INDEX_FIELD_LEN;
Tea.intToByte(bytes, pos, 1);
byte[] byteBuf = Tea.encrypt2(bytes, Tea.KEY);
session.writeAndFlush(byteBuf);
}
//服务器推送错误码,一般情况是系统错误
public static void sendErrorCode(ISession session,int errorCode, String errMsg) {
if( null == errMsg){
errMsg="";
}
GeneratedMessage generatedMessage = CommonProto.ErrorResponse.newBuilder().setErrCode(errorCode).setErrMsg(errMsg).build();
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(),
0, MessageTypeProto.MessageType.ERROR_CODE_INDICATION_VALUE, generatedMessage);
session.writeAndFlush(byteBuf);
}
//服务器逻辑错误返回,一般情况是业务逻辑错误
public static void sendErrorResponse(ISession session,int errorCode,int msgId, String errMsg) throws Exception {
sendErrorResponse(session, errorCode, msgId, errMsg,new ArrayList<>());
}
//服务器逻辑错误返回,一般情况是业务逻辑错误
public static void sendErrorResponse(ISession session,int errorCode,int msgId, String errMsg,List<String> param) throws Exception {
GeneratedMessage generatedMessage = null;
if( null == errMsg){
errMsg="";
}
generatedMessage = CommonProto.ErrorResponse.newBuilder().setErrCode(errorCode).setErrMsg(errMsg).addAllErrParams(param).build();
LOGGER.error("send error msg,the uid={},the msgId={},the errMsg={}",session.getUid(),msgId,errMsg);
byte[] byteBuf = wrappedBuffer(session.getUid(), session.getToken(), session.getIndex(),
0,msgId, generatedMessage);
session.writeAndFlush(byteBuf);
session.putBackMassageToMap(byteBuf);
}
}

View File

@ -0,0 +1,57 @@
package com.world.network;
import com.IManager;
import com.WorldServerApplication;
import com.ljsd.jieling.NetWorkFactory;
import com.ljsd.jieling.netty.config.EndPortCfg;
import com.ljsd.jieling.netty.server.NettyGameServer;
import com.world.config.ConfigurableApplicationContextManager;
import com.world.network.server.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Description:
* Author: zsx
* CreateDate: 2019/11/6 17:34
*/
public class NetManager implements IManager {
private static final Logger LOGGER = LoggerFactory.getLogger(WorldServerApplication.class);
public final static NetManager instance = new NetManager();
public static NetManager getInstance() {
return instance;
}
private static NettyGameServer nettyServer = null;
@Override
@SuppressWarnings("unchecked")
public void init() throws Exception {
try {
final NettyServerAutoConfiguration netServerConfig = ConfigurableApplicationContextManager.getBean(NettyServerAutoConfiguration.class);
NettyProperties properties = netServerConfig.getNettyProperties();
LOGGER.info("main->NettyServerAutoConfiguration start...");
//连接处理
nettyServer = NetWorkFactory.getServer(new EndPortCfg(properties.getTcpPort(), properties.getReadTimeout(),
properties.getWriteTimeout(), properties.getAllTimeout()), SessionManager.getInstance());
nettyServer.start();
} catch (Exception e) {
LOGGER.error("main->msg={}", e.getMessage(), e);
}
}
@Override
public void exit() throws Exception {
LOGGER.info("close->QuartzManager.getInstance().shutdownJob-------------------");
try {
nettyServer.stop();
} catch (Exception e) {
LOGGER.error("close->msg={}", e.getMessage(), e);
}
LOGGER.info("close->nettyServer.stop-------------------");
}
}

View File

@ -0,0 +1,130 @@
package com.world.network;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "netty")
public class NettyProperties {
private int logintcpPort;
private int chatTcpPort;
private int tcpPort;
private int udpPort;
private String udpTargetIp;
private int udpTargetPort;
private int reconnectDelay=300000;
private int bossThreadCount=2;
private int workerThreadCount=2;
private int readTimeout=600;
private int writeTimeout=600;
private int allTimeout=1000;
private String tcpIp;
public NettyProperties(){}
public int getLogintcpPort() {
return logintcpPort;
}
public void setLogintcpPort(int logintcpPort) {
this.logintcpPort = logintcpPort;
}
public int getTcpPort() {
return tcpPort;
}
public void setTcpPort(int tcpPort) {
this.tcpPort = tcpPort;
}
public int getUdpPort() {
return udpPort;
}
public void setUdpPort(int udpPort) {
this.udpPort = udpPort;
}
public int getReconnectDelay() {
return reconnectDelay;
}
public void setReconnectDelay(int reconnectDelay) {
this.reconnectDelay = reconnectDelay;
}
public int getBossThreadCount() {
return bossThreadCount;
}
public void setBossThreadCount(int bossThreadCount) {
this.bossThreadCount = bossThreadCount;
}
public int getWorkerThreadCount() {
return workerThreadCount;
}
public void setWorkerThreadCount(int workerThreadCount) {
this.workerThreadCount = workerThreadCount;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getWriteTimeout() {
return writeTimeout;
}
public void setWriteTimeout(int writeTimeout) {
this.writeTimeout = writeTimeout;
}
public int getAllTimeout() {
return allTimeout;
}
public void setAllTimeout(int allTimeout) {
this.allTimeout = allTimeout;
}
public String getUdpTargetIp() {
return udpTargetIp;
}
public void setUdpTargetIp(String udpTargetIp) {
this.udpTargetIp = udpTargetIp;
}
public int getUdpTargetPort() {
return udpTargetPort;
}
public void setUdpTargetPort(int udpTargetPort) {
this.udpTargetPort = udpTargetPort;
}
public int getChatTcpPort() {
return chatTcpPort;
}
public void setChatTcpPort(int chatTcpPort) {
this.chatTcpPort = chatTcpPort;
}
public String getTcpIp() {
return tcpIp;
}
public void setTcpIp(String tcpIp) {
this.tcpIp = tcpIp;
}
}

View File

@ -0,0 +1,18 @@
package com.world.network;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(NettyProperties.class)
public class NettyServerAutoConfiguration {
@Autowired
private NettyProperties nettyProperties;
public NettyProperties getNettyProperties() {
return nettyProperties;
}
}

View File

@ -0,0 +1,68 @@
package com.world.network;
import com.world.network.session.ISession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class OnlineServerManager {
public static Map<Integer, ISession> sessionMap = new ConcurrentHashMap<>();
public static void serverOnline(int serverId, ISession session) {
sessionMap.put(serverId, session);
}
public static void checkOnline(){
// UserManager.checkOffline();
}
public static void userOffline(int uid) {
sessionMap.remove(uid);
}
/**
* uidSession
*
* @param uid
* @return
*/
public static ISession getSessionByUid(int uid) {
if (sessionMap == null) {
return null;
}
return sessionMap.get(uid);
}
/**
* 线
*
* @param uid
* @return
*/
public static boolean checkUidOnline(int uid) {
if (sessionMap == null) {
return false;
}
return sessionMap.containsKey(uid);
}
static class DefinaMap<k,v> extends HashMap<k,v>{
@Override
public boolean remove(Object key, Object value) {
return super.remove(key, value);
}
@Override
public v put(k key, v value) {
return super.put(key, value);
}
@Override
public void clear() {
super.clear();
}
}
}

View File

@ -0,0 +1,51 @@
package com.world.network.server;
import com.ljsd.jieling.db.redis.RedisKey;
import com.ljsd.jieling.db.redis.RedisUtil;
import com.ljsd.jieling.netty.cocdex.PacketNetData;
import com.ljsd.jieling.network.session.ISession;
/**
* Description:
* Author: zsx
* CreateDate: 2019/11/20 20:41
*/
class AuthManager {
static boolean auVertiyFromRedis(ISession session, PacketNetData packetNetData) {
int uid = packetNetData.getUserId();
int token = packetNetData.getToken();
session.setUid(uid);
String tokenKey = RedisKey.getKey(RedisKey.TOKEN, String.valueOf(uid), false);
if (tokenKey.isEmpty()) {
return false;
}
String tokenK = (String) RedisUtil.getInstence().get(tokenKey);
if (null == tokenK || tokenK.isEmpty()) {
return false;
}
int serverToken = Integer.parseInt((String) RedisUtil.getInstence().get(tokenKey));
if (token == serverToken) {
session.setToken(token);
session.setUserLoginTime(System.currentTimeMillis());
return true;
}
return false;
}
static boolean auCheck(ISession session, PacketNetData packetNetData) {
if (session.getToken() != packetNetData.getToken()) {
SessionManager.getInstance().serverKick(session,"您的账号token不正确请退出游戏重新登陆!");
return false;
}
boolean b = Blocker.checkForbidUser(session);
if (b) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,55 @@
package com.world.network.server;
import com.ljsd.jieling.exception.ErrorCode;
import com.ljsd.jieling.logic.OnlineUserManager;
import com.ljsd.jieling.network.session.ISession;
import com.ljsd.jieling.util.MessageUtil;
import io.netty.util.internal.ConcurrentSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Description:
* Author: zsx
* CreateDate: 2019/11/5 14:42
*/
public class Blocker {
public static final AtomicInteger maxAllowedOnlineAccountCount = new AtomicInteger(5000);
private static ConcurrentSet<Integer> forbidLogin = new ConcurrentSet<>();
public static boolean checkForbidUser(ISession iSession){
if(forbidLogin.size()<1){
return false;
}
if(iSession!=null) {
if(forbidLogin.contains(iSession.getUid())){
MessageUtil.sendErrorCode(iSession, ErrorCode.reloginCode, "您已被踢下线!");
iSession.setOfflineType(ErrorCode.reloginCode);
return true;
}
}
return false;
}
public static boolean checkFlow(ISession iSession){
if(iSession!=null) {
if(OnlineUserManager.sessionMap.size()>maxAllowedOnlineAccountCount.get()){
MessageUtil.sendErrorCode(iSession, ErrorCode.ONLINE_FLOW.code(), "当前在线人数过多,请稍等哦!");
iSession.setOfflineType(ErrorCode.reloginCode);
return false;
}
}
return true;
}
static Set<Integer> getForbidLogin() {
return forbidLogin;
}
static void setForbidLogin(Set<Integer> forbidLogin) {
Blocker.forbidLogin.clear();
Blocker.forbidLogin.addAll(forbidLogin);
}
}

View File

@ -0,0 +1,147 @@
package com.world.network.server;
import com.WorldServerApplication;
import com.ljsd.jieling.netty.cocdex.PacketNetData;
import com.ljsd.jieling.protocol.ProtocolsAbstract;
import com.world.config.ConfigurableApplicationContextManager;
import com.world.handler.BaseHandler;
import com.world.network.session.ISession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Component;
import rpc.protocols.MessageTypeProto;
import util.ClassLoaderHelper;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
*
* world
*/
@Component
public class ProtocolsManager implements ProtocolsAbstract {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolsManager.class);
private static ProtocolsManager instance = new ProtocolsManager();
private Map<Integer, BaseHandler> handlers = new HashMap<>();
private static ClassLoader classLoader = WorldServerApplication.class.getClassLoader();
public static ProtocolsManager getInstance() {
return instance;
}
private void addHandler(BaseHandler handler) {
if(null==handler.getMessageCode()){
String simpleName = handler.getClass().getSimpleName();
int index = simpleName.indexOf("Handler");
if(index != -1)
{
simpleName = simpleName.substring(0, index);
int number = getProtoIdBySimpleName(simpleName);
if(number == 0){
//没写协议号
return;
}
handlers.put(number, handler);
}
return;
}
handlers.put(handler.getMessageCode().getNumber(), handler);
}
public static int getProtoIdBySimpleName(String name){
try {
MessageTypeProto.MessageType messageType = MessageTypeProto.MessageType.valueOf(name);
return messageType.getNumber();
}catch (IllegalArgumentException e){
return 0;
}
}
public void processMessage(ISession session, PacketNetData packetNetData) {
BaseHandler baseHandler = handlers.get(packetNetData.getMsgId());
if (baseHandler == null) {
//检查一下 是否有getMessageCode()返回null 或者就没有定义handler
try {
// MessageUtil.sendErrorResponse(session, 0, session.getLastMsgId() + 1,"request unknow commond : 通知服务器开发人员");
}catch (Exception e){}
LOGGER.info("request unknow commond : " + packetNetData.getMsgId());
return;
} else {
// addEntry(packetNetData);
}
}
public boolean addEntry(PacketNetData packetNetData) {
// int userId = packetNetData.getUserId();
// try {
//
// HandlerLogicThread handlerThread = handlerThreads[userId % HANDLER_THREAD_NUM];
// if (handlerThread == null) {
// LOGGER.error("addEntry->uid={};handlerThread is null", userId);
// return true;
// }
// handlerThread.addEntry(packetNetData);
// } catch (Exception e) {
// LOGGER.error("addEntry->uid={},mType={};request not return", userId, packetNetData.getMsgId(), e);
// }
return false;
}
public BaseHandler getHandler(int msgNum) {
return handlers.get(msgNum);
}
public void initHandler(String pck){
List<Class<?>> handlers = new LinkedList<>();
try
{
try {
ClassLoaderHelper.findLocalClass(pck, BaseHandler.class, classLoader, handlers);
}catch (RuntimeException e){
}
try {
ClassLoaderHelper.findClassJar(pck, BaseHandler.class, classLoader, handlers);
}catch (RuntimeException e){
}
handlers.forEach(hand ->
{
BaseHandler baseHandler = null;
try {
baseHandler = (BaseHandler) ConfigurableApplicationContextManager.getBean(hand);
} catch (NoSuchBeanDefinitionException e1) {
try {
baseHandler = (BaseHandler) hand.newInstance();
} catch (Exception ex) {
}
} catch (Exception e) {
e.printStackTrace();
}
if (null != baseHandler) {
addHandler(baseHandler);
}
});
}
catch(RuntimeException e2)
{
}
}
}

View File

@ -0,0 +1,201 @@
package com.world.network.server;
import com.google.gson.Gson;
import com.ljsd.jieling.netty.cocdex.PacketNetData;
import com.ljsd.jieling.netty.server.IChannel;
import com.ljsd.jieling.protocol.INetConnet;
import com.ljsd.jieling.protocol.INetReceived;
import com.ljsd.jieling.protocol.INetSession;
import com.ljsd.jieling.protocol.INetWorkHandler;
import com.world.network.OnlineServerManager;
import com.world.network.session.ISession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.protocols.MessageTypeProto;
import util.NetUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Description: session
* <p>
* INetSession session sessionfactory
* INetReceived nett ProtocolsAbstract
* INetConnet ProtocolsAbstract
* <p>
* 1session
* 2session
* <p>
* <p>
* Author: zsx
* CreateDate: 2019/11/5 17:05
*/
public class SessionManager implements INetSession<ISession>, INetReceived<ISession>, INetConnet<ISession>, INetWorkHandler {
private Map<String, ISession> currentSessions = new ConcurrentHashMap<>();
private static final Logger LOGGER = LoggerFactory.getLogger(SessionManager.class);
private static SessionManager instance = new SessionManager();
public static SessionManager getInstance() {
return instance;
}
public void OnsessionAdd(ISession gameSession) {
currentSessions.put(gameSession.getId(),gameSession);
}
@Override
public void OnsessionRemove(String id) {
currentSessions.remove(id);
}
@Override
public void onReceive(ISession session, Object obj) {
PacketNetData packetNetData = new PacketNetData((byte[]) obj);
//处理心跳
if (packetNetData.getMsgId() == MessageTypeProto.MessageType.HEART_BEAT_REQUEST_VALUE) {
dealHeartBeat(session);
return;
}
if (packetNetData.getMsgId() == MessageTypeProto.MessageType.ACK_INDICATION_REQUEST_VALUE) {
ackIndication(session, packetNetData.getIndex());
return;
}
if (checkIndex(session, packetNetData) != 0) {
return;
}
ProtocolsManager.getInstance().processMessage(session,packetNetData);
}
private void dealHeartBeat(ISession session) {
session.setHeartBreatNums(3);
// MessageUtil.sendHeartBeat(session);
}
private void ackIndication(ISession iSession, int ackId) {
LOGGER.info("the uid={},the ackId={}", iSession.getUid(), ackId);
iSession.clearIndication(ackId);
// MessageUtil.sendAck(iSession, ackId);
}
private Gson gson = new Gson();
private int checkIndex(ISession iSession, PacketNetData packetNetData) {
/* if(packetNetData.getMsgId() == MessageTypeProto.MessageType.LOGIN_REQUEST_VALUE || packetNetData.getMsgId() == MessageTypeProto.MessageType.RECONNECT_REQUEST_VALUE){
return 0;
}*/
int index = packetNetData.getIndex();
if (iSession.getIndex() >= index) {
byte[] message = iSession.getCacheMessage(index);
if (message == null) {
//TODO error
LOGGER.info("the uid={},the msg={} is processing,the index={},the sessionIndex={}", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()), index, iSession.getIndex());
return 1;
} else {
LOGGER.info("the uid={},the msg={} reback", iSession.getUid(), MessageTypeProto.MessageType.valueOf(packetNetData.getMsgId()));
iSession.writeAndFlush(message);
return 1;
}
} else {
iSession.setIndex(index);
}
return 0;
}
@Override
public void offLine(ISession session) {
LOGGER.info("player offLine ..{}",session.getUid());
synchronized (session) {
if (session.getUid() == 0) {
LOGGER.error("offLine->uid={}", session.getUid());
return;
}
OnlineServerManager.userOffline(session.getUid());
}
}
@Override
public void readIdel(ISession iSession) {
//对端口扫描直接关闭
if (iSession.getUid() == 0) {
iSession.close();
return;
}
String remoteAddress = "";
if (!iSession.getChannel().isClosed() && iSession.getChannel().isConnected()) {
remoteAddress = NetUtils.toAddressString(iSession.getChannel().getRemoteAddress());
}
LOGGER.error("readIdea->uid={},iSessionId={},HeartBreatNums={},remoteAddress={};not receieve heart breat",
iSession.getUid(), iSession.getId(), iSession.getHeartBreatNums(), remoteAddress);
int heartBreatNums = iSession.getHeartBreatNums();
heartBreatNums--;
if (heartBreatNums <= 0) {
if (!OnlineServerManager.sessionMap.containsKey(iSession.getUid())) {
iSession.close();
return;
}
ISession oldSession = OnlineServerManager.sessionMap.get(iSession.getUid());
if (iSession.getId().equals(oldSession.getId())) {
kickOldUser(iSession.getUid(), "", 000, "LOSE HEART PACKET!!!!", 0);
}
return;
}
iSession.setHeartBreatNums(heartBreatNums);
}
public boolean kickOldUser(int uid, String uToken, int errorCode, String errorMsg, long requestTime) {
if (OnlineServerManager.sessionMap.size() != 0 && OnlineServerManager.sessionMap.keySet().contains(uid)) {
if (requestTime != 0 && requestTime < OnlineServerManager.sessionMap.get(uid).getUserLoginTime()) {
LOGGER.info("kickOldUser->uid={},requestTime={},userLoginTime={}",
uid, requestTime, OnlineServerManager.sessionMap.get(uid).getUserLoginTime());
return false;
}
}
if (!OnlineServerManager.checkUidOnline(uid)) {
LOGGER.info("kickOldUser->uid={};isNotOnline", uid);
return false;
}
ISession oldSession = OnlineServerManager.getSessionByUid(uid);
if (oldSession == null) {
LOGGER.info("kickOldUser->uid={};oldSessionisNull", uid);
OnlineServerManager.userOffline(uid);
return false;
}
oldSession.setOfflineType(errorCode);
offLine(oldSession);
oldSession.close();
return true;
}
@Override
public ISession createGameSession(IChannel channel, INetWorkHandler handler) {
return new ISession(channel, handler);
}
}

View File

@ -0,0 +1,123 @@
package com.world.network.server;
import com.global.thrift.idl.InnerResult;
import com.global.thrift.idl.RPCgTGRequestIFace;
import com.google.protobuf.GeneratedMessage;
import com.ljsd.GameApplication;
import com.ljsd.jieling.config.json.CoreSettings;
import com.ljsd.jieling.thrift.pool.ClientAdapterPo;
import com.ljsd.jieling.util.ConfigurableApplicationContextManager;
import com.world.redis.RedisKey;
import com.world.redis.RedisUtil;
import com.world.thrift.idl.InnerResult;
import com.world.thrift.idl.RPCgTwRequestIFace;
import com.world.thrift.idl.RPCwTgRequestIFace;
import com.world.thrift.idl.pool.ClientAdapterPo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.net.GlobalProtocolsManager;
import rpc.net.RpcMessage;
import rpc.net.gtGBaseHandler;
import rpc.thrift.ServiceKey;
import util.StringUtil;
import java.nio.ByteBuffer;
/**
* Description:
* Author: zsx
* CreateDate: 2020/11/17 19:52
*/
public class gsHelper extends GlobalProtocolsManager {
private static final Logger LOGGER = LoggerFactory.getLogger(gsHelper.class);
public static gsHelper instance = new gsHelper();
private gsHelper() {
}
public static boolean sendMessageToWord(int serverId,int uid, GeneratedMessage message)throws Exception{
ClientAdapterPo<RPCwTgRequestIFace.Client> rPCClient = null;
String rpcString = RedisUtil.getInstence().getObject(RedisKey.LOGIC_SERVER_INFO, String.valueOf(serverId), String.class, -1);
if (null == rpcString) {
LOGGER.error("Exception send err rpcString dsid=>{},uid=>{},cmd=>{}", serverId, uid);
return false;
}
String thriftIp = rpcString.split(":")[0];
String thriftPort = rpcString.split(":")[2];
if (thriftIp == null || thriftIp.isEmpty() || null == thriftPort || thriftPort.isEmpty()) {
return false;
}
String serviceKey = StringUtil.getServiceKey(ServiceKey.RPC_WORLD, thriftIp,thriftPort);
try {
rPCClient = ClientAdapterPo.getClientAdapterPo(serviceKey);
InnerResult innerResult = rPCClient.getClient().messageRequest(uid,getProtoIdBySimpleName(message.getClass().getSimpleName()) , ByteBuffer.wrap(message.toByteArray()));
processMessage( new RpcMessage(0,uid, innerResult.getProtpId(),ByteBuffer.wrap(innerResult.getMessage())));
} catch (Exception e) {
LOGGER.info("callback=>",e);
return false;
}finally {
if (rPCClient != null){
rPCClient.returnObject(serviceKey);
}else{
LOGGER.info("callback=> rPCClient is null ");
}
}
return true;
}
public static void setWorldInfo(WorldInfo worldInfo) {
gsHelper.worldInfo = worldInfo;
}
private static InnerResult processMessage(RpcMessage message) throws Exception {
gtGBaseHandler baseHandler = getHandlers().get(message.getProtpId());
if (baseHandler == null) {
//检查一下 没有定义handler
LOGGER.info("request unknow commond : " + message.getProtpId());
throw new Exception("request unknow commond");
} else {
baseHandler.execute(message);//client not return
return new InnerResult();
}
}
public static class WorldInfo {
String ip;
String port;
int myGroup;
public WorldInfo(String ip, String port, int myGroup) {
this.ip = ip;
this.port = port;
this.myGroup = myGroup;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getMyGroup() {
return myGroup;
}
public void setMyGroup(int myGroup) {
this.myGroup = myGroup;
}
}
}

View File

@ -0,0 +1,165 @@
package com.world.network.session;
import com.ljsd.jieling.netty.NettyGameSession;
import com.ljsd.jieling.netty.server.IChannel;
import com.ljsd.jieling.protocol.INetWorkHandler;
import util.TimeUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class ISession extends NettyGameSession {
private int token;
private int index = -1; //客戶端index
private AtomicInteger indicationIndex = new AtomicInteger(1); //服務端index
private boolean kick;
private int fiveReady; //客户端可以接受服务器5点刷新
private byte[] fiveByteBuf; //五点推送数据缓存
private int lastMsgId;//最后客户端请求协议
private ConcurrentHashMap<Integer, byte[]> indexToMessage = new ConcurrentHashMap();
private ConcurrentHashMap<Integer, IndicationMsg> indexToIndication = new ConcurrentHashMap();
public static class IndicationMsg {
private long create;
private byte[] msg;
private int retryTimes;
public long getCreate() {
return create;
}
public byte[] getMsg() {
return msg;
}
public int getRetryTimes() {
return retryTimes;
}
public void setRetryTimes(int retryTimes) {
this.retryTimes = retryTimes;
}
public IndicationMsg(long crateTime, byte[] msg) {
this.create = crateTime;
this.msg = msg;
}
}
private int heartBreatNums = 3;
//<<<<<<< HEAD
//=======
// public ISession() {
// this.id = UUID.randomUUID().toString();
// this.loginTime = System.currentTimeMillis();
// }
//
// @Override
// public void postClose() {
//>>>>>>> 843e4f921d5bc65ced6568bf5fc4b58b2b17cf54
public ISession(IChannel channel, INetWorkHandler handler) {
super(channel, handler);
}
public int getToken() {
return token;
}
public void setToken(int token) {
this.token = token;
}
public int getHeartBreatNums() {
return heartBreatNums;
}
public void setHeartBreatNums(int heartBreatNums) {
this.heartBreatNums = heartBreatNums;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public boolean isKick() {
return kick;
}
public void setKick(boolean kick) {
this.kick = kick;
}
public ConcurrentHashMap<Integer, byte[]> getIndexToMessage() {
return indexToMessage;
}
public void setIndexToMessage(ConcurrentHashMap<Integer, byte[]> indexToMessage) {
this.indexToMessage = indexToMessage;
}
public void putBackMassageToMap(byte[] backMessage) {
this.indexToMessage.clear();
this.indexToMessage.putIfAbsent(this.index, backMessage);
}
public void putBackIndicationToMap(int index, byte[] backMessage) {
this.indexToIndication.putIfAbsent(index, new IndicationMsg(TimeUtils.now(), backMessage));
}
public void clearIndication(int ackId) {
this.indexToIndication.remove(ackId);
}
public byte[] getCacheMessage(int index) {
return this.indexToMessage.get(index);
}
public ConcurrentHashMap<Integer, IndicationMsg> getIndexToIndication() {
return indexToIndication;
}
public int getIndicationIndex() {
return indicationIndex.getAndIncrement();
}
public int getFiveReady() {
return fiveReady;
}
public void setFiveReady(int fiveReady) {
this.fiveReady = fiveReady;
}
public void updateIndicationIndex(int index) {
this.indicationIndex.set(index);
}
public byte[] getFiveByteBuf() {
return fiveByteBuf;
}
public void setFiveByteBuf(byte[] fiveByteBuf) {
this.fiveByteBuf = fiveByteBuf;
}
public int getLastMsgId() {
return lastMsgId;
}
public void setLastMsgId(int lastMsgId) {
this.lastMsgId = lastMsgId;
}
}

View File

@ -0,0 +1,11 @@
package com.world.network.session;
import com.ljsd.jieling.session.GameSession;
import com.ljsd.jieling.session.GameSessionFactory;
public class ISessionFactory implements GameSessionFactory {
@Override
public GameSession createGameSession() {
return null;
}
}

View File

@ -4,13 +4,6 @@ public class RedisKey {
public final static String Delimiter_colon = ":";
public static final String MATCH_UID_KEY = "MATCH_UID_KEY";
public static final String MATCH_ROOM_KEY = "MATCH_ROOM_KEY";
public static final String BLOODY_ROOM_ID = "BLOODY_ROOM_ID";
public static final String BLOODY_ROOM_ADDRESS = "BLOODY_ROOM_ADDRESS"; //房间服务器地址信息
public static final String USER_LOGIN_URL = "USER_LOGIN_URL"; //房间服务器地址信息
public static final String BLOODY_SERVER_INFO = "BLOODY_SERVER_INFO"; //房间服务器地址信息
public static final String MATCH_SERVER_INFO = "MATCH_SERVER_INFO"; //匹配服务器地址信息
public static final String MATCH_SIZE = "MATCH_SIZE"; //匹配人数设置
public static final String LOGIC_SERVER_INFO = "LOGIC_SERVER_INFO";
}

View File

@ -5,12 +5,14 @@ import com.google.gson.Gson;
import com.world.config.ConfigurableApplicationContextManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Author: zsx
@ -80,6 +82,28 @@ public class RedisUtil {
}
return gson.fromJson(source,clazz);
}
/**
* Object
*
* @param key
* @return
*/
public <T> T getObject(String type, String key, Class<T> clazz, int expireTime) {
try {
String valueStr = redisTemplate.opsForValue().get(type + RedisKey.Delimiter_colon + key);
if (valueStr == null) {
return null;
}
if (expireTime > 0) {
redisTemplate.expire(type + key, expireTime, TimeUnit.SECONDS);
}
return gson.fromJson(valueStr, clazz);
} catch (RedisConnectionFailureException e) {
LOGGER.error("------------------Redis 连接失败------------------msg={}", e);
}
return null;
}
public Long increment(String key) {

View File

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
/**
* Structs can also be exceptions, if they are nasty.
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerInvalidOperException extends TException implements org.apache.thrift.TBase<InnerInvalidOperException, InnerInvalidOperException._Fields>, java.io.Serializable, Cloneable, Comparable<InnerInvalidOperException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerInvalidOperException");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class InnerResult implements org.apache.thrift.TBase<InnerResult, InnerResult._Fields>, java.io.Serializable, Cloneable, Comparable<InnerResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InnerResult");

View File

@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-19")
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2020-11-20")
public class RPCgTwRequestIFace {
public interface Iface {

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,62 @@
package com.world.thrift.idl.pool;
import com.world.thrift.idl.RPCgTwRequestIFace;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.thrift.ServiceKey;
/**
* Created by Administrator on 2015/4/7.
*/
public class ClientAdapterPo<T>{
private static final Logger LOGGER = LoggerFactory.getLogger(ClientAdapterPo.class);
private TTransport tTransport;
private T client;
private final static GenericKeyedObjectPool<String, TTransport> pool = ThriftPoolUtils.getInstance().getThriftPool();
public final static ClientAdapterPo getClientAdapterPo(String key) throws Exception{
ClientAdapterPo clientPo = new ClientAdapterPo();
TTransport transport = pool.borrowObject(key);
TProtocol protocol = new TBinaryProtocol(transport);
Object object = getClientByEnum(key,protocol);
clientPo.setClient(object);
clientPo.settTransport(transport);
return clientPo;
}
private final static Object getClientByEnum(String serviceKey, TProtocol protocol){
String[] key = serviceKey.trim().split("\\|");
if(key[0].equals(ServiceKey.RPC_GS)){
return new RPCgTwRequestIFace.Client(protocol);
}
return null;
}
public void returnObject(String keyEnum){
pool.returnObject(keyEnum,tTransport);
}
private void settTransport(TTransport tTransport) {
this.tTransport = tTransport;
}
public T getClient() {
return client;
}
private void setClient(T client) {
this.client = client;
}
private ClientAdapterPo() {
}
}