diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09bc98f --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.iml +.idea +.gradle +build +out + + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..466ee7a --- /dev/null +++ b/build.gradle @@ -0,0 +1,21 @@ +group 'loginserver' +version '1.0-SNAPSHOT' + +apply plugin: 'java' +apply plugin: 'war' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +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.2.2' + 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' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..db28ddb Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a3a9a55 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed Dec 26 12:01:28 CST 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-rc-2-bin.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4453cce --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1df2e0d --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'loginserver' + diff --git a/src/main/java/com/ljsd/controller/GetServerListController.java b/src/main/java/com/ljsd/controller/GetServerListController.java new file mode 100644 index 0000000..edf2df1 --- /dev/null +++ b/src/main/java/com/ljsd/controller/GetServerListController.java @@ -0,0 +1,90 @@ +package com.ljsd.controller; + +import com.ljsd.pojo.UserServerInfo; +import com.ljsd.redis.RedisKey; +import com.ljsd.util.BaseGlobal; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.util.JSON; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class GetServerListController extends HttpServlet { + private final static String _COLLECTION_NAME = "server_info"; + + public GetServerListController() { + super(); + } + + public void destroy() { + super.destroy(); + } + + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + PrintWriter out = response.getWriter(); + try { + String openId = request.getParameter("openId"); + String channel = request.getParameter("channel"); + String sub_channel = request.getParameter("sub_channel"); + String plat = request.getParameter("plat"); + DBObject req = new BasicDBObject(); + req.put("channel", channel); + req.put("sub_channel", sub_channel); + req.put("plat", plat); + List serverInfoList = BaseGlobal.mongoDBPool.find(_COLLECTION_NAME, req); + List serverList = new ArrayList<>(); + for (DBObject serverInfo : serverInfoList) { + long time = Long.parseLong(serverInfo.get("open_time").toString()); + if (System.currentTimeMillis() < time) { + continue; + } + DBObject res = new BasicDBObject(); + res.put("name", serverInfo.get("name")); + res.put("ip", serverInfo.get("ip")); + res.put("port", serverInfo.get("port")); + res.put("server_id", serverInfo.get("server_id")); + res.put("state", serverInfo.get("state")); + res.put("open_time", serverInfo.get("open_time")); + serverList.add(res); + } + + //获取我的服务器列表 + Map userServerInfoMap = BaseGlobal.redisApp.hgetAll(RedisKey.USER_SERVER_INFO, openId, UserServerInfo.class, -1, false); + List myServerList = new ArrayList<>(); + for (Map.Entry entry : userServerInfoMap.entrySet()) { + DBObject res = new BasicDBObject(); + res.put("server_id", entry.getKey()); + res.put("login_time", entry.getValue().getLoginTime()); + myServerList.add(res); + } + DBObject resp = new BasicDBObject(); + resp.put("serverList", serverList); + resp.put("myServerList", myServerList); + out.print(resp.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + out.flush(); + out.close(); + } + + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + this.doGet(request, response); + } +} diff --git a/src/main/java/com/ljsd/controller/GetUserController.java b/src/main/java/com/ljsd/controller/GetUserController.java new file mode 100644 index 0000000..155ad0c --- /dev/null +++ b/src/main/java/com/ljsd/controller/GetUserController.java @@ -0,0 +1,68 @@ +package com.ljsd.controller; + +import com.ljsd.redis.RedisKey; +import com.ljsd.util.BaseGlobal; +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.List; +import java.util.Random; + +public class GetUserController extends HttpServlet { + private final static String _COLLECTION_NAME = "user_info"; + + public GetUserController() { + super(); + } + + public void destroy() { + super.destroy(); + } + + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String openId = request.getParameter("openId"); + String serverId = request.getParameter("serverId"); + DBObject dbObject = new BasicDBObject(); + dbObject.put("openId", openId); + dbObject.put("serverId", serverId); + try { + int uid = 0; + List userInfos = BaseGlobal.mongoDBPool.find(_COLLECTION_NAME, dbObject); + DBObject res = new BasicDBObject(); + if (userInfos.size() == 0) { + uid = BaseGlobal.mongoDBPool.inc("uid"); + dbObject.put("uid", uid); + userInfos.add(dbObject); + BaseGlobal.mongoDBPool.save(_COLLECTION_NAME, dbObject); + } + Random random = new Random(); + int token = random.nextInt(); + uid = (int) userInfos.get(0).get("uid"); + res.put("uid", uid); + res.put("token", token); + BaseGlobal.redisApp.set(RedisKey.TOKEN, String.valueOf(uid), token, -1, false); + PrintWriter out = response.getWriter(); + out.print(res); + out.flush(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + this.doGet(request, response); + } + +} diff --git a/src/main/java/com/ljsd/controller/IndexController.java b/src/main/java/com/ljsd/controller/IndexController.java new file mode 100644 index 0000000..20c3c6e --- /dev/null +++ b/src/main/java/com/ljsd/controller/IndexController.java @@ -0,0 +1,25 @@ +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(); + } + + public void destroy() { + super.destroy(); + } + + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + response.sendRedirect("/index.jsp"); + + } +} diff --git a/src/main/java/com/ljsd/controller/RegistController.java b/src/main/java/com/ljsd/controller/RegistController.java new file mode 100644 index 0000000..484d2aa --- /dev/null +++ b/src/main/java/com/ljsd/controller/RegistController.java @@ -0,0 +1,62 @@ +package com.ljsd.controller; + +import com.ljsd.util.BaseGlobal; +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; + +public class RegistController extends HttpServlet { + public RegistController() { + super(); + } + + public void destroy() { + super.destroy(); + } + + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + this.doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + //int serverId = BaseGlobal.mongoDBPool.inc("server_id"); + int serverId = 0; + request.setCharacterEncoding("utf-8"); + String name = request.getParameter("name"); + String ip = request.getParameter("ip"); + String port = request.getParameter("port"); + String server_id = request.getParameter("server_id"); + String channel = request.getParameter("channel"); + String sub_channel = request.getParameter("sub_channel"); + String plat = request.getParameter("plat"); + String state = request.getParameter("state"); + String open_time = request.getParameter("open_time"); + DBObject doc = new BasicDBObject(); + doc.put("_id", serverId); + doc.put("name", name); + doc.put("ip", ip); + doc.put("port", port); + doc.put("server_id", server_id); + doc.put("channel", channel); + doc.put("sub_channel", sub_channel); + doc.put("plat", plat); + doc.put("state", state); + doc.put("open_time", open_time); + BaseGlobal.mongoDBPool.save("server_info", doc); + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("add suc"); + out.flush(); + out.close(); + + } +} diff --git a/src/main/java/com/ljsd/listener/WebContextListener.java b/src/main/java/com/ljsd/listener/WebContextListener.java new file mode 100644 index 0000000..2d3bcea --- /dev/null +++ b/src/main/java/com/ljsd/listener/WebContextListener.java @@ -0,0 +1,36 @@ +package com.ljsd.listener; + +import com.ljsd.util.BaseGlobal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import java.io.InputStream; + +//创建的类名根据需要定义,但一定要实现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 arg0) { + // TODO Auto-generated method stub + LOGGER.debug("dddddddddddddddddddddddddddddddd"); + try { + InputStream inputStream = getClass().getResourceAsStream(DEFAULT_CONFIG_PATH); + if (inputStream != null) { + BaseGlobal.properties.load(inputStream); + } + BaseGlobal.init(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @Override + public void contextDestroyed(ServletContextEvent arg0) { + // TODO Auto-generated method stub + + } +} \ No newline at end of file diff --git a/src/main/java/com/ljsd/pojo/UserServerInfo.java b/src/main/java/com/ljsd/pojo/UserServerInfo.java new file mode 100644 index 0000000..6aae8dc --- /dev/null +++ b/src/main/java/com/ljsd/pojo/UserServerInfo.java @@ -0,0 +1,13 @@ +package com.ljsd.pojo; + +public class UserServerInfo { + private long loginTime; + + public long getLoginTime() { + return loginTime; + } + + public void setLoginTime(long loginTime) { + this.loginTime = loginTime; + } +} diff --git a/src/main/java/com/ljsd/redis/RedisApp.java b/src/main/java/com/ljsd/redis/RedisApp.java new file mode 100644 index 0000000..08ebb0f --- /dev/null +++ b/src/main/java/com/ljsd/redis/RedisApp.java @@ -0,0 +1,301 @@ +package com.ljsd.redis; + +import com.alibaba.fastjson.JSON; + +import java.util.*; + +public class RedisApp { + private final static String Delimiter_colon = ":"; + private RedisUtil redisUtil = new RedisUtil(); + private String areaId = "0"; + + public RedisApp() { + redisUtil.init(); + } + + private String getKey(String type, K key, boolean withServerId) { + if (withServerId) { + return areaId + Delimiter_colon + type + Delimiter_colon + String.valueOf(key); + } else { + return type + Delimiter_colon + String.valueOf(key); + } + } + + /***************************************普通键值对操作***************************************/ + //设置键值 + public 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 void set(final String type, final String key, T value, final int seconds) throws Exception { + set(type, key, value, seconds, true); + } + + //取得键值 + public T get(final String type, final K key, final Class 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 T get(final String type, final K key, final Class clazz, final int seconds) throws Exception { + return get(type, key, clazz, seconds, true); + } + + //取得键值 + public void del(final String type, final K key, final boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + redisUtil.del(fullKey); + } + + public void del(final String type, final K key) throws Exception { + del(type, key, true); + } + + public boolean exists(final String type, final K key, final boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + return redisUtil.exists(fullKey); + } + + public boolean exists(final String type, final K key) throws Exception { + return exists(type, key, true); + } + + //设置过期时间 + public 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 Map converStringMap(Map mapValues) { + Map map = new HashMap(); + for (Map.Entry entry : mapValues.entrySet()) { + String strKey = String.valueOf(entry.getKey()); + String strValue = JSON.toJSONString(entry.getValue()); + map.put(strKey, strValue); + } + return map; + } + + //设置map的 + public void hmset(final String type, final K key, final Map hash, int seconds, + boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + Map strHash = converStringMap(hash); + redisUtil.hmset(fullKey, strHash, seconds); + } + + public void hmset(final String type, final K key, final Map hash, final int seconds) throws Exception { + hmset(type, key, hash, seconds, true); + } + + //取得map下的子key + public Set 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 Set hkeys(final String type, final K key, final int seconds) throws Exception { + return hkeys(type, key, seconds, true); + } + + //设置redis map一个键值 下的子key下的值 + public 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 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 Map converClassMap(final Map mapValues, final Class valueClazz) { + Map map = new HashMap<>(); + for (Map.Entry entry : mapValues.entrySet()) { + T value = JSON.parseObject(entry.getValue(), valueClazz); + map.put(entry.getKey(), value); + } + return map; + } + + //取redis map全部数据的直接方法 + public Map hgetAll(final String type, final String key, + final Class valueClazz, int seconds, + boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + Map mapValues = redisUtil.hgetAll(fullKey); + return converClassMap(mapValues, valueClazz); + } + + public Map hgetAll(final String type, final String key, + final Class valueClazz, int seconds) throws Exception { + return hgetAll(type, key, valueClazz, seconds, true); + } + + //获取redis map下一个key的值的直接方法 + public T hmget(final String type, final K key, final SK field, final Class clazz, int seconds, + boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + String strField = String.valueOf(field); + List listStrs = redisUtil.hmget(fullKey, strField); + if (listStrs == null || listStrs.size() <= 0) { + return null; + } + return JSON.parseObject(listStrs.get(0), clazz); + } + + public T hmget(final String type, final K key, final SK field, final Class clazz, int seconds) throws Exception { + return hmget(type, key, field, clazz, seconds, true); + } + + //删除子key + public 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 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 long lpush(final String type, final K key, final int seconds, final T... strings) throws Exception { + return lpush(type, key, seconds, true, strings); + } + + + //从左面保留 + public 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 T rpop(final String type, final K key, final Class clazz, boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + String strValue = redisUtil.rpop(fullKey); + return JSON.parseObject(strValue, clazz); + } + + public T rpop(final String type, final K key, final Class clazz) throws Exception { + return rpop(type, key, clazz); + } + + //添加一个新的元素,如果list超过了count,则删除最早的 + public 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 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 List converClassList(final List listValues, final Class clazz) { + List list = new ArrayList<>(); + for (String strValue : listValues) { + T value = JSON.parseObject(strValue, clazz); + list.add(value); + } + + return list; + } + + //从头开始,向未取数据 + public List lrange(final String type, final K key, final Class clazz, + final long start, final long end, + final int seconds, boolean withServerId) throws Exception { + String fullKey = getKey(type, key, withServerId); + List listValues = redisUtil.lrange(fullKey, start, end); + return converClassList(listValues, clazz); + } + + public List lrange(final String type, final K key, final Class clazz, + final long start, final long end, final int seconds) throws Exception { + return lrange(type, key, clazz, start, end, seconds, true); + } + + //取得list的全部数据 + public List lgetAll(final String type, final K key, final Class clazz, final int seconds, + boolean withServerId) throws Exception { + return lrange(type, key, clazz, 0, -1, seconds, withServerId); + } + + public List lgetAll(final String type, final K key, final Class clazz, final int seconds) throws Exception { + return lgetAll(type, key, clazz, seconds, true); + } + + //自增 + 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); + } +} diff --git a/src/main/java/com/ljsd/redis/RedisKey.java b/src/main/java/com/ljsd/redis/RedisKey.java new file mode 100644 index 0000000..ad8e10c --- /dev/null +++ b/src/main/java/com/ljsd/redis/RedisKey.java @@ -0,0 +1,10 @@ +package com.ljsd.redis; + +public interface RedisKey { + String TOKEN = "TOKEN"; + + /** + * 最近登录服务器列表 + */ + String USER_SERVER_INFO = "USER_SERVER_INFO"; +} diff --git a/src/main/java/com/ljsd/redis/RedisUtil.java b/src/main/java/com/ljsd/redis/RedisUtil.java new file mode 100644 index 0000000..f6693fd --- /dev/null +++ b/src/main/java/com/ljsd/redis/RedisUtil.java @@ -0,0 +1,421 @@ +package com.ljsd.redis; + +import com.ljsd.util.BaseGlobal; +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 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;//非切片连接池 + + 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"))); + jedisPool = new JedisPool(config, BaseGlobal.properties.getProperty("redis_host"), Integer.parseInt(BaseGlobal.properties.getProperty("redis_port"))); + } + + /***************************************普通键值对操作***************************************/ + //设置键值 + protected void set(final String key, String value) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 hash, int seconds) throws Exception { + int i; + for (i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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 hkeys(final String key) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.getResource(); + try { + Set 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 = jedisPool.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 hgetAll(final String key) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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 hmget(final String key, final String... fields) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 = jedisPool.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 lrange(final String key, final long start, final long end) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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 = jedisPool.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 = jedisPool.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 超期时间,理论上应该比较短,一次请求在500毫秒内即可完成,因此过期时间不应大于1秒 + * @return 是否获取成功 + */ + protected boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) throws Exception { + for (int i = 0; i < MAX_TRY_TIMES; i++) { + Jedis jedis = jedisPool.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(); + } + } + throw new Exception("RedisUtil::tryGetDistributedLock 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 = jedisPool.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"); + } +} diff --git a/src/main/java/com/ljsd/util/BaseGlobal.java b/src/main/java/com/ljsd/util/BaseGlobal.java new file mode 100644 index 0000000..d7bc521 --- /dev/null +++ b/src/main/java/com/ljsd/util/BaseGlobal.java @@ -0,0 +1,16 @@ +package com.ljsd.util; + +import com.ljsd.redis.RedisApp; + +import java.util.Properties; + +public class BaseGlobal { + public static Properties properties = new Properties(); + public static MyMongoDBPool mongoDBPool; + public static RedisApp redisApp; + + public static void init() { + mongoDBPool = new MyMongoDBPool(); + redisApp = new RedisApp(); + } +} diff --git a/src/main/java/com/ljsd/util/MyMongoDBPool.java b/src/main/java/com/ljsd/util/MyMongoDBPool.java new file mode 100644 index 0000000..b705a87 --- /dev/null +++ b/src/main/java/com/ljsd/util/MyMongoDBPool.java @@ -0,0 +1,108 @@ +package com.ljsd.util; + +import com.mongodb.*; + +import java.util.ArrayList; +import java.util.List; + +/* + * mongodb数据库链接池 + */ +public class MyMongoDBPool { + private MongoClient mongoClient = null; + private String dbName; + private DB db; + + 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(); + mongoClient = new MongoClient(new ServerAddress(BaseGlobal.properties.getProperty("mongodb_host"), Integer.parseInt(BaseGlobal.properties.getProperty("mongodb_port"))), + 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 find(String collectionName, DBObject object) throws Exception { + DBCollection coll = db.getCollection(collectionName); + DBCursor cursor = coll.find(object); + List docs = new ArrayList<>(); + while (cursor.hasNext()) { + DBObject doc = cursor.next(); + docs.add(doc); + } + return docs; + } + + public String findList(String collectionName) throws Exception { + DBCollection coll = db.getCollection(collectionName); + DBCursor cursor = coll.find(); + List docs = new ArrayList<>(); + + while (cursor.hasNext()) { + DBObject doc = cursor.next(); + docs.add(doc); + } + return docs.toString(); + } + + + 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 int inc(String collectionName, String id, String key) { + DBCollection collection = db.getCollection(collectionName); + BasicDBObject searchQuery = new BasicDBObject(); + searchQuery.put("_id", id); + // 使用collection的find方法查找document + DBCursor cursor = collection.find(searchQuery); + // 循环输出结果 + if (cursor.hasNext()) { + BasicDBObject update = new BasicDBObject().append("$inc", new BasicDBObject().append(key, 1)); + DBObject query = cursor.next(); + DBObject result = collection.findAndModify(query, update); + return Integer.valueOf(result.get(key).toString()) + 1; + } else { + searchQuery.put(key, 1); + collection.insert(searchQuery); + return 1; + } + } + + public int inc(String key) { + return inc("inc_c", "inc_k", key); + } +} \ No newline at end of file diff --git a/src/main/java/com/ljsd/util/TimeUtil.java b/src/main/java/com/ljsd/util/TimeUtil.java new file mode 100644 index 0000000..76a3abb --- /dev/null +++ b/src/main/java/com/ljsd/util/TimeUtil.java @@ -0,0 +1,77 @@ +package com.ljsd.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + + +/** + * 时间的工具类 + */ +public class TimeUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(TimeUtil.class); + + private final static SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss"); + + public static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (Exception e) { + LOGGER.error("sleep->msg=null", e.getMessage(), e); + } + } + + public static boolean inCorrectTime(String startTime, String endTime) throws Exception { + long now = System.currentTimeMillis(); + long start = sdf.parse(startTime).getTime(); + long end = sdf.parse(endTime).getTime(); + if (now < start) { + 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; + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..519f1e0 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,31 @@ +#mogodb服务地址 +mongodb_host = 60.1.1.14 +#mogodb服务端口 +mongodb_port = 27017 +#数据库名 +mongodb_name=zhj_core + +#与目标数据库可以建立的最大链接数 +mongodb_maximumNumberOfConnections = 100 +#与数据库建立链接的超时时间 2分钟 +mongodb_connectTimeout = 1200000 +#一个线程成功获取到一个可用数据库之前的最大等待时间 3秒 +mongodb_maxWaitTime = 30000 +#最多xx个线程等级一个链接,推荐配置为5 +mongodb_threadsAllowedToBlockForConnectionMultiplier = 5 +#最大空闲时间,为0时,表示没有限制 +mongodb_maxConnectionIdleTime = 0 +#最大生存时间,为0时,表示没有限制 +mongodb_maxConnectionLifeTime = 0 +#连接过期时间 +mongodb_socketTimeout = 0 +#连接保持活跃 +mongodb_socketKeepAlive = true + +redis_host = 60.1.1.14 +redis_port = 6379 +redis_maxTotal = 10 +redis_minIdle = 3 +redis_maxWaitMillis = 20 +redis_maxIdle = 5 +redis_testOnBorrow = false \ No newline at end of file diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..592b778 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,50 @@ + + YSJLogging + + + + + + + + + + + [%level] - %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] - %logger{0}#%line - ${tip}:%msg%n + + + INFO + ACCEPT + ACCEPT + + + + + + + + [%level] - %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] - %logger{0}#%line - ${tip}:%msg%n + + + + + ${log_dir}/%d{yyyy-MM-dd}.log + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..d4ac6d4 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,59 @@ + + + + + + logbackConfigLocation + classpath:main/resources/logback.xml + + + + index + com.ljsd.controller.IndexController + + + + index + / + + + + getServerList + com.ljsd.controller.GetServerListController + + + + getServerList + /getServerList + + + + regist + com.ljsd.controller.RegistController + + + + regist + /regist + + + + getUserInfo + com.ljsd.controller.GetUserController + + + + getUserInfo + /getUserInfo + + + + + + com.ljsd.listener.WebContextListener + + + \ No newline at end of file diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp new file mode 100644 index 0000000..c4ffa26 --- /dev/null +++ b/src/main/webapp/index.jsp @@ -0,0 +1,34 @@ +<%-- + 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" %> + + + 注册服务器 + + +
+

name:

+

ip:

+

port:

+

server_id:

+

channel:

+

sub_channel:

+

plat:

+

state:

+

open_time:

+ +
+ +