增加开箱子登录服代码

main
DESKTOP-C3M45P4\dengdan 2024-11-19 22:55:38 +08:00
parent f214198cfe
commit 12fa14861e
62 changed files with 21216 additions and 3 deletions

8
.gitignore vendored 100644
View File

@ -0,0 +1,8 @@
*.iml
.idea
.gradle
build
out

View File

@ -0,0 +1,2 @@
Manifest-Version: 1.0

View File

@ -1,3 +0,0 @@
# jieling_server
服务器代码

26
build.gradle 100644
View File

@ -0,0 +1,26 @@
group 'loginserver'
version ''
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.8
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
repositories {
//mavenCentral()
maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile("javax.servlet:servlet-api:2.5")
compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.6.3'
compile("ch.qos.logback:logback-core:1.1.11")
compile("ch.qos.logback:logback-classic:1.1.11")
compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.47'
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored 100644

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Thu Jul 21 18:25:36 CST 2022
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-bin.zip

172
gradlew vendored 100644
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored 100644
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle 100644
View File

@ -0,0 +1,2 @@
rootProject.name = 'loginserver'

View File

@ -0,0 +1,57 @@
package com.ljsd.controller;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.MongoKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class CheckVersionController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(CheckVersionController.class);
public CheckVersionController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
DBObject dbObject = BaseGlobal.mongoDBPool.findOne(MongoKey.VERSION, "1");
DBObject res = new BasicDBObject();
res.put("resource_version", dbObject.get("resource_version"));
res.put("application_version", dbObject.get("application_version"));
LOGGER.debug("resource_version={},application_version={}", dbObject.get("resource_version"), dbObject.get("application_version"));
PrintWriter out = response.getWriter();
out.print(res);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,70 @@
package com.ljsd.controller;
import com.ljsd.pojo.UserServerInfo;
import com.ljsd.redis.RedisKey;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.BaseGlobal;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author gaojie
* @version V1.0
* @className ClientReportController
* @packageName com.ljsd.controller
* @description
* @date 2022-03-01 9:49
* copyright(c) 2020-2030
**/
public class ClientReportController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientReportController.class);
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String device = request.getParameter("device");
Map<String, Integer> reportMap = BaseGlobal.redisApp.hgetAll(RedisKey.CLIENT_REPORT_KEY, "", Integer.class, -1, true);
boolean isReport = false;
if (reportMap.containsKey(device)){
isReport = true;
}
DBObject resp = new BasicDBObject();
resp.put("is_report", isReport);
LOGGER.info("clientReport===>device={},isReport={}",device,isReport);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(resp);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,92 @@
package com.ljsd.controller;
import com.ljsd.pojo.LoginServerInfo;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.HttpClient;
import com.ljsd.util.LoginUtil;
import com.ljsd.util.MongoKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author gaojie
* @version V1.0
* @className GetLoginServerController
* @packageName com.ljsd.controller
* @description
* @date 2020-11-06 13:36
* copyright(c) 2020-2030
**/
public class GetLoginServerController extends HttpServlet {
public GetLoginServerController() {
super();
}
private static final Logger LOGGER = LoggerFactory.getLogger(GetLoginServerController.class);
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String plat = request.getParameter("plat");
String channel = request.getParameter("channel");
String itversion = request.getParameter("sub_channel");
//设备号id 用于白名单
String ipAddress = HttpClient.getIPAddress(request);
LOGGER.info("GetLoginServerController==>,plat={},channel={},itversion={},ipAddress={} ",
plat, channel, itversion, ipAddress);
DBObject whiteInfo = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, "2");
boolean isWhiteIp = LoginUtil.checkIpIsWhiteList(ipAddress, whiteInfo);
int isWhite = 1;
if (isWhiteIp) {
// 测试环境
isWhite = 0;
}
String key = itversion + ":" + plat + ":" + channel + ":" + isWhite;
LoginServerInfo loginServerInfo = ServerManager.loginServerInfoMap.get(key);
DBObject resp = new BasicDBObject();
if (loginServerInfo != null) {
resp.put("login_url", loginServerInfo.getLoginServerUrl());
resp.put("res", loginServerInfo.getResUrl());
} else {
resp.put("login_url", "");
resp.put("res", "");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(resp);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,104 @@
package com.ljsd.controller;
import com.ljsd.sdk.KSManager;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.GlobalVersion;
import com.ljsd.util.HttpClient;
import com.ljsd.util.LoginUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
/**
* @author gaojie
* @version V1.0
* @className GetMyServerInfoController
* @packageName com.ljsd.controller
* @description
* @date 2022-07-07 10:20
* copyright(c) 2020-2030
**/
public class GetMyServerInfoController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginSDKController.class);
public GetMyServerInfoController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String openId = request.getParameter("openId");
String sessionId = request.getParameter("sessionId");
String ipAddress = HttpClient.getIPAddress(request);
LOGGER.info("GetMyServerInfoController==>,openId={},sessionId={},ipAddress={}", openId, sessionId,ipAddress);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
try {
DBObject resp = new BasicDBObject();
if (!KSManager.btLoginVerify(openId, sessionId)) {
resp.put("result", 1);
resp.put("error", "verify error !!");
out.print(resp);
out.flush();
return;
}
List<DBObject> myServerList = LoginUtil.createMyServerList(openId);
DBObject recommendServer = LoginSDKController.recommendServerList();
List<DBObject> serverList = new ArrayList<>();
if (recommendServer != null){
serverList.add(ServerManager.serverMapById.get(recommendServer.get("server_id").toString()));
}
for (DBObject dbObject : myServerList){
String serverId = dbObject.get("server_id").toString();
DBObject server = ServerManager.serverMapById.get(serverId);
if (server == null){
continue;
}
serverList.add(server);
}
resp.put("result", 0);
resp.put("myServerList", myServerList);
resp.put("recommendServerList", recommendServer);
resp.put("serverList", serverList);
out.print(resp);
out.flush();
} catch (Exception e) {
LOGGER.info("error,version={}", GlobalVersion.getServerVersion(), e);
e.printStackTrace();
} finally {
out.close();
}
}
public List<DBObject> getServerListByGroupId(int groupId) {
List<DBObject> dbObjects = new ArrayList<>();
for (DBObject dbObject : ServerManager.servers) {
int state = Integer.parseInt(dbObject.get("state").toString());
if (state != 0) {
continue;
}
int groupIdFromDb = Integer.parseInt(dbObject.get("groupId").toString());
if (groupIdFromDb == groupId) {
dbObjects.add(dbObject);
}
}
return dbObjects;
}
}

View File

@ -0,0 +1,79 @@
package com.ljsd.controller;
import com.ljsd.pojo.PlatformServerinfo;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.HttpClient;
import com.ljsd.util.LoginUtil;
import com.ljsd.util.MongoKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class GetServerController extends HttpServlet {
public GetServerController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// String channel = request.getParameter("channel");
String channel = "ljsd";
String platform = request.getParameter("plat");
String ipaddress = HttpClient.getIPAddress(request);
DBObject whiteInfo = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, "2");
boolean isWhiteIp = LoginUtil.checkIpIsWhiteList(ipaddress,whiteInfo);
if (isWhiteIp){
platform = platform + "_test";
}
String key = channel+"-"+platform;
DBObject resp = new BasicDBObject();
PlatformServerinfo pt = ServerManager.platServerinfo.get(key);
if(null != pt)
{
resp.put("app_version", pt.getApp_version());
resp.put("res_version", pt.getRes_version());
resp.put("res", pt.getRes_url());
}
else
{
resp.put("error", "param is error,plat:"+platform);
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(resp);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,262 @@
package com.ljsd.controller;
import com.ljsd.redis.RedisKey;
import com.ljsd.sdk.KSManager;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class GetUserController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(GetUserController.class);
public GetUserController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long nowTime = System.currentTimeMillis();
String openId = request.getParameter("openId");
String serverId = request.getParameter("serverId");
String version = request.getParameter("version");
String channel = request.getParameter("channel");
String device = request.getParameter("device");
if (null == device || device.isEmpty()) {
device = "";
}
String ipAddress = HttpClient.getIPAddress(request);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
LOGGER.info("GetUserController==>start,openId={},serverId={},version={},channel={},ipAddress={} ",
openId, serverId, version, channel, ipAddress);
DBObject res = new BasicDBObject();
PrintWriter out = response.getWriter();
if (null == openId || openId.isEmpty()) {
res.put("result", 1);
res.put("error", "parmeter error!!");
out.print(res);
out.flush();
return;
}
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", openId);
boolean isWhite;
try {
if (serverId == null) {
res.put("result", 1);
res.put("error", "亲爱的镇魂将,请求参数有误");
out.print(res);
out.flush();
return;
}
isWhite = LoginUtil.isWhiteUser(openId, ipAddress, device);
// 检查服务器状态
DBObject server = ServerManager.getServer(serverId);
if (server == null) {
res.put("result", 1);
res.put("error", "亲爱的镇魂将,您选择的服务器未开启");
out.print(res);
out.flush();
return;
}
//维护状态:正常玩家可见不可进,白名单可见可进
int upHoldState = 4;
//白名单状态(新服):正常玩家不可见不可进,白名单见可进
int whiteState = 3;
String state = "state";
// 未开服
if (Integer.parseInt(server.get(state).toString()) == upHoldState) {
if (!isWhite) {
res.put("result", 1);
res.put("error", "当前服务器正在维护中,具体开启时间请您关注公告");
out.print(res);
out.flush();
return;
}
}
// 检查白名单
if (Integer.parseInt(server.get(state).toString()) == whiteState) {
if (!isWhite) {
res.put("result", 1);
res.put("error", "服务器未开启,敬请期待!");
out.print(res);
out.flush();
return;
}
}
// 检查白名单
if (Integer.parseInt(server.get(state).toString()) == -1) {
if (!isWhite) {
res.put("result", 1);
res.put("error", "服务器未开启,敬请期待!");
out.print(res);
out.flush();
return;
}
}
// if (!ServerManager.serverIsOpen(serverId)) {
// res.put("result", 1);
// res.put("error", "当前服务器正在维护中,具体开启时间请您关注公告");
// out.print(res);
// out.flush();
// return;
// }
String openTime = "open_time";
String closeTime = "closeTime";
//验证是否在当前开服时间段内
if (!TimeUtil.inCorrectTime(String.valueOf(server.get(openTime)), String.valueOf(server.get(closeTime)))) {
if (!isWhite) {
res.put("result", 1);
res.put("error", "服务器将于" + server.get(openTime) + "时开启,请您耐心等待");
out.print(res);
out.flush();
return;
}
}
Integer uid = null;
try {
boolean getUserLock = BaseGlobal.redisApp.tryGetDistributedLock(RedisKey.USER_LOGIN_LOCK, openId, openId, 2000);
if (!getUserLock) {
res.put("result", 1);
res.put("error", "登录繁忙");
out.print(res);
out.flush();
LOGGER.error("玩家获取锁失败---openId={}", openId);
return;
}
List<DBObject> userInfos = BaseGlobal.mongoDBPool.find(MongoKey.USER_INFO, dbObject);
if (userInfos.isEmpty()) {
dbObject.put("_id", openId);
userInfos.add(dbObject);
}
dbObject = userInfos.get(0);
uid = (Integer) dbObject.get(serverId);
if (uid == null) {
Boolean isCanRegister = BaseGlobal.redisApp.get(RedisKey.SERVER_REGISTER_STATE, String.valueOf(serverId), Boolean.class, -1
, true);
if (null != isCanRegister && !isCanRegister) {
res.put("result", 1);
res.put("error", "非常报歉,该服务器注册已关闭,请联系管理员!");
out.print(res);
out.flush();
return;
}
//判断服务器是否达到注册人数上限
Integer registCount = BaseGlobal.redisApp.get(RedisKey.REGIST_NUM, String.valueOf(serverId), Integer.class, -1, false);
if (registCount == null) {
registCount = 0;
}
Integer maxRegister = Integer.valueOf(String.valueOf(server.get("max_register")));
if (maxRegister == null) {
maxRegister = 1050;
}
if (registCount != null && registCount >= maxRegister) {
// 2 为状态选择其他服务器
res.put("result", 1);
res.put("error", "当前服务器已达注册上限,请您选择其他服务器进行游戏");
out.print(res);
out.flush();
return;
}
// 注册人满 后自动开下个服 默认1000开一个服
if (registCount + 1 >= maxRegister - 50 && "1".equals(KSManager.OPEN_SERVER_STRATEGY)) {
openNextServer(String.valueOf(server.get("server_id")));
}
uid = BaseGlobal.mongoDBPool.inc("uid");
dbObject.put(serverId, uid);
userInfos.add(dbObject);
BaseGlobal.mongoDBPool.save(MongoKey.USER_INFO, dbObject);
//渠道注册人数
BaseGlobal.redisApp.incr(channel, RedisKey.SUBCHANNEL_REGISTER_NUM);
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("玩家注册异常 openId={} ", openId, e);
} finally {
BaseGlobal.redisApp.releaseDistributedLock(RedisKey.USER_LOGIN_LOCK, openId, openId);
}
Random random = new Random();
int token = random.nextInt();
BaseGlobal.redisApp.set(RedisKey.TOKEN, String.valueOf(uid), token, RedisKey.TOKEN_EXPIRE, false);
boolean exists = BaseGlobal.redisApp.exists(RedisKey.UID, String.valueOf(uid), false);
if (!exists) {
BaseGlobal.redisApp.set(RedisKey.UID, String.valueOf(uid), serverId + "_" + openId, -1, false);
}
LOGGER.info("GetUserController==>uid={},info={},exists={}", uid, serverId + "_" + openId, exists);
res.put("result", 0);
res.put("uid", uid);
res.put("token", token);
LOGGER.info("GetUserController==>end,openId={},res={},costTime={}", openId, res.toString(), System.currentTimeMillis() - nowTime);
out.print(res);
out.flush();
} catch (Exception e) {
LOGGER.debug("error ", e);
e.printStackTrace();
} finally {
out.close();
}
}
public static void openNextServer(String serverId) throws Exception {
String nextOpenServerId = String.valueOf(Integer.valueOf(serverId) + 1);
DBObject one = ServerManager.getServer(nextOpenServerId);
if (one == null) {
LOGGER.info("openNextServer==>serverId={},nextOpenServerId={},nextOpenServerId is null",serverId,nextOpenServerId);
BaseGlobal.redisApp.set(RedisKey.RECOMMEND_ID, "", nextOpenServerId, -1, false);
return;
}
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("server_id", serverId);
BasicDBObject dbObject = new BasicDBObject();
dbObject.append("$set", new BasicDBObject().append("recommend", 0));
BaseGlobal.mongoDBPool.updateValue(MongoKey.SERVER_INFO, searchQuery, dbObject);
int state = Integer.parseInt(one.get("state").toString());
if (state != -1){
return;
}
searchQuery = new BasicDBObject();
searchQuery.put("server_id", nextOpenServerId);
dbObject = new BasicDBObject();
long openTime = TimeUtil.getNowDayTimeStamp(System.currentTimeMillis());
dbObject.append("$set", new BasicDBObject().append("recommend", 1).append("state", 0).append("open_time", TimeUtil.timeStamp2Date(openTime)));
//设置开服时间
LoginUtil.setOpenTime(String.valueOf(one.get("server_id")),openTime);
BaseGlobal.mongoDBPool.updateValue(MongoKey.SERVER_INFO, searchQuery, dbObject);
LOGGER.info("openNextServer==>serverId={},nextOpenServerId={},",serverId,nextOpenServerId);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,27 @@
package com.ljsd.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class IndexController extends HttpServlet {
public IndexController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("/index.jsp");
}
}

View File

@ -0,0 +1,242 @@
package com.ljsd.controller;
import com.ljsd.redis.RedisKey;
import com.ljsd.sdk.KSManager;
import com.ljsd.timer.ServerManager;
import com.ljsd.util.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Tuple;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class LoginSDKController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginSDKController.class);
public LoginSDKController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
//0正常 1用户不存在
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String openId = request.getParameter("openId");
String sessionId = request.getParameter("sessionId");
String channel = request.getParameter("channel");
String itversion = request.getParameter("sub_channel");
String plat = request.getParameter("plat");
String market = request.getParameter("market");
String device = request.getParameter("device");
String id = request.getParameter("areaId");
int areaId = 0 ;
if (id != null){
areaId = Integer.parseInt(id);
}
if (null == market || market.isEmpty()) {
market = "";
}
if (null == device || device.isEmpty()) {
device = "";
}
String ipAddress = HttpClient.getIPAddress(request);
LOGGER.info("LoginSDKController==>,openId={},sessionId={},channel={},subChannel={},plat={},ipAddress={},market={},device={} ",
openId, sessionId, channel, itversion, plat, ipAddress, market, device);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
try {
DBObject resp = new BasicDBObject();
if (openId == null || "".equals(openId)) {
resp.put("result", 1);
resp.put("error", "openid is null");
out.print(resp);
out.flush();
return;
}
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", openId);
List<DBObject> userInfos = BaseGlobal.mongoDBPool.find(MongoKey.USER_INFO, dbObject);
if (!KSManager.btLoginVerify(openId, sessionId)) {
resp.put("result", 1);
resp.put("error", "verify error !!");
out.print(resp);
out.flush();
return;
}
if (userInfos.size() == 0) {
BaseGlobal.mongoDBPool.save(MongoKey.USER_INFO, dbObject);
}
boolean isWhite = LoginUtil.isWhiteUser(openId, ipAddress, device);
if (!market.isEmpty()) {
channel = channel + "@" + market;
}
List<DBObject> serverList = createServerList(channel, itversion, plat, isWhite,areaId);
// List<DBObject> myServerList = LoginUtil.createMyServerList(openId);
//
// List<DBObject> recommendServerList = recommendServerList(serverList);
resp.put("result", 0);
resp.put("serverList", serverList);
// resp.put("myServerList", myServerList);
// resp.put("recommendServerList", recommendServerList);
out.print(resp);
out.flush();
} catch (Exception e) {
LOGGER.info("error,version={}", GlobalVersion.getServerVersion(), e);
e.printStackTrace();
} finally {
out.close();
}
}
public static List<DBObject> recommendServerList(List<DBObject> serverList) throws Exception {
List<DBObject> recommendServers = new ArrayList<>(ServerManager.recommendServers);
List<DBObject> recommendServerList = new ArrayList<>();
for (DBObject dbObject : recommendServers) {
DBObject server = new BasicDBObject();
server.put("server_id", dbObject.get("server_id"));
server.put("pcu", ServerManager.totalCount(String.valueOf(dbObject.get("server_id"))));
server.put("groupId",dbObject.get("groupId"));
recommendServerList.add(server);
}
// if (serverList.size() == 0) {
// return recommendServerList;
// }
// // 没有设置推荐服按照时间最大的为推荐服
// if (recommendServers.size() == 0) {
// serverList.sort((o1, o2) -> (int) ((long) o2.get("open_time") / 1000) - (int) ((long) o1.get("open_time") / 1000));
// DBObject server = new BasicDBObject();
// server.put("server_id", serverList.get(0).get("server_id"));
// recommendServerList.add(server);
// return recommendServerList;
// }
// for (DBObject dbObject : recommendServers) {
// String serverId = String.valueOf(dbObject.get("server_id"));
// Integer registCount = BaseGlobal.redisApp.get(RedisKey.REGIST_NUM, String.valueOf(serverId), Integer.class, -1, false);
// if (null == registCount) {
// registCount = 0;
// }
// dbObject.put("registCount", registCount);
// }
// // 设置推荐服按照注册人数最小的为推荐服
// recommendServers.sort((o1, o2) -> (int) o2.get("registCount") - (int) o1.get("registCount"));
// DBObject serverInfo = recommendServers.get(recommendServers.size() - 1);
// DBObject server = new BasicDBObject();
// server.put("server_id", serverInfo.get("server_id"));
// recommendServerList.add(server);
return recommendServerList;
}
public static DBObject recommendServerList() throws Exception {
List<DBObject> recommendServers = new ArrayList<>(ServerManager.recommendServers);
for (DBObject dbObject : recommendServers) {
DBObject server = new BasicDBObject();
server.put("server_id", dbObject.get("server_id"));
server.put("groupId",dbObject.get("groupId"));
long time = Long.parseLong(TimeUtil.date3TimeStamp(String.valueOf(dbObject.get("open_time"))));
server.put("open_time", time);
return server;
}
return null;
}
public static List<DBObject> createServerList(String channel, String itversion, String plat, boolean isWhite,int areaId) throws Exception {
DBObject req = new BasicDBObject();
req.put("channel", channel);
req.put("itversion", itversion);
req.put("plat", plat);
List<String> serverInfoList = ServerManager.getServerList(req);
List<DBObject> serverList = new ArrayList<>();
for (String serverId : serverInfoList) {
DBObject serverInfo = ServerManager.getServerById(serverId);
int state = Integer.parseInt(serverInfo.get("state").toString());
// 白名单状态非白名单用户不能看到服务器列表
if (state == 3 && !isWhite) {
continue;
}
// -1 不对外
if (state == -1 && !isWhite){
continue;
}
// 维护状态,白名单用户服务器正常
if (state == 4 && isWhite) {
state = 0;
}
int groupId = Integer.parseInt(serverInfo.get("groupId").toString());
if (areaId != 0 && areaId != groupId){
continue;
}
DBObject server = new BasicDBObject();
server.put("state", state);
server.put("name", serverInfo.get("name"));
setIpAndPort(server, serverInfo);
server.put("server_id", serverInfo.get("server_id"));
long time = Long.parseLong(TimeUtil.date3TimeStamp(String.valueOf(serverInfo.get("open_time"))));
server.put("open_time", time);
server.put("area_name", serverInfo.get("groupId"));
server.put("recommend", serverInfo.get("recommend"));
server.put("isNew", serverInfo.get("isNew"));
server.put("groupId", serverInfo.get("groupId"));
String displayId = "";
if (null != serverInfo.get("display_id")) {
displayId = String.valueOf(serverInfo.get("display_id"));
}
server.put("display_id", displayId);
serverList.add(server);
}
return serverList;
}
public static void setIpAndPort(DBObject server, DBObject serverInfo) throws Exception {
String serverId = String.valueOf(serverInfo.get("server_id"));
long nowTime = System.currentTimeMillis();
List<String> ipAddressList = new ArrayList<>();
Set<Tuple> tuples = BaseGlobal.redisApp.zrangeWithScores(serverId, RedisKey.GATEWAY_ADDRESS_LIST);
for (Tuple tuple : tuples) {
String address = tuple.getElement();
long score = (long) tuple.getScore();
if ((nowTime - score) > 2 * 60 * 1000) {
continue;
}
ipAddressList.add(address);
}
if (ipAddressList.size() <= 1) {
server.put("ip", serverInfo.get("ip"));
server.put("port", serverInfo.get("port"));
} else {
Random r = new Random();
int index = r.nextInt(ipAddressList.size());
String info = ipAddressList.get(index);
String[] split = info.split(":");
server.put("ip", split[0]);
server.put("port", split[1]);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,89 @@
package com.ljsd.controller;
import com.ljsd.timer.ServerManager;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UnknownFormatConversionException;
public class NoticeController extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginSDKController.class);
public NoticeController() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String itversion = request.getParameter("itversion");
String channel = request.getParameter("channel");
String market = request.getParameter("market");
if (null == market || market.isEmpty()){
market = "";
}
String key = channel + "@" + market;
Map<String, List<DBObject>> noticeMap = ServerManager.noticeMap;
List<DBObject> noticeList = new ArrayList<>();
for (Map.Entry<String, List<DBObject>> entry: noticeMap.entrySet()){
String key1 = entry.getKey();
List<DBObject> value = entry.getValue();
if (key.contains(key1)){
for (DBObject data : value){
if((int)data.get("ifOpen") == 0) {
continue;
}
DBObject notice = new BasicDBObject();
notice.put("id", data.get("_id"));
notice.put("type", data.get("type"));
notice.put("pic", data.get("pic"));
notice.put("name", data.get("name"));
notice.put("content", data.get("content"));
notice.put("isNew", data.get("isNew"));
notice.put("weight",data.get("weight"));
if (noticeList.contains(notice)){
continue;
}
noticeList.add(notice);
}
}
}
noticeList.sort((o1, o2) -> (int) o2.get("weight") - (int) o1.get("weight"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
DBObject resp = new BasicDBObject();
resp.put("noticeList", noticeList);
out.print(resp);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

View File

@ -0,0 +1,92 @@
package com.ljsd.listener;
import com.ljsd.timer.ServerManager;
import com.ljsd.timer.UpdateServerNameThread;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.LogBackConfigLoader;
import com.ljsd.util.MongoKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.FileInputStream;
//创建的类名根据需要定义但一定要实现ServletContextListener接口
public class WebContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ServletContextListener.class);
private static final String DEFAULT_CONFIG_PATH = "/application.properties";
@Override
public void contextInitialized(ServletContextEvent event) {
try {
String path=System.getProperty("catalina.home");
path += "/config/loginserver/application.properties";
FileInputStream inputStream = new FileInputStream(path);
// InputStream inputStream = getClass().getResourceAsStream(path);
LogBackConfigLoader.load();
if (inputStream != null) {
BaseGlobal.properties.load(inputStream);
}
BaseGlobal.init();
DBObject dbObject = BaseGlobal.mongoDBPool.findOne(MongoKey.INC_C, "inc_k");
if (dbObject == null) {
int startUid = Integer.parseInt(BaseGlobal.properties.getProperty("start_uid"));
dbObject = new BasicDBObject();
dbObject.put("_id", "inc_k");
dbObject.put("uid", startUid);
dbObject.put("server_id", 0);
BaseGlobal.mongoDBPool.save(MongoKey.INC_C, dbObject);
}
//Object uid = dbObject.get("uid");
// dbObject = new BasicDBObject();
// dbObject.put("_id", "1");
// dbObject.put("resource_version", "1.0.0.0");
// dbObject.put("application_version", "1.0.0.0");
// BaseGlobal.mongoDBPool.save("version", dbObject);
// STableManager.init(event.getServletContext());
new ServerManager().start();
new UpdateServerNameThread().start();
// 添加渠道白名单
addChannelWhites();
} catch (Exception ex) {
LOGGER.error("error",ex);
ex.printStackTrace();
}
}
private void addChannelWhites() {
String channel = "ljsd2";
for(int i = 1; i <= 20; i++) {
String openId;
if(i >= 10) {
openId = "Zhjwsqww0"+i;
} else {
openId = "Zhjwsqww00"+i;
}
DBObject channelWhite = new BasicDBObject();
channelWhite.put("_id", openId);
channelWhite.put("channel", channel);
BaseGlobal.mongoDBPool.save(MongoKey.CHANNEL_WHITE, channelWhite);
}
DBObject channelWhite1 = new BasicDBObject();
channelWhite1.put("_id", "Zhj01");
channelWhite1.put("channel", channel);
BaseGlobal.mongoDBPool.save(MongoKey.CHANNEL_WHITE, channelWhite1);
DBObject channelWhite2 = new BasicDBObject();
channelWhite2.put("_id", "Zhj02");
channelWhite2.put("channel", channel);
BaseGlobal.mongoDBPool.save(MongoKey.CHANNEL_WHITE, channelWhite2);
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,219 @@
package com.ljsd.pojo;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class AccountInfo {
private String openId; //外部ID
private int exp; //经验
private long createTime; //创建账号时间
private String name;//昵称
private int head;//头像
private int frame;//头像框
private int level; //玩家等级
private int playerST;//国战玩家状态
//private List<Integer> guide;
private int hellLevel; // 地狱道等级
//private List<Integer> weakGuide = new ArrayList<>();//弱引导
private int question = 0;//问卷
private int unionId = 0;//联盟id
private int serverId = 0;//服务器id
private int vipLevel = 0;//vip等级
private long beforeLevelTime = 0;//升级时间
private int changeNameNum = 0;//改名次数
private long offlineTime = 0;//下线时间
/**
*
*/
private long shareTime = 0;
/**
* key:cardType_cardQuality value
*/
private Map<String,Integer> shareNumMap = new HashMap<>();
/**
*
*/
private long allCap = 0;
/**
*
*/
private String userDataVersion;
/**
*
*/
private String channel;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHead() {
return head;
}
public void setHead(int head) {
this.head = head;
}
public int getFrame() {
return frame;
}
public void setFrame(int frame) {
this.frame = frame;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getPlayerST() {
return playerST;
}
public void setPlayerST(int playerST) {
this.playerST = playerST;
}
public int getHellLevel() {
return hellLevel;
}
public void setHellLevel(int hellLevel) {
this.hellLevel = hellLevel;
}
public int getQuestion() {
return question;
}
public void setQuestion(int question) {
this.question = question;
}
public int getUnionId() {
return unionId;
}
public void setUnionId(int unionId) {
this.unionId = unionId;
}
public int getServerId() {
return serverId;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
public int getVipLevel() {
return vipLevel;
}
public void setVipLevel(int vipLevel) {
this.vipLevel = vipLevel;
}
public long getBeforeLevelTime() {
return beforeLevelTime;
}
public void setBeforeLevelTime(long beforeLevelTime) {
this.beforeLevelTime = beforeLevelTime;
}
public int getChangeNameNum() {
return changeNameNum;
}
public void setChangeNameNum(int changeNameNum) {
this.changeNameNum = changeNameNum;
}
public long getOfflineTime() {
return offlineTime;
}
public void setOfflineTime(long offlineTime) {
this.offlineTime = offlineTime;
}
public long getShareTime() {
return shareTime;
}
public void setShareTime(long shareTime) {
this.shareTime = shareTime;
}
public Map<String, Integer> getShareNumMap() {
return shareNumMap;
}
public void setShareNumMap(Map<String, Integer> shareNumMap) {
this.shareNumMap = shareNumMap;
}
public long getAllCap() {
return allCap;
}
public void setAllCap(long allCap) {
this.allCap = allCap;
}
public String getUserDataVersion() {
return userDataVersion;
}
public void setUserDataVersion(String userDataVersion) {
this.userDataVersion = userDataVersion;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
}

View File

@ -0,0 +1,32 @@
package com.ljsd.pojo;
/**
* @author gaojie
* @version V1.0
* @className LoginServerInfo
* @packageName com.ljsd.pojo
* @description
* @date 2020-11-06 13:52
* copyright(c) 2020-2030
**/
public class LoginServerInfo {
private String resUrl ="";
private String loginServerUrl;
public LoginServerInfo(String loginServerUrl,String resUrl){
this.loginServerUrl = loginServerUrl;
this.resUrl = resUrl;
}
public String getLoginServerUrl() {
return loginServerUrl;
}
public String getResUrl() {
return resUrl;
}
}

View File

@ -0,0 +1,68 @@
package com.ljsd.pojo;
public class Notice {
private int _id;
private int type;
private String pic;
private String name;
private String content;
private int isNew;
private int ifOpen;
public int get__id() {
return _id;
}
public void set__id(int _id) {
this._id = _id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getpic() {
return pic;
}
public void setpic(String pic) {
this.pic = pic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
public int getIfOpen() {
return ifOpen;
}
public void setIfOpen(int ifOpen) {
this.ifOpen = ifOpen;
}
}

View File

@ -0,0 +1,39 @@
package com.ljsd.pojo;
import java.util.HashMap;
/**
* @version V1.0
* @ClassName: PlatformServerinfo
* @Package com.ljsd.pojo
* @Description: ${TODO}
* @Author: zw
* @date: 2020/6/1 14:01
*/
public class PlatformServerinfo {
//平台类型
private String app_version="";
private String res_version="";
private String res_url="";
public String getApp_version() {
return app_version;
}
public String getRes_version() {
return res_version;
}
public String getRes_url() {
return res_url;
}
public PlatformServerinfo(String app_version, String res_version, String res_url)
{
this.app_version = app_version;
this.res_version = res_version;
this.res_url = res_url;
}
}

View File

@ -0,0 +1,45 @@
package com.ljsd.pojo;
/**
* @version V1.0
* @ClassName: ServerAddress
* @Package com.ljsd.pojo
* @Description: ${TODO}
* @Author: zw
* @date: 2020/6/1 14:01
*/
public class ServerAddress {
private String ip;
private int port;
public ServerAddress(){}
public ServerAddress(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public String toString() {
return "ServerAddress{" +
"ip='" + ip + '\'' +
", port=" + port +
'}';
}
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setPort(int port) {
this.port = port;
}
}

View File

@ -0,0 +1,40 @@
package com.ljsd.pojo;
public class UserServerInfo {
private long loginTime;
private int level;
private int head;//头像
private int frame;//头像框
public long getLoginTime() {
return loginTime;
}
public void setLoginTime(long loginTime) {
this.loginTime = loginTime;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getHead() {
return head;
}
public void setHead(int head) {
this.head = head;
}
public int getFrame() {
return frame;
}
public void setFrame(int frame) {
this.frame = frame;
}
}

View File

@ -0,0 +1,316 @@
package com.ljsd.redis;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Tuple;
import java.util.*;
public class RedisApp {
private final static String Delimiter_colon = ":";
private RedisUtil redisUtil = new RedisUtil();
public RedisApp() {
redisUtil.init();
}
private <K, T> String getKey(String type, K key, boolean withServerId) {
if (withServerId) {
String areaId = "common";
return areaId + Delimiter_colon + type + Delimiter_colon + String.valueOf(key);
} else {
return type + Delimiter_colon + String.valueOf(key);
}
}
/***************************************普通键值对操作***************************************/
//设置键值
public <K, T> void set(final String type, final K key, T value, final int seconds, boolean withServerId) throws Exception {
String strValue = JSON.toJSONString(value);
String fullKey = getKey(type, key, withServerId);
if (seconds <= 0) {
redisUtil.set(fullKey, strValue);
} else {
redisUtil.setex(fullKey, seconds, strValue);
}
}
public <T> void set(final String type, final String key, T value, final int seconds) throws Exception {
set(type, key, value, seconds, true);
}
//取得键值
public <K, T> T get(final String type, final K key, final Class<T> clazz, final int seconds,
boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
String strValue = redisUtil.get(fullKey);
if (strValue == null) {
return null;
}
return JSON.parseObject(strValue, clazz);
}
public <K, T> T get(final String type, final K key, final Class<T> clazz, final int seconds) throws Exception {
return get(type, key, clazz, seconds, true);
}
//取得键值
public <K, T> void del(final String type, final K key, final boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
redisUtil.del(fullKey);
}
public <K, T> void del(final String type, final K key) throws Exception {
del(type, key, true);
}
public <K> boolean exists(final String type, final K key, final boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
return redisUtil.exists(fullKey);
}
public <K> boolean exists(final String type, final K key) throws Exception {
return exists(type, key, true);
}
//设置过期时间
public <K, T> void expire(final String type, final K key, final int seconds, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
redisUtil.expire(fullKey, seconds);
}
public void expire(final String type, final String key, final int seconds) throws Exception {
expire(type, key, seconds, true);
}
/***************************************以下是map操作***************************************/
//转换map对象类型
private <K, T> Map<String, String> converStringMap(Map<K, T> mapValues) {
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<K, T> entry : mapValues.entrySet()) {
String strKey = String.valueOf(entry.getKey());
String strValue = JSON.toJSONString(entry.getValue());
map.put(strKey, strValue);
}
return map;
}
//设置map的
public <K, T> void hmset(final String type, final K key, final Map<K, T> hash, int seconds,
boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
Map<String, String> strHash = converStringMap(hash);
redisUtil.hmset(fullKey, strHash, seconds);
}
public <K, T> void hmset(final String type, final K key, final Map<K, T> hash, final int seconds) throws Exception {
hmset(type, key, hash, seconds, true);
}
//取得map下的子key
public <K> Set<String> hkeys(final String type, final K key, final int seconds, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
return redisUtil.hkeys(fullKey);
}
public <K> Set<String> hkeys(final String type, final K key, final int seconds) throws Exception {
return hkeys(type, key, seconds, true);
}
//设置redis map一个键值 下的子key下的值
public <K, T> void hset(final String type, final K key, final String field, final T value, int seconds,
boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
String strValue = JSON.toJSONString(value);
redisUtil.hset(fullKey, field, strValue, seconds);
}
public <K, T> void hset(final String type, final K key, final String field, final T value, int seconds) throws Exception {
hset(type, key, field, value, seconds, true);
}
//转换map对象类型
private <T> Map<String, T> converClassMap(final Map<String, String> mapValues, final Class<T> valueClazz) {
Map<String, T> map = new HashMap<>();
for (Map.Entry<String, String> entry : mapValues.entrySet()) {
T value = JSON.parseObject(entry.getValue(), valueClazz);
map.put(entry.getKey(), value);
}
return map;
}
//取redis map全部数据的直接方法
public <T> Map<String, T> hgetAll(final String type, final String key,
final Class<T> valueClazz, int seconds,
boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
Map<String, String> mapValues = redisUtil.hgetAll(fullKey);
return converClassMap(mapValues, valueClazz);
}
public <T> Map<String, T> hgetAll(final String type, final String key,
final Class<T> valueClazz, int seconds) throws Exception {
return hgetAll(type, key, valueClazz, seconds, true);
}
//获取redis map下一个key的值的直接方法
public <K, SK, T> T hGamemget(final String fullKey, final SK field, final Class<T> clazz, int seconds) throws Exception {
String strField = String.valueOf(field);
List<String> listStrs = redisUtil.hmget(fullKey, strField);
if (listStrs == null || listStrs.size() <= 0) {
return null;
}
return JSON.parseObject(listStrs.get(0), clazz);
}
//获取redis map下一个key的值的直接方法
public <K, SK, T> T hmget(final String type, final K key, final SK field, final Class<T> clazz, int seconds,
boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
String strField = String.valueOf(field);
List<String> listStrs = redisUtil.hmget(fullKey, strField);
if (listStrs == null || listStrs.size() <= 0) {
return null;
}
return JSON.parseObject(listStrs.get(0), clazz);
}
public <K, SK, T> T hmget(final String type, final K key, final SK field, final Class<T> clazz, int seconds) throws Exception {
return hmget(type, key, field, clazz, seconds, true);
}
//删除子key
public <K, SK> void hdel(final String type, final K key, final SK field, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
String strField = String.valueOf(field);
redisUtil.hdel(fullKey, strField);
}
public void hdel(final String type, final String key, final String field) throws Exception {
hdel(type, key, field, true);
}
/***************************************以下是list操作***************************************/
//添加list数据
public <K, T> long lpush(final String type, final K key, final int seconds, boolean withServerId,
final T... strings) throws Exception {
String fullKey = getKey(type, key, withServerId);
String[] strValues = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
strValues[i] = JSON.toJSONString(strings[i]);
}
return redisUtil.lpush(fullKey, seconds, strValues);
}
public <K, T> long lpush(final String type, final K key, final int seconds, final T... strings) throws Exception {
return lpush(type, key, seconds, true, strings);
}
//从左面保留
public <K, T> void ltrimLeft(final String type, final K key, final int start, final int end) throws Exception {
String fullKey = getKey(type, key, true);
redisUtil.ltrim(fullKey, start, end);
}
//移除最早的元素
public <K, T> T rpop(final String type, final K key, final Class<T> clazz, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
String strValue = redisUtil.rpop(fullKey);
return JSON.parseObject(strValue, clazz);
}
public <K, T> T rpop(final String type, final K key, final Class<T> clazz) throws Exception {
return rpop(type, key, clazz);
}
//添加一个新的元素如果list超过了count则删除最早的
public <K, T> long lpushRpop(final String type, final String key,
final T value, final int count, final int seconds, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
long len = redisUtil.llen(fullKey);
if (count > 0 && len >= count) {
for (int i = 0; i < len - count + 1; i++) {
redisUtil.rpop(fullKey);
}
}
String strValue = JSON.toJSONString(value);
return redisUtil.lpush(fullKey, seconds, strValue);
}
public <K, T> long lpushRpop(final String type, final String key, final T value,
final int count, final int seconds) throws Exception {
return lpushRpop(type, key, value, count, seconds, true);
}
private <T> List<T> converClassList(final List<String> listValues, final Class<T> clazz) {
List<T> list = new ArrayList<>();
for (String strValue : listValues) {
T value = JSON.parseObject(strValue, clazz);
list.add(value);
}
return list;
}
//从头开始,向未取数据
public <K, T> List<T> lrange(final String type, final K key, final Class<T> clazz,
final long start, final long end,
final int seconds, boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
List<String> listValues = redisUtil.lrange(fullKey, start, end);
return converClassList(listValues, clazz);
}
public <K, T> List<T> lrange(final String type, final K key, final Class<T> clazz,
final long start, final long end, final int seconds) throws Exception {
return lrange(type, key, clazz, start, end, seconds, true);
}
//取得list的全部数据
public <K, T> List<T> lgetAll(final String type, final K key, final Class<T> clazz, final int seconds,
boolean withServerId) throws Exception {
return lrange(type, key, clazz, 0, -1, seconds, withServerId);
}
public <K, T> List<T> lgetAll(final String type, final K key, final Class<T> clazz, final int seconds) throws Exception {
return lgetAll(type, key, clazz, seconds, true);
}
public Set<Tuple> zrangeWithScores(final String type, final String key) throws Exception {
String fullKey = type +Delimiter_colon+key ;
return redisUtil.zrangeWithScores(fullKey, 0, -1);
}
//自增
public Long incr(final String type, final String key, final boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
return redisUtil.incr(fullKey);
}
public Long incr(final String type, final String key) throws Exception {
return incr(type, key, true);
}
//redis分布式锁加锁
public boolean tryGetDistributedLock(final String type, final String key, final String requestId,
final int expireTime, final boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
return redisUtil.tryGetDistributedLock(fullKey, requestId, expireTime);
}
public boolean tryGetDistributedLock(final String type, final String key, final String requestId,
final int expireTime) throws Exception {
String fullKey = getKey(type, key, true);
return tryGetDistributedLock(type, key, requestId, expireTime, true);
}
//redis分布式锁解锁
public boolean releaseDistributedLock(final String type, final String key, final String requestId,
final boolean withServerId) throws Exception {
String fullKey = getKey(type, key, withServerId);
return redisUtil.releaseDistributedLock(fullKey, requestId);
}
public boolean releaseDistributedLock(final String type, final String key, final String requestId) throws Exception {
return releaseDistributedLock(type, key, requestId, true);
}
}

View File

@ -0,0 +1,81 @@
package com.ljsd.redis;
public interface RedisKey {
String TOKEN = "TOKEN";
/**
*
*/
String USER_SERVER_INFO = "USER_SERVER_INFO";
String GATE_SERVER = "gate_server";
/**
* 线
*/
String ONLINE_ROLE_COUNT = "ONLINE_ROLE_COUNT";
String WHITE_LIST = "WHITE_LIST";
/**
* // 白名单状态 0白名单用户以及白名单ip都生效 1: 只是白名单用户生效 2只是白名单ip生效
*/
String WHITE_LIST_STATE = "WHITE_LIST_STATE";
/**
* token
*/
public static int TOKEN_EXPIRE = 60 * 60 * 24 * 7;
/**
* gateway
*/
String GATEWAY_ADDRESS_LIST = "GATEWAY_ADDRESS_LIST";
String SUBCHANNEL_REGISTER_NUM= "SUBCHANNEL_REGISTER_NUM";
String REGIST_NUM = "REGIST_NUM" ;
/**
* true false
*/
String SERVER_REGISTER_STATE = "SERVER_REGISTER_STATE";
/**
* uid
*/
String UID = "UID";
/**
*
*/
String USER_LOGIN_LOCK = "USER_LOGIN_LOCK";
/**
*
*/
String ACCOUNT_INFO = "AccountInfo";
/**
*
*/
String SERVER_NAME = "SERVER_NAME";
/**
*
*/
String CLIENT_REPORT_KEY = "CLIENT_REPORT_KEY";
/**
* //开服时间
*/
String SERVER_OPEN_TIME = "SERVER_OPEN_TIME";
/**
* id
*/
String RECOMMEND_ID = "RECOMMEND_ID";
}

View File

@ -0,0 +1,463 @@
package com.ljsd.redis;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.GlobalVersion;
import com.ljsd.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Tuple;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RedisUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);
private static int MAX_TRY_TIMES = 3; //最大尝试次数,保障获取/存储成功
private static int FAILED_SLEEP = 2; //每次失败最大停顿时间
private JedisPool jedisPool;//非切片连接池
private static int redisdb;
protected void init() {
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(BaseGlobal.properties.getProperty("redis_maxTotal")));
config.setMinIdle(Integer.parseInt(BaseGlobal.properties.getProperty("redis_minIdle")));
config.setMaxWaitMillis(Integer.parseInt(BaseGlobal.properties.getProperty("redis_maxWaitMillis")));
config.setMaxIdle(Integer.parseInt(BaseGlobal.properties.getProperty("redis_maxIdle")));
config.setTestOnBorrow(Boolean.parseBoolean(BaseGlobal.properties.getProperty("redis_testOnBorrow")));
String password = BaseGlobal.properties.getProperty("redis_pwd");
String redisStr = BaseGlobal.properties.getProperty("redis_db");
if (redisStr == null || redisStr.equals("")) {
redisdb = 0;
} else {
redisdb = Integer.parseInt(redisStr);
}
if (password.equals("-1")) {
password = null;
}
jedisPool = new JedisPool(config, BaseGlobal.properties.getProperty("redis_host"), Integer.parseInt(BaseGlobal.properties.getProperty(
"redis_port")),
Integer.parseInt(BaseGlobal.properties.getProperty("redis_connectTimeout")), password);
LOGGER.info("redis init success !!!");
LOGGER.info("loginServer version:" + GlobalVersion.getServerVersion());
}
protected Jedis getResource() {
Jedis jedis = jedisPool.getResource();
jedis.select(redisdb);
return jedis;
}
/***************************************普通键值对操作***************************************/
//设置键值
protected void set(final String key, String value) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.set(key, value);
return;
} catch (Exception e) {
LOGGER.error("set->i={}: key={}, value={}", i, key, value, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::set exception");
}
//设置键值,带过期时间
protected void setex(final String key, final int seconds, final String value) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.setex(key, seconds, value);
return;
} catch (Exception e) {
LOGGER.error("setex->i={},key={},value={},seconds={}", i, key, value, seconds, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::setex exception");
}
//取得键的值
protected String get(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.get(key);
} catch (Exception e) {
LOGGER.error("get->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::get exception");
}
//删除键值
protected void del(String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.del(key);
return;
} catch (Exception e) {
LOGGER.error("del->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::del exception");
}
//删除键值
protected boolean exists(String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.exists(key);
} catch (Exception e) {
LOGGER.error("exists->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::exists exception");
}
//设置过期时间
protected Long expire(final String key, final int seconds) throws Exception {
if (seconds <= 0) {
return 0L;
}
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.expire(key, seconds);
} catch (Exception e) {
LOGGER.error("expire->i={},key={},seconds={}", i, key, seconds, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::del exception");
}
/***************************************以下是map操作***************************************/
//添加redis map
protected void hmset(final String key, final Map<String, String> hash, int seconds) throws Exception {
int i;
for (i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.hmset(key, hash);
break;
} catch (Exception e) {
LOGGER.error("hmset->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
expire(key, seconds);
if (i >= MAX_TRY_TIMES) {
throw new Exception("RedisUtil::hmset exception");
}
}
//取得主key下的所有子key
protected Set<String> hkeys(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
Set<String> keySet = jedis.hkeys(key);
return keySet;
} catch (Exception e) {
LOGGER.error("hkeys->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::hkeys exception");
}
//设置redis map一个键值 下的子key下的值
protected void hset(final String key, final String field, final String value, int seconds) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.hset(key, field, value);
return;
} catch (Exception e) {
LOGGER.error("hset->i={},key={},field={},value={}", i, key, field, value, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
expire(key, seconds);
throw new Exception("RedisUtil::hset exception");
}
//取redis map全部数据的直接方法
protected Map<String, String> hgetAll(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.hgetAll(key);
} catch (Exception e) {
LOGGER.error("hgetAll->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::hgetAll exception");
}
//获取redis map下一个key的值的直接方法
protected List<String> hmget(final String key, final String... fields) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.hmget(key, fields);
} catch (Exception e) {
LOGGER.error("hmget->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::hmget exception");
}
//删除子key
protected void hdel(final String key, final String... fields) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.hdel(key, fields);
return;
} catch (Exception e) {
LOGGER.error("hdel->i={},key={},fields={}", i, key, fields, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::hdel exception");
}
/***************************************以下是list操作***************************************/
//添加list数据
protected long lpush(final String key, final int seconds, final String... strings) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.lpush(key, strings);
} catch (Exception e) {
LOGGER.error("lpush->i={},key={},value={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
expire(key, seconds);
throw new Exception("RedisUtil::lpush exception");
}
protected void ltrim(final String key, final int start, final int end) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.ltrim(key, start, end);
return;
} catch (Exception e) {
LOGGER.error("lpush->i={},key={},value={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::ltrim exception");
}
//删除元素
protected void lrem(final String key, final long count, final String value) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
jedis.lrem(key, count, value);
return;
} catch (Exception e) {
LOGGER.error("lrem->i={},key={},count={},value={}", i, key, count, value, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::lrem exception");
}
//移除最好的元素
protected String rpop(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.rpop(key);
} catch (Exception e) {
LOGGER.error("rpop->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::rpop exception");
}
//取得指定范围的元素
protected List<String> lrange(final String key, final long start, final long end) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.lrange(key, start, end);
} catch (Exception e) {
LOGGER.error("lrange->i={},key={},start={},end={}", i, key, start, end, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::lrange exception");
}
//取得list的长度
protected Long llen(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.llen(key);
} catch (Exception e) {
LOGGER.error("llen->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::llen exception");
}
//自增
protected Long incr(final String key) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.incr(key);
} catch (Exception e) {
LOGGER.error("incr->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::incr exception");
}
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
/**
*
*
* @param lockKey
* @param requestId
* @param expireTime 5001
* @return
*/
protected boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
// LOGGER.error("tryGetDistributedLock->i={},key={};failed", i, lockKey);
//理论上锁冲突的几率很小,如果连续三次加锁失败,直接抛出异常
TimeUtil.sleep(200);
} catch (Exception e) {
LOGGER.error("tryGetDistributedLock->i={},key={}", i, lockKey, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
LOGGER.error("tryGetDistributedLock->key={} requestId={};failed", lockKey, requestId);
return false;
}
protected Set<Tuple> zrangeWithScores(final String key, final int start, final int end) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
return jedis.zrangeWithScores(key, start, end);
} catch (Exception e) {
LOGGER.error("zrangeWithScores->i={},key={}", i, key, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::zrangeWithScores exception");
}
private static final Long RELEASE_SUCCESS = 1L;
/**
*
*
* @param lockKey
* @param requestId
* @return
*/
protected boolean releaseDistributedLock(String lockKey, String requestId) throws Exception {
for (int i = 0; i < MAX_TRY_TIMES; i++) {
Jedis jedis = getResource();
try {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false; //解锁失败,等待过期自动解锁即可
} catch (Exception e) {
LOGGER.error("releaseDistributedLock->i={},key={}", i, lockKey, e);
TimeUtil.sleep(FAILED_SLEEP);
} finally {
jedis.close();
}
}
throw new Exception("RedisUtil::releaseDistributedLock exception");
}
}

View File

@ -0,0 +1,114 @@
package com.ljsd.sdk;
import com.alibaba.fastjson.JSONObject;
import com.ljsd.controller.LoginSDKController;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @version V1.0
* @ClassName: KSManager
* @Package com.ljsd.ks
* @Description: ${}
* @Author: zw
* @date: 2020/6/4 15:33
*/
public class KSManager {
private static final Logger LOGGER = LoggerFactory.getLogger(KSManager.class);
private static final String APP_ID = "ks681732397632875242";
public static String LOGIN_VERIFY_URL = "https://open.kuaishou.com/game/user_info";
public static String LOGIN_TEST_VERIFY_URL = "http://open.test.gifshow.com/game/user_info";
public static final String KUAI_SHOU = "KuaiShou";
private static String BT_LOGIN_VERIFY_URL = "https://supersdk.7pa.com/login/checkuserinfo";
private static String X7_LOGIN_VERIFY_URL = "https://api.x7sy.com/user/check_v4_login";
public static String OPEN_SERVER_STRATEGY = "1"; // 开服策略1 按注册量开 2 按时间开
/**
*
*
* @param gameId
* @param token
* @return
*/
public static String loginVerify(String gameId, String token, boolean isOnline) {
Map<String, String> param = new HashMap<>();
param.put("app_id", APP_ID);
param.put("game_id", gameId);
param.put("game_token", token);
String paramStr = HttpClient.joinParam(param);
String response = "";
if (isOnline) {
response = HttpClient.sendGet(LOGIN_VERIFY_URL, paramStr);
} else {
response = HttpClient.sendGet(LOGIN_TEST_VERIFY_URL, paramStr);
}
return response;
}
// public static void main(String[] args) {
// String gameId = "120592009db2d8e3eb07fb38a2730acf12";
// String token =
// "ChJvcGVucGxhdGZvcm0udG9rZW4SMAM7UR7xnKWv0WNlJUju9Fhg0onfcvYhIpfyuzOJMoEeR6r86eKwab60hbGDzvxckhoSiFj3919FQSKj7382Le0VBErzIiCsbZy5IGlecA9xQvQgIsZMfBZdr9XrpjhPDS9kN1g0ySgFMAE";
// String response = loginVerify(gameId, token,true);
// JSONObject jsonObject = JSONObject.parseObject(response);
// int result = jsonObject.getInteger("result");
// System.out.println(response);
// }
/**
* bt
*
* @param gameId
* @param token
* @return
*/
public static boolean btLoginVerify(String gameId, String token) {
boolean isOnline = Boolean.parseBoolean(BaseGlobal.properties.getProperty("isOnline"));
if (!isOnline){
return true;
}
Map<String, String> param = new HashMap<>(2);
param.put("super_user_id", gameId);
param.put("token", token);
String result = HttpClient.sendPost(BT_LOGIN_VERIFY_URL, param);
JSONObject json = JSONObject.parseObject(result);
return json.getInteger("code") == 200;
}
/**
* x7
*
* @param tokenkey
* @param sign
* @return
*/
public static JSONObject x7LoginVerify(String tokenkey, String sign) {
boolean isOnline = Boolean.parseBoolean(BaseGlobal.properties.getProperty("isOnline"));
if (!isOnline){
LOGGER.info("x7LoginVerify isOnline={} gameId={} token={}", isOnline, tokenkey, sign);
return null;
}
Map<String, String> param = new HashMap<>(2);
param.put("tokenkey", tokenkey);
param.put("sign", sign);
String result = HttpClient.sendPost(X7_LOGIN_VERIFY_URL, param);
JSONObject json = JSONObject.parseObject(result);
LOGGER.info("x7LoginVerify=====result={} json={}", result, json);
return json;
}
}

View File

@ -0,0 +1,404 @@
package com.ljsd.timer;
import com.ljsd.pojo.LoginServerInfo;
import com.ljsd.pojo.Notice;
import com.ljsd.pojo.PlatformServerinfo;
import com.ljsd.pojo.ServerAddress;
import com.ljsd.redis.RedisKey;
import com.ljsd.util.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class ServerManager extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerManager.class);
public static Map<String,List<DBObject>> noticeMap = new HashMap<>();
/**
* key:sub_channel key1:channel|plat
*/
public static Map<String,Map<String, List<DBObject>>> serverMap = new ConcurrentHashMap<>();
public static List<DBObject> recommendServers = new ArrayList<>();
public static List<DBObject> servers = new ArrayList<>();
public static Map<String, DBObject> serverMapById = new ConcurrentHashMap<>();
public static Map<Integer, String> serverGroups = new HashMap<>();
/**
*
*/
public static Map<String, Integer> channelMaxRegister = new HashMap<>();
public static Map<String, List<String>> channelWhites = new HashMap<>();
public static Map<String, PlatformServerinfo> platServerinfo = new HashMap<>();
/**
* key:channel:sub_channel:market
*/
public static Map<String,LoginServerInfo> loginServerInfoMap = new HashMap<>();
public static String openTime;
public static String closeTime;
public static int maxRegister;
public static String whiteIpRange;
public static int version;
@Override
public void run() {
while (true) {
try {
noticeMap = initNotice();
// checkServers();
List<DBObject> channelWhite = BaseGlobal.mongoDBPool.findList(MongoKey.CHANNEL_WHITE);
checkChannelWhites(channelWhite);
updateWhiteList();
List<DBObject> list = BaseGlobal.mongoDBPool.findList(MongoKey.SERVER_GROUP);
//默认添加group数据
if (list.size() ==0){
DBObject dbObject = new BasicDBObject();
dbObject.put("_id",1);
dbObject.put("groupName","一区");
dbObject.put("orderId",1);
dbObject.put("groupType",1);
BaseGlobal.mongoDBPool.save(MongoKey.SERVER_GROUP,dbObject);
list = BaseGlobal.mongoDBPool.findList(MongoKey.SERVER_GROUP);
}
// Map<Integer, String> map = new HashMap<>();
// for (DBObject data : list) {
// map.put(Integer.parseInt(data.get("_id").toString()), data.get("groupName").toString());
// }
// serverGroups = map;
serverMap = initServerList();
loginServerInfoMap = ininLoginServerInfo();
checkUpdateServerinfo();
sleep(10 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* @return
*/
private Map<String,List<DBObject>> initNotice() throws Exception {
List<DBObject> list = BaseGlobal.mongoDBPool.findList(MongoKey.NOTICE_INFO);
Map<String,List<DBObject>> noticeMap = new HashMap<>();
long nowTime = System.currentTimeMillis();
for (DBObject dbObject:list){
String channel = String.valueOf(dbObject.get("channel"));
long startTime = Long.parseLong(String.valueOf(dbObject.get("start_time")));
long endTime = Long.parseLong(String.valueOf(dbObject.get("end_time")));
if (nowTime < startTime ){
continue;
}
if (nowTime > endTime){
continue;
}
String[] split = channel.split("#");
for (String str : split){
if (!noticeMap.containsKey(str)){
noticeMap.put(str,new ArrayList<>());
}
noticeMap.get(str).add(dbObject);
}
}
return noticeMap;
}
private Map<String, LoginServerInfo> ininLoginServerInfo() throws Exception {
Map<String, LoginServerInfo> map = new ConcurrentHashMap<>();
List<DBObject> platformList = BaseGlobal.mongoDBPool.findList(MongoKey.LOGIN_SERVER_INFO);
for (DBObject object : platformList){
String itversion = String.valueOf(object.get("_id"));
Map<String,DBObject> marketInfoMap = (Map<String, DBObject>) object.get("channelMap");
for (Map.Entry<String,DBObject> entry:marketInfoMap.entrySet()){
String channel = entry.getKey();
DBObject marketInfo = entry.getValue();
for (int i = 0 ; i < 2; i++){
String key = itversion + ":" + channel+ ":" + i;
map.put(key,getloginServerInfo(marketInfo,i));
}
}
}
return map;
}
private LoginServerInfo getloginServerInfo(DBObject marketInfo,int type) {
//type 0: 测试 1线上
LoginServerInfo loginServerInfo;
if (type == 0){
loginServerInfo= new LoginServerInfo(String.valueOf(marketInfo.get("testLoginServerUrl")), String.valueOf(marketInfo.get("testRes")));
}else{
loginServerInfo= new LoginServerInfo(String.valueOf(marketInfo.get("loginServerUrl")),String.valueOf(marketInfo.get("res")));
}
return loginServerInfo;
}
private Map<String, Integer> checkChannelMaxRegister() throws Exception {
DBObject dbObject = BaseGlobal.mongoDBPool.findOne(MongoKey.SERVER_CONFIG, "1");
Map<String,Integer> maxRegisterMap = new ConcurrentHashMap<>();
if (dbObject != null){
maxRegisterMap = (Map<String, Integer>) dbObject.get("max_register_map");
}
return maxRegisterMap;
}
private Map<String ,Map<String, List<DBObject>>> initServerList() throws Exception {
Map<String ,Map<String, List<DBObject>>> map= new ConcurrentHashMap<>(16);
servers = BaseGlobal.mongoDBPool.findList(MongoKey.SERVER_INFO);
List<DBObject> recommendServerList = new ArrayList<>();
for (DBObject dbObject : servers){
int recommend = (int) dbObject.get("recommend");
//推荐服
if (recommend == 1){
recommendServerList.add(dbObject);
}
String itversion = String.valueOf( dbObject.get("itversion"));
if (itversion == null || itversion.isEmpty()){
itversion = "1";
}
if (!map.containsKey(itversion)){
map.put(itversion,new HashMap<>(16));
}
Map<String, List<DBObject>> serverMap = map.get(itversion);
String[] channels = dbObject.get("channel").toString().split("#");
for (String channel : channels){
String info = channel + "|" + dbObject.get("plat");
if (!serverMap.containsKey(info)){
serverMap.put(info,new ArrayList<>());
}
serverMap.get(info).add(dbObject);
}
serverMapById.put(String.valueOf(dbObject.get("server_id")),dbObject);
int groupId = Integer.parseInt(dbObject.get("groupId").toString());
// dbObject.put("area_name", serverGroups.get(groupId));
}
recommendServers = recommendServerList;
if (recommendServers.size() == 0){
String nextOpenServerId = BaseGlobal.redisApp.get(RedisKey.RECOMMEND_ID, "", String.class, -1, false);
if (nextOpenServerId == null || nextOpenServerId.isEmpty()){
nextOpenServerId = "0";
}
DBObject one = BaseGlobal.mongoDBPool.findOne(MongoKey.SERVER_INFO, nextOpenServerId);
if (one != null){
long openTime = TimeUtil.getNowDayTimeStamp(System.currentTimeMillis());
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject dbObject = new BasicDBObject();
searchQuery.put("_id",nextOpenServerId);
dbObject.append("$set", new BasicDBObject().append("recommend", 1).append("state", 0).append("open_time", TimeUtil.timeStamp2Date(openTime)));
//设置开服时间
LoginUtil.setOpenTime(String.valueOf(one.get("server_id")),openTime);
BaseGlobal.mongoDBPool.updateValue(MongoKey.SERVER_INFO,searchQuery,dbObject);
}
}
return map;
}
private void checkUpdateServerinfo() throws Exception {
// 先获取所有公告
List<DBObject> platformList = BaseGlobal.mongoDBPool.findList(MongoKey.PLATFORM_INFO);
for (DBObject obj : platformList) {
Set<String> keySet = obj.keySet();
String palt = (String)obj.get("_id");
for (String key : keySet){
if ("_id" .equals(key) || "_class".equals(key)){
continue;
}
DBObject obj1 = (DBObject)obj.get(key);
String ptkey = palt+"-"+ key;
String appversion = (String)obj1.get("app_ver");
String resversion = (String)obj1.get("res_ver");
String res_url = (String)obj1.get("res");
PlatformServerinfo server = new PlatformServerinfo(appversion, resversion, res_url);
platServerinfo.put(ptkey,server);
}
}
}
private void checkChannelWhites(List<DBObject> channelWhite) {
if (channelWhite == null || channelWhite.isEmpty()) {
return;
}
for (DBObject data : channelWhite) {
String openId = data.get("_id").toString();
String channel = data.get("channel").toString();
if (!channelWhites.containsKey(channel)) {
channelWhites.put(channel, new ArrayList<>());
}
if (channelWhites.get(channel).contains(openId)) {
continue;
}
channelWhites.get(channel).add(openId);
}
}
// private void checkServers() throws Exception {
// // 更新服务器开服时间到redis
// for (DBObject data : servers) {
// String serverId = data.get("server_id").toString();
// String openTime = data.get("open_time").toString();
// BaseGlobal.redisApp.hset("SERVER_OPEN", "", serverId, openTime, -1, false);
// }
// }
public static boolean serverIsOpen(String serverId) throws Exception {
for (DBObject data : servers) {
if (!data.get("server_id").toString().equals(serverId)) {
continue;
}
String type = "game:" + serverId + ":server";
Map<String, Object> coreMap = BaseGlobal.redisApp.hgetAll(type, "", Object.class, -1, false);
if (coreMap == null || coreMap.isEmpty()) {
return false;
} else {
boolean isOpen = false;
for (String coreId : coreMap.keySet()) {
Object obj = BaseGlobal.redisApp.get(type, coreId, Object.class, -1, false);
if (obj != null) {
isOpen = true;
break;
}
}
if (!isOpen) {
return false;
}
}
}
return true;
}
private void reloadNoticeFromTxt() throws Exception {
version = Integer.parseInt(BaseGlobal.noticeVersion.getProperty("version"));
// 先获取所有公告
List<DBObject> noticeList = BaseGlobal.mongoDBPool.findList(MongoKey.NOTICE_INFO);
for (DBObject obj : noticeList) {
BaseGlobal.mongoDBPool.remove(MongoKey.NOTICE_INFO, obj);
}
Map<Integer, Notice> noticeMap = STableManager.getConfig("notice", Notice.class);
for (Notice data : noticeMap.values()) {
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", data.get__id());
dbObject.put("ifOpen", data.getIfOpen());
dbObject.put("name", data.getName());
dbObject.put("isNew", data.getIsNew());
dbObject.put("type", data.getType());
dbObject.put("pic", data.getpic());
dbObject.put("content", data.getContent());
BaseGlobal.mongoDBPool.save(MongoKey.NOTICE_INFO, dbObject);
}
}
public static List<String>getServerList(DBObject req) {
String itversion = (String) req.get("itversion");
if (itversion == null || itversion.isEmpty()){
itversion = "1";
}
float version = Float.parseFloat(itversion);
String channel = String.valueOf(req.get("channel"));
String plat = String.valueOf(req.get("plat"));
// List<DBObject> serverInfoList = new ArrayList<>();
List<String> serverIds = new ArrayList<>();
Map<String, Map<String, List<DBObject>>> serverMap = ServerManager.serverMap;
for (Map.Entry<String,Map<String, List<DBObject>>> entry : serverMap.entrySet()){
String[] split1 = entry.getKey().split("#");
float minVer = Float.parseFloat(split1[0]);
float maxVer = Float.parseFloat(split1[1]);
if (version >= minVer && version <= maxVer){
Map<String, List<DBObject>> value = entry.getValue();
for (Map.Entry<String, List<DBObject>> entry1: value.entrySet()){
String[] split = entry1.getKey().split("\\|");
String schannel = split[0];
// String splat = split[1];
// if (!plat.equals(splat)){
// continue;
// }
if (channel.contains(schannel)){
for (DBObject dbObject : entry1.getValue()){
// String serverId = dbObject.get("server_id").toString();
String serverId = dbObject.get("_id").toString();
if (serverIds.contains(serverId)){
continue;
}
serverIds.add(serverId);
}
}
}
}
}
return serverIds;
}
public static DBObject getServer(String serverId) {
// for (DBObject data : servers) {
// if (serverId == Integer.parseInt(data.get("server_id").toString())) {
// return data;
// }
// }
return new HashMap<>(serverMapById).get(serverId);
}
public static DBObject getServerById(String _id) {
for (DBObject data : servers) {
if (_id.equals(data.get("_id").toString())) {
return data;
}
}
return null;
}
public static ServerAddress getServerAddress(int serverId) throws Exception {
Map<String, ServerAddress> addressMap = BaseGlobal.redisApp.hgetAll
(RedisKey.GATE_SERVER, String.valueOf(serverId), ServerAddress.class, -1, false);
List<String> keys = new ArrayList<>(addressMap.keySet());
if (keys.size() == 0) {
return null;
}
Random random = new Random();
int index = random.nextInt(keys.size());
String key = keys.get(index);
ServerAddress address = addressMap.get(key);
return address;
}
/**
* game线
*
* @return
* @throws Exception
*/
public static int totalCount(String serverId) throws Exception {
Integer onlineNum = BaseGlobal.redisApp.hGamemget("game:"+serverId+":" + RedisKey.ONLINE_ROLE_COUNT +":","1", Integer.class, -1);
if (onlineNum == null){
onlineNum = 0;
}
return onlineNum;
}
public static void updateWhiteList() throws Exception {
List<DBObject> whiteUsers = BaseGlobal.mongoDBPool.findList(MongoKey.WHITE_LIST);
for (DBObject user : whiteUsers) {
String id = user.get("_id").toString();
BaseGlobal.redisApp.hset(RedisKey.WHITE_LIST, "", id, 0, -1, true);
}
}
}

View File

@ -0,0 +1,114 @@
package com.ljsd.timer;
import com.ljsd.controller.GetUserController;
import com.ljsd.redis.RedisKey;
import com.ljsd.sdk.KSManager;
import com.ljsd.util.BaseGlobal;
import com.ljsd.util.MongoKey;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author gaojie
* @version V1.0
* @className UpdateServerNameThread
* @packageName com.ljsd.timer
* @description redis
* @date 2021-04-27 15:09
* copyright(c) 2020-2030
**/
public class UpdateServerNameThread extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(UpdateServerNameThread.class);
@Override
public void run() {
while (true) {
try {
List<Integer> openServers = new ArrayList<>();
Map<Integer, Long> closeServers = new HashMap<>();
List<DBObject> servers = BaseGlobal.mongoDBPool.findList(MongoKey.SERVER_INFO);
for (DBObject dbObject : servers) {
String serverId = String.valueOf(dbObject.get("server_id"));
String displayId = "";
if (null != dbObject.get("display_id")) {
displayId = String.valueOf(dbObject.get("display_id"));
}
String name = displayId + dbObject.get("name");
BaseGlobal.redisApp.set(RedisKey.SERVER_NAME, serverId, name, -1, false);
int state = Integer.parseInt(dbObject.get("state").toString());
long openTime = stringToTimeLong(dbObject.get("open_time").toString());
if (state == -1){
closeServers.put(Integer.parseInt(serverId), openTime);
} else {
openServers.add(Integer.parseInt(serverId));
}
}
if ("2".equals(KSManager.OPEN_SERVER_STRATEGY)) {
openServerByTime(openServers, closeServers);
}
sleep(60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void openServerByTime(List<Integer> openServers, Map<Integer, Long> closeServers) throws Exception {
LOGGER.info("按时间开服程序 已开启服务器数=》{} 待开启的服务器数=》{}", openServers.size(), closeServers.size());
int nextServerId = 0;
int curServerId = 0;
if (openServers.isEmpty()) {
nextServerId = 1001;
curServerId = 1001;
} else {
Collections.sort(openServers);
curServerId = openServers.get(openServers.size() - 1);
nextServerId = curServerId + 1;
}
if (closeServers.isEmpty()) {
LOGGER.info(" 按时间开服 没有服务器了 nextServerId=>{}", nextServerId);
return;
}
Long nextServerOpenTime = closeServers.get(nextServerId);
if (nextServerOpenTime == null || nextServerOpenTime == 0) {
LOGGER.info("按时间开服 serverId=>{} 没有设置开服时间 serverInfo.getOpen_time() == 0", nextServerId);
return;
}
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis < nextServerOpenTime) {
LOGGER.info("按时间开服 未到开服时间 serverId=>{} 设置开服时间=> {} ", nextServerId, getStrDateYMDHMS(nextServerOpenTime));
return;
}
GetUserController.openNextServer(Integer.toString(curServerId));
}
/**
*
*
* @param dateStr
* @return
* @throws ParseException
*/
public static long stringToTimeLong(String dateStr) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.parse(dateStr).getTime();
} catch (ParseException e) {
LOGGER.error("", e);
}
return System.currentTimeMillis();
}
public static String getStrDateYMDHMS(long time) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(time);
return dateString;
}
}

View File

@ -0,0 +1,36 @@
package com.ljsd.util;
import com.ljsd.redis.RedisApp;
import com.ljsd.sdk.KSManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
public class BaseGlobal {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseGlobal.class);
public static Properties properties = new Properties();
public static MyMongoDBPool mongoDBPool;
public static RedisApp redisApp;
public static Properties noticeVersion = new Properties();
public static void init() {
mongoDBPool = new MyMongoDBPool();
redisApp = new RedisApp();
initKsUrl();
}
public static void initKsUrl() {
if (BaseGlobal.properties.getProperty("login_verify_url") != null) {
KSManager.LOGIN_VERIFY_URL = BaseGlobal.properties.getProperty("login_verify_url");
}
if (BaseGlobal.properties.getProperty("login_test_verify_url") != null) {
KSManager.LOGIN_TEST_VERIFY_URL = BaseGlobal.properties.getProperty("login_test_verify_url");
}
if (BaseGlobal.properties.getProperty("strategy") != null) {
KSManager.OPEN_SERVER_STRATEGY = BaseGlobal.properties.getProperty("strategy");
}
LOGGER.info("开服策略={}", ("1".equals(KSManager.OPEN_SERVER_STRATEGY) ? "按注册量开服" : "按开服时间开服"));
}
}

View File

@ -0,0 +1,32 @@
package com.ljsd.util;
/**
* @author gaojie
* @version V1.0
* @className GlobalVersion
* @packageName com.ljsd.common.globals
* @description
* @date 2020-12-18 14:46
* copyright(c) 2020-2030
**/
public class GlobalVersion {
/**
*
*/
private static int serverBigVersion = 2;
/**
*
*/
private static int serverReleaseVersion = 5;
/**
*
*/
private static int serverBuildVersion = 356;
public static String getServerVersion()
{
return "V" + serverBigVersion + "." + serverReleaseVersion + "." + serverBuildVersion;
}
}

View File

@ -0,0 +1,255 @@
package com.ljsd.util;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClient {
public static String sendPost(String urlStr, Map<String, String> params) {
Reader in = null;
try {
URL url = new URL(urlStr);
//开始访问
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {postData.append('&');}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(param.getValue(), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
// conn.setRequestProperty("Content-Type", "application/json");
// conn.setRequestProperty("User-Agent", "platform:CP;channel:CP;appVersion:1.0.0;" +
// "package:com.cp.sdk;sdkVersion:1.0.0;sdkName:MSSDK;networkType:WiFi;" +
// "deviceBrand:common;deviceId:00000000;localTime:2019-01-01 00:00:00");
// conn.setRequestProperty("Accept-Language", "zh_CN");
// conn.setRequestProperty("AppKey", SDKProperties.app_key);
// conn.setRequestProperty("Nonce", UUID.randomUUID().toString());
// conn.setRequestProperty("Timestamp", String.valueOf(System.currentTimeMillis()));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; ) {
sb.append((char) c);
}
String response = sb.toString();
return response;
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return "";
}
public static JSONObject sendLedouPost(String urlStr, String requestBody, long time, String nonce, String sign) {
try {
URL url = new URL(urlStr);
//开始访问
byte[] postDataBytes = requestBody.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("User-Agent", "platform:CP;channel:CP;appVersion:1.0.0;" +
"package:com.cp.sdk;sdkVersion:1.0.0;sdkName:MSSDK;networkType:WiFi;" +
"deviceBrand:common;deviceId:00000000;localTime:2019-01-01 00:00:00");
conn.setRequestProperty("Accept-Language", "zh_CN");
conn.setRequestProperty("AppKey", SDKProperties.app_key);
conn.setRequestProperty("Nonce", nonce);
conn.setRequestProperty("Signature", sign);
conn.setRequestProperty("Timestamp", String.valueOf(time));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; ) {
sb.append((char) c);
}
JSONObject response = JSONObject.parseObject(sb.toString());
System.out.println(response.toJSONString());
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* URLGET
*
* @param url URL
* @param param name1=value1&name2=value2
* @return URL
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String joinParam(Map<String, String> map) {
StringBuffer sb = new StringBuffer();
boolean flag = false;
for (String key : map.keySet()) {
String value = map.get(key);
if (flag) {
sb.append("&");
}
sb.append(key).append("=").append(value);
flag = true;
}
return sb.toString();
}
public static String getIPAddress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-ForSquid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IPapache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IPweblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//X-Real-IPnginx服务代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些网络通过多层代理那么获取到的ip就会有多个一般都是通过逗号,分割开来并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//还是不能获取到最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
}
/**
* IPIP
* ipRange IP'-'
*
* @param ipRange
* @param ip
* @return boolean
*/
public static boolean ipIsInRange(String ip, String ipRange) {
if (ipRange == null)
{
System.out.println("IP段不能为空");
return false;
}
if (ip == null)
{
System.out.println("IP不能为空");
return false;
}
ipRange = ipRange.trim();
if (ipRange.equals(ip)){
return true;
}
ip = ip.trim();
final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;
if (!ipRange.matches(REGX_IPB) || !ip.matches(REGX_IP))
return false;
int idx = ipRange.indexOf('-');
String[] sips = ipRange.substring(0, idx).split("\\.");
String[] sipe = ipRange.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i) {
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe) {
long t = ips;
ips = ipe;
ipe = t;
}
return ips <= ipt && ipt <= ipe;
}
}

View File

@ -0,0 +1,49 @@
package com.ljsd.util;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* Simple Utility class for loading an external config file for logback
*
* @author daniel
*/
public class LogBackConfigLoader {
public static void load() throws IOException, JoranException {
String path = System.getProperty("catalina.home");
path += "/config/loginserver/logback.xml";
String externalConfigFileLocation = path;
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
File externalConfigFile = new File(externalConfigFileLocation);
if (!externalConfigFile.exists()) {
throw new IOException("Logback External Config File Parameter does not reference a file that exists");
} else {
if (!externalConfigFile.isFile()) {
throw new IOException("Logback External Config File Parameter exists, but does not reference a file");
} else {
if (!externalConfigFile.canRead()) {
throw new IOException("Logback External Config File exists and is a file, but cannot be read.");
} else {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(externalConfigFileLocation);
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
}
}
}
}

View File

@ -0,0 +1,134 @@
package com.ljsd.util;
import com.ljsd.controller.GetUserController;
import com.ljsd.pojo.AccountInfo;
import com.ljsd.pojo.UserServerInfo;
import com.ljsd.redis.RedisKey;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class LoginUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginUtil.class);
/**
*
* @param userOpenId
* @param ip
* @return
* @throws Exception
*/
public static boolean isWhiteUser(String userOpenId, String ip,String device) throws Exception {
Integer state = BaseGlobal.redisApp.get("", RedisKey.WHITE_LIST_STATE, Integer.class, -1,true);
if(state==null) {
//默认为全生效
state =0;
}
DBObject whiteInfo = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, "1");
boolean isWhiteList = false;
switch (state){
//白名单用户生效
case 1:
DBObject whiteUser = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, userOpenId);
if (whiteUser != null){
isWhiteList = true;
}
break;
//白名ip生效
case 2:
isWhiteList = checkIpIsWhiteList(ip,whiteInfo);
break;
default:
//任意一个就可以登录
boolean isInRange = checkIpIsWhiteList(ip,whiteInfo);
whiteUser = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, userOpenId);
DBObject whiteDevice = BaseGlobal.mongoDBPool.findOne(MongoKey.WHITE_LIST, device);
if (isInRange || null != whiteUser || null != whiteDevice){
isWhiteList = true;
}
}
return isWhiteList;
}
public static boolean checkIpIsWhiteList(String ip,DBObject whiteInfo) throws Exception {
boolean isInRange = false;
if (whiteInfo != null){
List<String> ipList = (List<String>) whiteInfo.get("ip_list");
for (String ipRange : ipList){
isInRange = HttpClient.ipIsInRange(ip, ipRange);
if (isInRange){
break;
}
}
}
return isInRange;
}
public static void setOpenTime(String serverId,long openTime) throws Exception {
BaseGlobal.redisApp.set("game:" + serverId , RedisKey.SERVER_OPEN_TIME + ":",openTime,-1,false);
LOGGER.info("setOpenTime==> serverId:{},openTime:{}",serverId,openTime);
}
public static List<DBObject> createMyServerList(String openId) throws Exception {
Map<String, UserServerInfo> userServerInfoMap = BaseGlobal.redisApp.hgetAll(RedisKey.USER_SERVER_INFO,
openId, UserServerInfo.class, -1, false);
List<DBObject> myServerList = new ArrayList<>();
if (userServerInfoMap ==null || userServerInfoMap.size() ==0){
return myServerList;
}
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", openId);
List<DBObject> userInfos = BaseGlobal.mongoDBPool.find(MongoKey.USER_INFO, dbObject);
DBObject userInfo = userInfos.get(0);
Set<String> serverList = userInfo.keySet();
Set<String> lostList = new HashSet<>();
for (String s : serverList) {
if (!userServerInfoMap.containsKey(s) && !s.equals("_id")) {
lostList.add(s);
}
}
for (String s : lostList) {
Integer uid = (Integer) userInfo.get(s);
DBObject server = new BasicDBObject();
boolean flag = false;
if (uid != null) {
AccountInfo accountInfo = initAccount(s, uid);
if (accountInfo != null) {
flag = true;
server.put("level", accountInfo.getLevel());
server.put("head", accountInfo.getHead());
server.put("frame", accountInfo.getFrame());
server.put("login_time", accountInfo.getBeforeLevelTime());
}
}
if (!flag) {
continue;
}
server.put("server_id", s);
myServerList.add(server);
}
for (Map.Entry<String, UserServerInfo> entry : userServerInfoMap.entrySet()) {
DBObject server = new BasicDBObject();
UserServerInfo userServerInfo = entry.getValue();
server.put("server_id", entry.getKey());
server.put("level", userServerInfo.getLevel());
server.put("head", userServerInfo.getHead());
server.put("frame", userServerInfo.getFrame());
server.put("login_time", userServerInfo.getLoginTime());
myServerList.add(server);
}
return myServerList;
}
public static AccountInfo initAccount(String serverId, int uid) throws Exception {
String type = "game" + ":" + serverId + ":" + RedisKey.ACCOUNT_INFO;
AccountInfo accountInfo = BaseGlobal.redisApp.get(type, uid, AccountInfo.class, -1, false);
return accountInfo;
}
}

View File

@ -0,0 +1,17 @@
package com.ljsd.util;
public class MongoKey {
public final static String WHITE_LIST = "white_list";
public final static String SERVER_INFO = "server_info";
public final static String SERVER_GROUP = "server_group";
public final static String VERSION = "version";
public final static String INC_C = "inc_c";
public final static String NOTICE_INFO = "notice_info";
public final static String USER_INFO = "user_info";
public final static String CHANNEL_WHITE = "channel_white";
public final static String PLATFORM_INFO = "platform_info";
public final static String SERVER_CONFIG = "server_config";
public final static String LOGIN_SERVER_INFO = "loginServer_info";
}

View File

@ -0,0 +1,22 @@
package com.ljsd.util;
import java.security.MessageDigest;
public class MyMD5Util {
public static String encrypt(String dataStr) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(dataStr.getBytes("UTF8"));
byte s[] = m.digest();
String result = "";
for (int i = 0; i < s.length; i++) {
result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}

View File

@ -0,0 +1,147 @@
package com.ljsd.util;
import ch.qos.logback.core.joran.spi.JoranException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.Query;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/*
* mongodb
*/
public class MyMongoDBPool {
private MongoClient mongoClient = null;
private String dbName;
private DB db;
private static final Logger LOGGER = LoggerFactory.getLogger(MyMongoDBPool.class);
public MyMongoDBPool() {
MongoClientOptions.Builder buide = new MongoClientOptions.Builder();
buide.connectionsPerHost(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_maximumNumberOfConnections")));// 与目标数据库可以建立的最大链接数
buide.connectTimeout(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_connectTimeout")));// 与数据库建立链接的超时时间
buide.maxWaitTime(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_maxWaitTime")));// 一个线程成功获取到一个可用数据库之前的最大等待时间
buide.threadsAllowedToBlockForConnectionMultiplier(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_threadsAllowedToBlockForConnectionMultiplier")));
buide.maxConnectionIdleTime(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_maxConnectionIdleTime")));
buide.maxConnectionLifeTime(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_maxConnectionLifeTime")));
buide.socketTimeout(Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_socketTimeout")));
buide.socketKeepAlive(Boolean.parseBoolean(BaseGlobal.properties.getProperty("mongodb_socketKeepAlive")));
// MongoClientOptions myOptions = buide.build();
// MongoCredential credential = MongoCredential.createCredential(BaseGlobal.properties.getProperty("mongodb_user"),
// "admin",
// BaseGlobal.properties.getProperty("mongodb_password").toCharArray());
// mongoClient = new MongoClient(new ServerAddress(BaseGlobal.properties.getProperty("mongodb_host"), Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_port"))),
// credential, myOptions);
String mongodb_url = BaseGlobal.properties.getProperty("mongodb_url");
if (mongodb_url != null && !mongodb_url.isEmpty()) {
mongoClient = new MongoClient(new MongoClientURI(mongodb_url, buide));
} else {
MongoClientOptions myOptions = buide.build();
MongoCredential credential = MongoCredential.createCredential(BaseGlobal.properties.getProperty("mongodb_user"),
"admin",
BaseGlobal.properties.getProperty("mongodb_password").toCharArray());
mongoClient = new MongoClient(new ServerAddress(BaseGlobal.properties.getProperty("mongodb_host"), Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_port"))),
credential, myOptions);
}
dbName = BaseGlobal.properties.getProperty("mongodb_name");
db = mongoClient.getDB(dbName);
}
public DBCollection getCollection(String collectionName) {
return db.getCollection(collectionName);
}
public DBObject findOne(String collectionName, String id) throws Exception {
return findOne2(collectionName, id);
}
public List<DBObject> find(String collectionName, DBObject object) throws Exception {
DBCollection coll = db.getCollection(collectionName);
DBCursor cursor = coll.find(object);
List<DBObject> docs = new ArrayList<>();
while (cursor.hasNext()) {
DBObject doc = cursor.next();
docs.add(doc);
}
return docs;
}
public List<DBObject> findList(String collectionName) throws Exception {
DBCollection coll = db.getCollection(collectionName);
DBCursor cursor = coll.find();
List<DBObject> docs = new ArrayList<>();
while (cursor.hasNext()) {
DBObject doc = cursor.next();
docs.add(doc);
}
return docs;
}
public void remove(String collectionName, DBObject obj) throws Exception {
DBCollection coll = db.getCollection(collectionName);
coll.remove(obj);
}
public DBObject findOne(String collectionName, Integer id) throws Exception {
return findOne2(collectionName, id);
}
private DBObject findOne2(String collectionName, Object id) throws Exception {
DBCollection coll = db.getCollection(collectionName);
return coll.findOne(id.toString());
}
public void updateValue(String collectionName, BasicDBObject searchQuery, BasicDBObject dbObject) {
DBCollection coll = db.getCollection(collectionName);
coll.update(searchQuery, dbObject);
}
public void save(String collectionName, DBObject doc) {
DBCollection coll = db.getCollection(collectionName);
coll.save(doc);
}
public synchronized int inc(String collectionName, String id, String key) {
DBCollection collection = db.getCollection(collectionName);
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", id);
BasicDBObject update = new BasicDBObject().append("$inc", new BasicDBObject().append(key, 1));
int nMax = 3;
for(int i = 0;i < nMax; i++)
{
try {
DBObject result = collection.findAndModify(searchQuery, null, null, false, update,true,true);
if(result != null && result.get(key) != null)
{
return Integer.valueOf(result.get(key).toString()) + 1;
}
else {
Thread.sleep(200);
LOGGER.error("mongodb inc return too max error collection:{},id:{},key:{}",collectionName,id,key);
}
}
catch (Exception e)
{
LOGGER.error("inc==e:{}",e);
}
}
LOGGER.info("mongodb inc return too max error collection:{},id:{},key:{}",collectionName,id,key);
return 1;
}
public int inc(String key) {
return inc(MongoKey.INC_C, "inc_k", key);
}
}

View File

@ -0,0 +1,7 @@
package com.ljsd.util;
public class SDKProperties {
public static String secret = "wF3DebNKeASmtKXxsQVz";
public static String url_login = "https://pub-gw.uu.cc/public-gateway/ms-public-oauth2/sdk_/oauth/checkSession";
public static String app_key = "pn4ZM8NdVzMzXzlXbSNP";
}

View File

@ -0,0 +1,141 @@
package com.ljsd.util;
import com.ljsd.pojo.Notice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
public class STableManager {
private static final Logger LOGGER = LoggerFactory.getLogger(STableManager.class);
private static String path;
public static Map<Integer, Notice> noticeMap = new HashMap<>();
public static void init(ServletContext servletContext) throws Exception{
path = servletContext.getRealPath("/");
// noticeMap = getConfig("notice", Notice.class);
}
/**
*
*/
public static <T> Map<Integer, T> getConfig(String tableName, Class<T> clazz) throws Exception {
Map<Integer, T> map = new HashMap<>();
try {
String path=System.getProperty("catalina.home");
path += "/config/loginserver/config/notice.txt";
String filePath = path;
// String osName = System.getProperty("os.name");
// if(osName.matches("^(?i)Windows.*$")) {
// filePath += "WEB-INF\\classes\\config\\"+ tableName + ".txt";
// } else {
// filePath += "WEB-INF/classes/config/"+ tableName + ".txt";
// }
LOGGER.info("getConfig->name={},path={}", tableName, filePath);
File file = new File(filePath);
String line;
List<String> key = new ArrayList<>();
List<String> type = new ArrayList<>();
int lineNum = 0;
if(!file.exists()){
LOGGER.error("file not find {}, do not find sheet with {} you need rebuild all sheet by gen sheet tool!",path,tableName);
// return null;
}
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
while ((line = bufferedReader.readLine()) != null) {
T obj = clazz.newInstance();
String[] prarms = line.split("\\t");
switch (lineNum) {
case 0:
prarms = fieldHandle(prarms);
key.addAll(Arrays.asList(prarms));
break;
case 1:
type.addAll(Arrays.asList(prarms));
break;
default:
dealParams(clazz, map, key, type, obj, prarms);
break;
}
lineNum++;
}
LOGGER.info("initMap:{}", clazz.getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
*
*/
private static <T> void dealParams(Class<T> clazz, Map<Integer, T> map, List<String> key, List<String> type, T obj, String[] prarms) throws NoSuchFieldException, IllegalAccessException {
int id = Integer.parseInt(prarms[0]);
for (int i = 0; i < prarms.length; i++) {
try {
Field field = clazz.getDeclaredField(key.get(i));
boolean flag = field.isAccessible();
field.setAccessible(true);
switch (type.get(i)) {
case "int":
field.set(obj, Integer.parseInt(prarms[i]));
break;
case "string":
case "stringt":
if (!"null".equalsIgnoreCase(prarms[i])) {
field.set(obj, prarms[i]);
}
break;
case "long":
field.set(obj, Long.parseLong(prarms[i]));
break;
case "double":
field.set(obj, Double.parseDouble(prarms[i]));
break;
case "float":
field.set(obj, Float.parseFloat(prarms[i]));
break;
case "bool":
field.set(obj, Boolean.parseBoolean(prarms[i]));
break;
default:
break;
}
field.setAccessible(flag);
map.put(id, obj);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
/**
*
*
* @return
*/
private static String[] fieldHandle(String[] params) {
String[] params1 = new String[params.length];
for (int i = 0; i < params.length; i++) {
if (params[i].length() <= 2) {
params1[i] = params[i].toLowerCase();
} else {
params1[i] = (new StringBuilder()).append(Character.toLowerCase(params[i].charAt(0))).append(params[i].substring(1)).toString();
}
if(params1[i].equals("id")) {
params1[i] = "_id";
}
}
return params1;
}
}

View File

@ -0,0 +1,108 @@
package com.ljsd.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
*/
public class TimeUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(TimeUtil.class);
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (Exception e) {
LOGGER.error("sleep->msg=null", e.getMessage(), e);
}
}
// 毫秒转为年月日时分秒
public static String timeStamp2Date(long seconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date(seconds));
}
//年月日时分秒 转为毫秒的时间戳
public static String date3TimeStamp(String date_str){
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return String.valueOf(sdf.parse(date_str).getTime());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static boolean inCorrectTime(String startTime, String endTime) throws Exception {
long now = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long start = sdf.parse(startTime).getTime();
// long end = sdf.parse(endTime).getTime();
if (now < start) {
LOGGER.info("inCorrectTime==>now:{},start:{},startTime:{}",now,start,startTime);
return false;
}
// if (now > end) {
// return false;
// }
return true;
}
public static long fixTime(String fixTime) {
String[] temp = fixTime.split(":");
int hour = Integer.parseInt(temp[0]);
int minute = Integer.parseInt(temp[1]);
int second = Integer.parseInt(temp[2]);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
}
/**
*
*
* @return
*/
public static int getDayOfWeek() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return (week == 0) ? 7 : week;
}
/**
*
*
* @return
*/
public static int getDayOfWeek(long time) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return (week == 0) ? 7 : week;
}
/**
* 0
* @param time
* @return
*/
public static long getNowDayTimeStamp(long time){
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
}
}

View File

@ -0,0 +1,47 @@
isOnline=false
start_uid=100000
#mogodb\u670D\u52A1\u5730\u5740
mongodb_host=60.1.1.22
#\u6570\u636E\u5E93\u7528\u6237\u540D
mongodb_user=zhj
#\u6570\u636E\u5E93\u5BC6\u7801
mongodb_password=zhj666
#mogodb\u670D\u52A1\u7AEF\u53E3
mongodb_port=27017
#\u6570\u636E\u5E93\u540D
mongodb_name=zhj_core
#\u4E0E\u76EE\u6807\u6570\u636E\u5E93\u53EF\u4EE5\u5EFA\u7ACB\u7684\u6700\u5927\u94FE\u63A5\u6570
mongodb_maximumNumberOfConnections=100
#\u4E0E\u6570\u636E\u5E93\u5EFA\u7ACB\u94FE\u63A5\u7684\u8D85\u65F6\u65F6\u95F4 2\u5206\u949F
mongodb_connectTimeout=1200000
#\u4E00\u4E2A\u7EBF\u7A0B\u6210\u529F\u83B7\u53D6\u5230\u4E00\u4E2A\u53EF\u7528\u6570\u636E\u5E93\u4E4B\u524D\u7684\u6700\u5927\u7B49\u5F85\u65F6\u95F4 3\u79D2
mongodb_maxWaitTime=30000
#\u6700\u591Axx\u4E2A\u7EBF\u7A0B\u7B49\u7EA7\u4E00\u4E2A\u94FE\u63A5\uFF0C\u63A8\u8350\u914D\u7F6E\u4E3A5
mongodb_threadsAllowedToBlockForConnectionMultiplier=5
#\u6700\u5927\u7A7A\u95F2\u65F6\u95F4\uFF0C\u4E3A0\u65F6\uFF0C\u8868\u793A\u6CA1\u6709\u9650\u5236
mongodb_maxConnectionIdleTime=0
#\u6700\u5927\u751F\u5B58\u65F6\u95F4\uFF0C\u4E3A0\u65F6\uFF0C\u8868\u793A\u6CA1\u6709\u9650\u5236
mongodb_maxConnectionLifeTime=0
#\u8FDE\u63A5\u8FC7\u671F\u65F6\u95F4
mongodb_socketTimeout=0
#\u8FDE\u63A5\u4FDD\u6301\u6D3B\u8DC3
mongodb_socketKeepAlive=true
redis_host=60.1.1.22
redis_pwd=zhj666
redis_port=6379
redis_maxTotal=10
redis_minIdle=3
redis_maxWaitMillis=20
redis_maxIdle=5
redis_testOnBorrow=false
redis_connectTimeout=1200000
redis_db = 0
####------------快手url配置---------------
#登录验证地址
login_verify_url = https://open.kuaishou.com/game/user_info
#测试登录验证地址
login_test_verify_url = http://open.test.gifshow.com/game/user_info
####-------------------------------------

View File

@ -0,0 +1,3 @@
ID Type Name Pic Content IsNew IfOpen
int int string string string int int
1 1 开测公告 ui_dtex_Notice_c3_001 <b><size=48>限号删档测试</size></b>\r\n<size=32>亲爱的玩家:\r\n 这是我们的首个版本可能存在很多问题和不足非常感谢参加本次限号删档测试。我们希望通过此次测试收集广大玩家的建议以便对游戏系统和技术进行验证和优化精益求精希望正式上线版本可以提供最优质的游戏体验。有关游戏的建议欢迎加入官方QQ群联系管理员反馈。\r\n 官方QQ群724613365\r\n 话不多说,这条街交给你了!</size> 1 1

View File

@ -0,0 +1,5 @@
version=2
openTime=2020-07-18 10:00:00
closeTime = 2030-07-19 17:00:00
whiteIpRange = 192.168.1.1-192.168.1.255
maxRegister=2200

View File

@ -0,0 +1,88 @@
{
"_id" : "Zhjwsqww001",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww002",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww003",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww004",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww005",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww006",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww007",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww008",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww009",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww010",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww011",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww012",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww013",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww014",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww015",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww016",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww017",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww018",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww019",
"channel" : "ljsd2"
}
{
"_id" : "Zhjwsqww020",
"channel" : "ljsd2"
}
{
"_id" : "Zhj01",
"channel" : "ljsd2"
}
{
"_id" : "Zhj02",
"channel" : "ljsd2"
}

View File

@ -0,0 +1,13 @@
use zhj_core
db.inc_c.save({ "_id" : "inc_k", "uid" : NumberInt(1), "server_id" : NumberInt(1), "test_id" : NumberInt(1)})
db.server_group.save({ "_id" : "1", "groupName" : "一区", "orderId" : NumberInt(1), "groupType" : NumberInt(1)})
db.server_info.save({ "_id" : "1", "name" : "镇魂街", "ip" : "60.1.1.22", "port" : "9000", "server_id" : "10022"
, "channel" : "pc#Ljsd", "sub_channel" : "", "plat" : "android", "state" : "0", "open_time" : "1568995200"
, "recommend" : "0", "is_new" : "0", "groupId" : NumberInt(1)})
#server_info字段说明"_id"-唯一ID"ip"-网关服IP"port"-网关服端口,
"server_id"-服务器ID需要与online.properties中的serverId一致
"channel"-渠道(多渠道#号分隔),"sub_channel"-子渠道(暂时未用),"plat"-平台android/ios这三个字段需要与客户端一致
"state"-服务器状态0-正常1-火热2-爆满3-白名单4-停服),
"open_time"-开服时间,"recommend"-推荐0-不推荐1-推荐),"is_new"-是否为新服0-非新服1-新服),
"groupId"-组ID需要存在于server_group中的"_id"

View File

@ -0,0 +1,180 @@
{
"_id" : ObjectId("5de8a3b840740c14ac1184d0"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a46b40740c14ac1184d1"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a48f40740c14ac1184d2"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a56540740c14ac1184d3"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a64d40740c14ac1184d4"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "null"
}
{
"_id" : ObjectId("5de8a68740740c14ac1184d5"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "null"
}
{
"_id" : ObjectId("5de8a6af40740c14ac1184d6"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a85340740c343c226ec4"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a87940740c343c226ec5"),
"ip" : "127.0.0.1",
"server" : "\"\"",
"title" : "\"测试邮件\"",
"content" : "\"测试邮件内容\"",
"uid" : "\"10003249\"",
"attachment" : "\"\""
}
{
"_id" : ObjectId("5de8a9cb40740c3c0c01aad4"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aad5"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aad6"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aad7"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aad8"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aad9"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aada"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aadb"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aadc"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aadd"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}
{
"_id" : ObjectId("5de8a9f440740c3c0c01aade"),
"ip" : "127.0.0.1",
"server" : "",
"title" : "测试邮件",
"content" : "测试邮件内容",
"uid" : "10003249",
"attachment" : ""
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
{
"_id" : "1",
"username" : "admin",
"password" : "admin"
}

View File

@ -0,0 +1,6 @@
{
"_id" : "inc_k",
"uid" : NumberInt(10004671),
"server_id" : NumberInt(13),
"test_id" : NumberInt(9)
}

View File

@ -0,0 +1,36 @@
{
"_id" : "65535_20190823_0900_0.log"
}
{
"_id" : "65535_20190823_1300_0.log"
}
{
"_id" : "65535_20190823_1400_0.log"
}
{
"_id" : "65535_20190823_1500_0.log"
}
{
"_id" : "65535_20190823_1600_0.log"
}
{
"_id" : "65535_20190823_1700_0.log"
}
{
"_id" : "65535_20190823_1800_0.log"
}
{
"_id" : "65535_20190823_2000_0.log"
}
{
"_id" : "65535_20190823_2100_0.log"
}
{
"_id" : "D:/data/logs/tlog/2019-08-26/65535_20190826_1400_0.log"
}
{
"_id" : "D:/data/logs/tlog/2019-08-26/65535_20190826_1600_0.log"
}
{
"_id" : "D:/data/logs/tlog/2019-08-26/65535_20190826_1700_0.log"
}

View File

@ -0,0 +1,6 @@
{
"_id" : NumberInt(1),
"groupName" : "一区",
"orderId" : NumberInt(1),
"groupType" : NumberInt(1)
}

View File

@ -0,0 +1,224 @@
{
"_id" : "2",
"name" : "狄奕更",
"ip" : "60.1.1.234",
"port" : "9000",
"server_id" : "10234",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568995200",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : "3",
"name" : "李浩然",
"port" : "9000",
"server_id" : "10236",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"ip" : "60.1.1.238",
"open_time" : "1569340800",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : "7",
"name" : "二月版本",
"ip" : "60.1.1.23",
"port" : NumberInt(9000),
"server_id" : "10023",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1569427200",
"area_name" : "公共",
"recommend" : "1",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : NumberInt(13),
"name" : "朱治国",
"ip" : "60.1.1.157",
"port" : "9000",
"server_id" : "10186",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568822400",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : "14",
"name" : "阮锦程",
"ip" : "60.1.1.154",
"port" : "9000",
"server_id" : "10154",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1569168000",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : "6",
"name" : "冉天悦",
"ip" : "60.1.1.26",
"port" : NumberInt(9000),
"server_id" : "10026",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568736000",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "16",
"name" : "李超服",
"port" : "9000",
"server_id" : "10176",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"ip" : "60.1.1.176",
"open_time" : "1568908800",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "10",
"name" : "付雨鑫",
"ip" : "60.1.1.227",
"port" : NumberInt(9000),
"server_id" : "10227",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568476800",
"area_name" : "测试",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "17",
"name" : "徐鹏",
"ip" : "60.1.1.211",
"port" : "9000",
"server_id" : "10211",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568563200",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "4",
"name" : "测试服",
"ip" : "60.1.1.22",
"port" : NumberInt(9000),
"server_id" : "10022",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1569427200",
"area_name" : "公共",
"recommend" : "1",
"is_new" : "1",
"groupId" : NumberInt(1)
}
{
"_id" : "18",
"name" : "胡镇",
"ip" : "60.1.1.164",
"port" : "9000",
"server_id" : "10164",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1569168000",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "100",
"name" : "高杰",
"ip" : "60.1.1.162",
"port" : "9000",
"server_id" : "10162",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1568563200",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "101",
"name" : "贾会文",
"ip" : "60.1.1.225",
"port" : NumberInt(9000),
"server_id" : "10225",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "0",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}
{
"_id" : "19",
"name" : "刘宏伟",
"ip" : "60.1.1.128",
"port" : "9000",
"server_id" : "10128",
"channel" : "pc#Ljsd",
"sub_channel" : "",
"plat" : "android",
"state" : "0",
"open_time" : "1569168000",
"area_name" : "个人",
"recommend" : "0",
"is_new" : "0",
"groupId" : NumberInt(1)
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
{
"_id" : "1",
"resource_version" : "1.0.0.0",
"application_version" : "1.0.0.0"
}

View File

@ -0,0 +1,3 @@
{
"_id" : "qqqqqq1"
}

View File

@ -0,0 +1,50 @@
<configuration scan="true" scanPeriod="60 seconds">
<contextName>YSJLogging</contextName>
<property name="tip" value="INFO"/>
<!-- 定义日志文件 输入位置 -->
<property name="log_dir" value="../logs"/>
<!-- 日志最大的历史 30天 -->
<property name="maxHistory" value="30"/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder charset="UTF-8">
<pattern>[%level] - %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] - %logger{0}#%line - ${tip}:%msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
</appender>
<appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--<Encoding>UTF-8</Encoding>-->
<!-- 过滤器只记录WARN级别的日志 -->
<encoder charset="UTF-8">
<pattern>[%level] - %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] - %logger{0}#%line - ${tip}:%msg%n</pattern>
</encoder>
<!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>${log_dir}/loginserver/%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
</appender>
<logger name="org.mongodb.driver" level="ERROR"/>
<logger name="org.apache.commons.httpclient" level="WARN"/>
<root level="INFO">
<!-- 控制台输出 -->
<appender-ref ref="console"/>
<appender-ref ref="file_console"/>
<!--<appender-ref ref="TRACE" />-->
</root>
</configuration>

View File

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--<context-param>-->
<!--<param-name>logbackConfigLocation</param-name>-->
<!--<param-value>classpath:main/resources/logback.xml</param-value>-->
<!--</context-param>-->
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>com.ljsd.controller.IndexController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getUserInfo</servlet-name>
<servlet-class>com.ljsd.controller.GetUserController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getUserInfo</servlet-name>
<url-pattern>/getUserInfo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loginSDK</servlet-name>
<servlet-class>com.ljsd.controller.LoginSDKController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginSDK</servlet-name>
<url-pattern>/loginSDK</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>checkVersion</servlet-name>
<servlet-class>com.ljsd.controller.CheckVersionController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkVersion</servlet-name>
<url-pattern>/checkVersion</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>noticeList</servlet-name>
<servlet-class>com.ljsd.controller.NoticeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>noticeList</servlet-name>
<url-pattern>/noticeList</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getserverinfo</servlet-name>
<servlet-class>com.ljsd.controller.GetServerController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getserverinfo</servlet-name>
<url-pattern>/getserverinfo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getLoginServer</servlet-name>
<servlet-class>com.ljsd.controller.GetLoginServerController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getLoginServer</servlet-name>
<url-pattern>/getLoginInfo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>clientReport</servlet-name>
<servlet-class>com.ljsd.controller.ClientReportController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>clientReport</servlet-name>
<url-pattern>/isReport</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getMyServerInfo</servlet-name>
<servlet-class>com.ljsd.controller.GetMyServerInfoController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getMyServerInfo</servlet-name>
<url-pattern>/getMyServerInfo</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.ljsd.listener.WebContextListener</listener-class>
</listener>
</web-app>

View File

@ -0,0 +1,44 @@
<%--
Created by IntelliJ IDEA.
User: Lee
Date: 2018/11/9
Time: 11:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册服务器</title>
</head>
<body>
<img src="static/1.png">
<form action="regist" method="post">
<p>name: <input type="text" name="name"/></p>
<p>ip: <input type="text" name="ip"/></p>
<p>port: <input type="text" value="9000" name="port"/></p>
<p>server_id: <input type="text" name="server_id"/></p>
<p>channel:<select name="channel">
<option value="pc" selected>pc</option>
<option value="qq">qq</option>
<option value="wx">wx</option>
</select></p>
<p>sub_channel: <input type="text" name="sub_channel"/></p>
<p>plat:<select name="plat">
<option value="android" selected>android</option>
<option value="ios">ios</option>
</select></p>
<p>state: <input type="text" value="0" name="state"/></p>
<p>open_time: <input type="text" value="0" name="open_time"/></p>
<p>area_name: <input type="text" value="0" name="area_name"/></p>
<p>recommend:<select name="recommend">
<option value="1" selected>recommend</option>
<option value="0">no_recommend</option>
</select></p>
<p>is_new:<select name="is_new">
<option value="1" selected>is_new</option>
<option value="0">no_new</option>
</select></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB