├── .gitignore ├── LICENSE ├── README.md ├── assembly.xml ├── bin ├── env-mp.sh ├── mp.sh └── set-env.sh ├── conf ├── conf-dev.properties └── conf-pub.properties ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── shinemo │ │ └── mpush │ │ └── alloc │ │ ├── AllocHandler.java │ │ ├── AllocServer.java │ │ ├── HttpServerCreator.java │ │ ├── IndexPageHandler.java │ │ ├── Main.java │ │ └── PushHandler.java └── resources │ ├── index.html │ ├── logback.xml │ └── mpush.conf └── test ├── java └── com │ └── shinemo │ └── mpush │ └── alloc │ └── AllocServerMainTest.java └── resources ├── application.conf └── logback.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.classpath 3 | *.project 4 | */.settings/* 5 | */target/* 6 | */bin/* 7 | */WebContent/* 8 | /*/*.iml 9 | 10 | .idea/ 11 | 12 | /target/ 13 | 14 | 15 | # Mobile Tools for Java (J2ME) 16 | .mtj.tmp/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.ear 22 | *.iml 23 | .DS_Store 24 | 25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 26 | hs_err_pid* 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # alloc 2 | mpush allocator demo 3 | 4 | ### 服务用途 5 | 6 | > * alloc 是针对client提供的一个轻量级的负载均衡服务 7 | > * 每次客户端在链接MPUSH server之前都要调用下该服务 8 | > * 以获取可用的MPUSH server列表,然后按顺序去尝试建立TCP链接,直到链接建立成功 9 | 10 | ### 对外提供的接口定义 11 | 12 | > 接口类型 :HTTP 13 | > 14 | > Method : GET 15 | > 16 | > 参数 :无 17 | > 18 | > 返回值格式 : ip:port,ip:port 19 | > 20 | > content-type : text/plain;charset=utf-8 21 | 22 | ### 其他 23 | 24 | 25 | -------------------------------------------------------------------------------- /assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | release-${project.version} 4 | mpush-alloc-${project.version} 5 | true 6 | 7 | tar.gz 8 | 9 | 10 | 11 | ./ 12 | 13 | 14 | LICENSE 15 | README.md 16 | 17 | 18 | 19 | ./bin/ 20 | bin 21 | 22 | *.sh 23 | *.cmd 24 | 25 | 26 | 27 | target/classes/ 28 | conf 29 | 30 | mpush.conf 31 | logback.xml 32 | 33 | 34 | 35 | target/ 36 | bin 37 | 38 | bootstrap.jar 39 | 40 | 41 | 42 | 43 | 44 | false 45 | runtime 46 | false 47 | lib 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /bin/env-mp.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one or more 4 | # contributor license agreements. See the NOTICE file distributed with 5 | # this work for additional information regarding copyright ownership. 6 | # The ASF licenses this file to You under the Apache License, Version 2.0 7 | # (the "License"); you may not use this file except in compliance with 8 | # the License. You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | # This script should be sourced into other mpush 19 | # scripts to setup the env variables 20 | 21 | # We use MP_CFG_DIR if defined, 22 | # otherwise we use /etc/mp 23 | # or the conf directory that is 24 | # a sibling of this script's directory 25 | 26 | MP_BIN_DIR="${MP_BIN_DIR:-/usr/bin}" 27 | MPUSH_PREFIX="${MP_BIN_DIR}/.." 28 | MPUSH_HOME=$MPUSH_PREFIX 29 | 30 | if [ "x$MP_CFG_DIR" = "x" ] 31 | then 32 | if [ -e "${MPUSH_PREFIX}/conf" ]; then 33 | MP_CFG_DIR="$MP_BIN_DIR/../conf" 34 | else 35 | MP_CFG_DIR="$MP_BIN_DIR/../etc/mpush" 36 | fi 37 | fi 38 | 39 | if [ "x${MP_DATA_DIR}" = "x" ] 40 | then 41 | MP_DATA_DIR="${MPUSH_PREFIX}/tmp" 42 | fi 43 | 44 | if [ "x${MP_LOG_DIR}" = "x" ] 45 | then 46 | MP_LOG_DIR="${MPUSH_PREFIX}/logs" 47 | fi 48 | 49 | if [ -f "${MP_BIN_DIR}/set-env.sh" ]; then 50 | . "${MP_BIN_DIR}/set-env.sh" 51 | fi 52 | 53 | if [ "x$MP_CFG" = "x" ] 54 | then 55 | MP_CFG="mpush.conf" 56 | fi 57 | 58 | MP_CFG="$MP_CFG_DIR/$MP_CFG" 59 | 60 | if [ -f "$MP_BIN_DIR/java.env" ] 61 | then 62 | . "$MP_BIN_DIR/java.env" 63 | fi 64 | 65 | if [ "x${MP_LOG4J_PROP}" = "x" ] 66 | then 67 | MP_LOG4J_PROP="INFO,CONSOLE" 68 | fi 69 | 70 | if [ "$JAVA_HOME" != "" ]; then 71 | JAVA="$JAVA_HOME/bin/java" 72 | else 73 | JAVA=java 74 | fi 75 | 76 | 77 | #add the conf dir to classpath 78 | CLASSPATH="$MP_CFG_DIR:$CLASSPATH" 79 | 80 | #make it work in the binary package 81 | #(use array for LIB_PATH to account for spaces within wildcard expansion) 82 | if [ -e "${MPUSH_PREFIX}"/../lib/plugins/*.jar ]; then 83 | LIB_PATH=("${MPUSH_PREFIX}"/../lib/plugins/*.jar) 84 | fi 85 | 86 | for i in "${LIB_PATH[@]}" 87 | do 88 | CLASSPATH="$i:$CLASSPATH" 89 | done 90 | 91 | case "`uname`" in 92 | CYGWIN*) cygwin=true ;; 93 | *) cygwin=false ;; 94 | esac 95 | 96 | if $cygwin 97 | then 98 | CLASSPATH=`cygpath -wp "$CLASSPATH"` 99 | fi 100 | -------------------------------------------------------------------------------- /bin/mp.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Licensed to the Apache Software Foundation (ASF) under one or more 4 | # contributor license agreements. See the NOTICE file distributed with 5 | # this work for additional information regarding copyright ownership. 6 | # The ASF licenses this file to You under the Apache License, Version 2.0 7 | # (the "License"); you may not use this file except in compliance with 8 | # the License. You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | # 19 | # If this scripted is run out of /usr/bin or some other system bin directory 20 | # it should be linked to and not copied. Things like java jar files are found 21 | # relative to the canonical path of this script. 22 | # 23 | 24 | 25 | 26 | # use POSTIX interface, symlink is followed automatically 27 | MP_BIN="${BASH_SOURCE-$0}" 28 | MP_BIN="$(dirname "${MP_BIN}")" 29 | MP_BIN_DIR="$(cd "${MP_BIN}"; pwd)" 30 | 31 | if [ -e "$MP_BIN/../libexec/env-mp.sh" ]; then 32 | . "$MP_BIN_DIR/../libexec/env-mp.sh" 33 | else 34 | . "$MP_BIN_DIR/env-mp.sh" 35 | fi 36 | 37 | # See the following page for extensive details on setting 38 | # up the JVM to accept JMX remote management: 39 | # http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html 40 | # by default we allow local JMX connections 41 | if [ "x$JMXLOCALONLY" = "x" ] 42 | then 43 | JMXLOCALONLY=false 44 | fi 45 | 46 | if [ "x$JMXDISABLE" = "x" ] || [ "$JMXDISABLE" = 'false' ] 47 | then 48 | echo "MPush JMX enabled by default" >&2 49 | if [ "x$JMXPORT" = "x" ] 50 | then 51 | # for some reason these two options are necessary on jdk6 on Ubuntu 52 | # accord to the docs they are not necessary, but otw jconsole cannot 53 | # do a local attach 54 | MP_MAIN="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=$JMXLOCALONLY" 55 | else 56 | if [ "x$JMXAUTH" = "x" ] 57 | then 58 | JMXAUTH=false 59 | fi 60 | if [ "x$JMXSSL" = "x" ] 61 | then 62 | JMXSSL=false 63 | fi 64 | if [ "x$JMXLOG4J" = "x" ] 65 | then 66 | JMXLOG4J=true 67 | fi 68 | echo "MPush remote JMX Port set to $JMXPORT" >&2 69 | echo "MPush remote JMX authenticate set to $JMXAUTH" >&2 70 | echo "MPush remote JMX ssl set to $JMXSSL" >&2 71 | echo "MPush remote JMX log4j set to $JMXLOG4J" >&2 72 | MP_MAIN="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=$JMXPORT -Dcom.sun.management.jmxremote.authenticate=$JMXAUTH -Dcom.sun.management.jmxremote.ssl=$JMXSSL -Dmpush.jmx.log4j.disable=$JMXLOG4J" 73 | fi 74 | else 75 | echo "JMX disabled by user request" >&2 76 | MP_MAIN="" 77 | fi 78 | 79 | MP_MAIN="$MP_MAIN -jar $MP_BIN_DIR/bootstrap.jar" 80 | 81 | if [ "x$SERVER_JVM_FLAGS" != "x" ] 82 | then 83 | JVM_FLAGS="$SERVER_JVM_FLAGS $JVM_FLAGS" 84 | fi 85 | 86 | if [ "x$2" != "x" ] 87 | then 88 | MP_CFG="$MP_CFG_DIR/$2" 89 | fi 90 | 91 | # if we give a more complicated path to the config, don't screw around in $MP_CFG_DIR 92 | if [ "x$(dirname "$MP_CFG")" != "x$MP_CFG_DIR" ] 93 | then 94 | MP_CFG="$2" 95 | fi 96 | 97 | if $cygwin 98 | then 99 | MP_CFG=`cygpath -wp "$MP_CFG"` 100 | # cygwin has a "kill" in the shell itself, gets confused 101 | KILL=/bin/kill 102 | else 103 | KILL=kill 104 | fi 105 | 106 | echo "Using config: $MP_CFG" >&2 107 | 108 | case "$OSTYPE" in 109 | *solaris*) 110 | GREP=/usr/xpg4/bin/grep 111 | ;; 112 | *) 113 | GREP=grep 114 | ;; 115 | esac 116 | if [ -z "$MP_PID_FILE" ]; then 117 | # MP_DATA_DIR="$($GREP "^[[:space:]]*dataDir" "$MP_CFG" | sed -e 's/.*=//')" 118 | if [ ! -d "$MP_DATA_DIR" ]; then 119 | mkdir -p "$MP_DATA_DIR" 120 | fi 121 | MP_PID_FILE="$MP_DATA_DIR/mpush_server.pid" 122 | else 123 | # ensure it exists, otw stop will fail 124 | mkdir -p "$(dirname "$MP_PID_FILE")" 125 | fi 126 | 127 | if [ ! -w "$MP_LOG_DIR" ] ; then 128 | mkdir -p "$MP_LOG_DIR" 129 | fi 130 | 131 | _MP_DAEMON_OUT="$MP_LOG_DIR/mpush.out" 132 | 133 | case $1 in 134 | start) 135 | echo -n "Starting mpush ... " 136 | if [ -f "$MP_PID_FILE" ]; then 137 | if kill -0 `cat "$MP_PID_FILE"` > /dev/null 2>&1; then 138 | echo $command already running as process `cat "$MP_PID_FILE"`. 139 | exit 0 140 | fi 141 | fi 142 | nohup "$JAVA" "-Dmp.home=$MPUSH_HOME" "-Dmp.conf=$MP_CFG" -cp "$CLASSPATH" $JVM_FLAGS $MP_MAIN > "$_MP_DAEMON_OUT" 2>&1 < /dev/null & 143 | if [ $? -eq 0 ] 144 | then 145 | case "$OSTYPE" in 146 | *solaris*) 147 | /bin/echo "${!}\\c" > "$MP_PID_FILE" 148 | ;; 149 | *) 150 | /bin/echo -n $! > "$MP_PID_FILE" 151 | ;; 152 | esac 153 | if [ $? -eq 0 ]; 154 | then 155 | sleep 1 156 | echo STARTED 157 | else 158 | echo FAILED TO WRITE PID 159 | exit 1 160 | fi 161 | else 162 | echo SERVER DID NOT START 163 | exit 1 164 | fi 165 | ;; 166 | start-foreground) 167 | "$JAVA" "-Dmp.home=$MPUSH_HOME" "-Dmp.conf=$MP_CFG" -cp "$CLASSPATH" $JVM_FLAGS $MP_MAIN 168 | ;; 169 | print-cmd) 170 | echo "\"$JAVA\" $MP_MAIN " 171 | echo "\"-Dmp.home=$MPUSH_HOME -Dmp.conf=$MP_CFG\" " 172 | echo "$JVM_FLAGS " 173 | echo "-cp \"$CLASSPATH\" " 174 | echo "> \"$_MP_DAEMON_OUT\" 2>&1 < /dev/null" 175 | ;; 176 | stop) 177 | echo "Stopping mpush ... " 178 | if [ ! -f "$MP_PID_FILE" ] 179 | then 180 | echo "no mpush to stop (could not find file $MP_PID_FILE)" 181 | else 182 | $KILL -15 $(cat "$MP_PID_FILE") 183 | SLEEP=30 184 | SLEEP_COUNT=1 185 | while [ $SLEEP -ge 0 ]; do 186 | kill -0 $(cat "$MP_PID_FILE") >/dev/null 2>&1 187 | if [ $? -gt 0 ]; then 188 | rm -f "$MP_PID_FILE" >/dev/null 2>&1 189 | if [ $? != 0 ]; then 190 | if [ -w "$MP_PID_FILE" ]; then 191 | cat /dev/null > "$MP_PID_FILE" 192 | else 193 | echo "The PID file could not be removed or cleared." 194 | fi 195 | fi 196 | echo STOPPED 197 | break 198 | fi 199 | if [ $SLEEP -gt 0 ]; then 200 | echo "stopping ... $SLEEP_COUNT" 201 | sleep 1 202 | fi 203 | if [ $SLEEP -eq 0 ]; then 204 | echo "MPUSH did not stop in time." 205 | echo "To aid diagnostics a thread dump has been written to standard out." 206 | kill -3 `cat "$MP_PID_FILE"` 207 | echo "force stop MPUSH." 208 | kill -9 `cat "$MP_PID_FILE"` 209 | echo STOPPED 210 | fi 211 | SLEEP=`expr $SLEEP - 1` 212 | SLEEP_COUNT=`expr $SLEEP_COUNT + 1` 213 | done 214 | fi 215 | exit 0 216 | ;; 217 | upgrade) 218 | shift 219 | echo "upgrading the servers to 3.*" 220 | "$JAVA" -cp "$CLASSPATH" $JVM_FLAGS com.mpush.tools.upgrade.UpgradeMain ${@} 221 | echo "Upgrading ... " 222 | ;; 223 | restart) 224 | shift 225 | "$0" stop ${@} 226 | sleep 1 227 | "$0" start ${@} 228 | ;; 229 | status) 230 | # -q is necessary on some versions of linux where nc returns too quickly, and no stat result is output 231 | clientPortAddress=`$GREP "^[[:space:]]*clientPortAddress[^[:alpha:]]" "$MP_CFG" | sed -e 's/.*=//'` 232 | if ! [ $clientPortAddress ] 233 | then 234 | clientPortAddress="localhost" 235 | fi 236 | clientPort=`$GREP "^[[:space:]]*connect-server-port[^[:alpha:]]" "$MP_CFG" | sed -e 's/.*=//'` 237 | telnet 127.0.0.1 3002 238 | ;; 239 | *) 240 | echo "Usage: $0 {start|start-foreground|stop|restart|status|upgrade|print-cmd}" >&2 241 | 242 | esac -------------------------------------------------------------------------------- /bin/set-env.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | #开启远程调试 3 | #JVM_FLAGS="$JVM_FLAGS -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8008" 4 | 5 | #GC配置 6 | #运行模式 整个堆内存大小 GC算法 7 | #JVM_FLAGS="$JVM_FLAGS -server -Xmx1024m -Xms1024m -XX:+UseG1GC -XX:MaxGCPauseMillis=200" 8 | #GC日志 发生OOM时创建堆内存转储文件 9 | #JVM_FLAGS="$JVM_FLAGS -Xloggc:$MP_LOG_DIR/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps" 10 | #发生OOM后的操作 11 | #JVM_FLAGS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$MP_LOG_DIR -XX:OnOutOfMemoryError=$MP_BIN_DIR/restart.sh" -------------------------------------------------------------------------------- /conf/conf-dev.properties: -------------------------------------------------------------------------------- 1 | log.level=debug 2 | min.hb=10s -------------------------------------------------------------------------------- /conf/conf-pub.properties: -------------------------------------------------------------------------------- 1 | log.level=warn 2 | min.hb=3m -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mpush 8 | alloc 9 | 0.8.0 10 | mpush-alloc 11 | mpush Server Allocator 12 | https://github.com/mpusher/mpush 13 | 14 | 15 | 16 | The Apache Software License, Version 2.0 17 | http://www.apache.org/licenses/LICENSE-2.0.txt 18 | repo 19 | 20 | 21 | 22 | 23 | master 24 | git@github.com:mpusher/mpush-client-java.git 25 | scm:git@github.com:mpusher/mpush-client-java.git 26 | scm:git@github.com:mpusher/mpush-client-java.git 27 | 28 | 29 | 30 | 31 | ohun 32 | ohun@live.cn 33 | mpusher 34 | 35 | 36 | 37 | 38 | UTF-8 39 | UTF-8 40 | UTF-8 41 | 1.8 42 | 43 | 44 | 45 | 46 | com.github.mpusher 47 | mpush-client 48 | 0.8.0 49 | 50 | 51 | 52 | 53 | bootstrap 54 | 55 | conf/conf-${deploy.env}.properties 56 | 57 | 58 | 59 | src/main/resources 60 | 61 | **/* 62 | 63 | true 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-compiler-plugin 70 | 3.1 71 | 72 | ${java.version} 73 | ${java.version} 74 | ${java.encoding} 75 | 76 | 77 | 78 | maven-resources-plugin 79 | 80 | ${java.encoding} 81 | 82 | 83 | 84 | org.apache.maven.plugins 85 | maven-surefire-plugin 86 | 2.4.2 87 | 88 | true 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | dev 97 | 98 | true 99 | 100 | 101 | dev 102 | 103 | 104 | 105 | pub 106 | 107 | pub 108 | 109 | 110 | 111 | zip 112 | 113 | 114 | 115 | maven-jar-plugin 116 | 117 | 118 | 119 | false 120 | 121 | 122 | 123 | true 124 | 125 | ../lib/ 126 | 127 | com.shinemo.mpush.alloc.Main 128 | 129 | 130 | 131 | 132 | 133 | package 134 | 135 | 136 | 137 | 138 | maven-assembly-plugin 139 | 2.6 140 | 141 | alloc 142 | 143 | assembly.xml 144 | 145 | 146 | 147 | 148 | package 149 | 150 | single 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/AllocHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Contributors: 17 | * ohun@live.cn (夜色) 18 | */ 19 | 20 | package com.shinemo.mpush.alloc; 21 | 22 | import com.mpush.api.Constants; 23 | import com.mpush.api.spi.common.CacheManagerFactory; 24 | import com.mpush.api.spi.common.ServiceDiscoveryFactory; 25 | import com.mpush.api.srd.ServiceDiscovery; 26 | import com.mpush.api.srd.ServiceListener; 27 | import com.mpush.api.srd.ServiceNames; 28 | import com.mpush.api.srd.ServiceNode; 29 | import com.mpush.common.user.UserManager; 30 | import com.sun.net.httpserver.HttpExchange; 31 | import com.sun.net.httpserver.HttpHandler; 32 | 33 | import java.io.IOException; 34 | import java.io.OutputStream; 35 | import java.util.Collections; 36 | import java.util.Iterator; 37 | import java.util.List; 38 | import java.util.concurrent.Executors; 39 | import java.util.concurrent.ScheduledExecutorService; 40 | import java.util.concurrent.TimeUnit; 41 | import java.util.stream.Collectors; 42 | 43 | /** 44 | * Created by ohun on 16/9/22. 45 | * 46 | * @author ohun@live.cn (夜色) 47 | */ 48 | /*package*/ final class AllocHandler implements HttpHandler { 49 | 50 | private List serverNodes = Collections.emptyList(); 51 | private ScheduledExecutorService scheduledExecutor; 52 | private final ServiceDiscovery discovery = ServiceDiscoveryFactory.create(); 53 | private final UserManager userManager = new UserManager(null); 54 | 55 | public void start() { 56 | CacheManagerFactory.create().init(); //启动缓冲服务 57 | 58 | ServiceDiscovery discovery = ServiceDiscoveryFactory.create();// 启动发现服务 59 | discovery.syncStart(); 60 | discovery.subscribe(ServiceNames.CONN_SERVER, new ConnServerNodeListener()); 61 | 62 | 63 | scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); 64 | scheduledExecutor.scheduleAtFixedRate(this::refresh, 0, 5, TimeUnit.MINUTES); 65 | } 66 | 67 | public void stop() { 68 | discovery.syncStop(); 69 | CacheManagerFactory.create().destroy(); 70 | scheduledExecutor.shutdown(); 71 | } 72 | 73 | public void handle(HttpExchange httpExchange) throws IOException { 74 | //3.格式组装 ip:port,ip:port 75 | StringBuilder sb = new StringBuilder(); 76 | Iterator it = serverNodes.iterator(); 77 | if (it.hasNext()) { 78 | ServerNode node = it.next(); 79 | sb.append(node.host).append(':').append(node.port); 80 | } 81 | 82 | while (it.hasNext()) { 83 | ServerNode node = it.next(); 84 | sb.append(',').append(node.host).append(':').append(node.port); 85 | } 86 | 87 | byte[] data = sb.toString().getBytes(Constants.UTF_8); 88 | httpExchange.sendResponseHeaders(200, data.length);//200, content-length 89 | OutputStream out = httpExchange.getResponseBody(); 90 | out.write(data); 91 | out.close(); 92 | httpExchange.close(); 93 | } 94 | 95 | /** 96 | * 从zk中获取可提供服务的机器,并以在线用户量排序 97 | */ 98 | private void refresh() { 99 | //1.从缓存中拿取可用的长链接服务器节点 100 | List nodes = discovery.lookup(ServiceNames.CONN_SERVER); 101 | if (nodes.size() > 0) { 102 | //2.对serverNodes可以按某种规则排序,以便实现负载均衡,比如:随机,轮询,链接数量等 103 | this.serverNodes = nodes 104 | .stream() 105 | .map(this::convert) 106 | .sorted(ServerNode::compareTo) 107 | .collect(Collectors.toList()); 108 | } 109 | } 110 | 111 | private long getOnlineUserNum(String publicIP) { 112 | return userManager.getOnlineUserNum(publicIP); 113 | } 114 | 115 | private ServerNode convert(ServiceNode node) { 116 | String public_ip = node.getAttr(ServiceNames.ATTR_PUBLIC_IP); 117 | if (public_ip == null) { 118 | public_ip = node.getHost(); 119 | } 120 | long onlineUserNum = getOnlineUserNum(public_ip); 121 | return new ServerNode(public_ip, node.getPort(), onlineUserNum); 122 | } 123 | 124 | private class ConnServerNodeListener implements ServiceListener { 125 | 126 | @Override 127 | public void onServiceAdded(String s, ServiceNode serviceNode) { 128 | refresh(); 129 | } 130 | 131 | @Override 132 | public void onServiceUpdated(String s, ServiceNode serviceNode) { 133 | refresh(); 134 | } 135 | 136 | @Override 137 | public void onServiceRemoved(String s, ServiceNode serviceNode) { 138 | refresh(); 139 | } 140 | } 141 | 142 | private static class ServerNode implements Comparable { 143 | long onlineUserNum = 0; 144 | String host; 145 | int port; 146 | 147 | public ServerNode(String host, int port, long onlineUserNum) { 148 | this.onlineUserNum = onlineUserNum; 149 | this.host = host; 150 | this.port = port; 151 | } 152 | 153 | @Override 154 | public int compareTo(ServerNode o) { 155 | return Long.compare(onlineUserNum, o.onlineUserNum); 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/AllocServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Contributors: 17 | * ohun@live.cn (夜色) 18 | */ 19 | 20 | package com.shinemo.mpush.alloc; 21 | 22 | import com.mpush.api.service.BaseService; 23 | import com.mpush.api.service.Listener; 24 | import com.mpush.api.service.ServiceException; 25 | import com.mpush.tools.config.CC; 26 | import com.mpush.tools.log.Logs; 27 | import com.sun.net.httpserver.HttpServer; 28 | 29 | import java.io.IOException; 30 | import java.net.InetSocketAddress; 31 | import java.util.concurrent.Executors; 32 | 33 | /** 34 | * Created by yxx on 2016/5/6. 35 | * 36 | * @author ohun@live.cn 37 | */ 38 | public final class AllocServer extends BaseService { 39 | 40 | private HttpServer httpServer; 41 | private AllocHandler allocHandler; 42 | private PushHandler pushHandler; 43 | 44 | @Override 45 | public void init() { 46 | int port = CC.mp.net.cfg.getInt("alloc-server-port"); 47 | boolean https = "https".equals(CC.mp.net.cfg.getString("alloc-server-protocol")); 48 | 49 | this.httpServer = HttpServerCreator.createServer(port, https); 50 | this.allocHandler = new AllocHandler(); 51 | this.pushHandler = new PushHandler(); 52 | 53 | httpServer.setExecutor(Executors.newCachedThreadPool());//设置线程池,由于是纯内存操作,不需要队列 54 | httpServer.createContext("/", allocHandler);//查询mpush机器 55 | httpServer.createContext("/push", pushHandler);//模拟发送push 56 | httpServer.createContext("/index.html", new IndexPageHandler());//查询mpush机器 57 | } 58 | 59 | @Override 60 | protected void doStart(Listener listener) throws Throwable { 61 | pushHandler.start(); 62 | allocHandler.start(); 63 | httpServer.start(); 64 | Logs.Console.info("==================================================================="); 65 | Logs.Console.info("====================ALLOC SERVER START SUCCESS====================="); 66 | Logs.Console.info("==================================================================="); 67 | } 68 | 69 | @Override 70 | protected void doStop(Listener listener) throws Throwable { 71 | httpServer.stop(0);//1 min 72 | pushHandler.stop(); 73 | allocHandler.stop(); 74 | Logs.Console.info("==================================================================="); 75 | Logs.Console.info("====================ALLOC SERVER STOPPED SUCCESS====================="); 76 | Logs.Console.info("==================================================================="); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/HttpServerCreator.java: -------------------------------------------------------------------------------- 1 | /* Copyright rememberjava.com. Licensed under GPL 3. See http://rememberjava.com/license */ 2 | package com.shinemo.mpush.alloc; 3 | 4 | import com.sun.net.httpserver.HttpServer; 5 | import com.sun.net.httpserver.HttpsConfigurator; 6 | import com.sun.net.httpserver.HttpsServer; 7 | 8 | import javax.net.ssl.KeyManagerFactory; 9 | import javax.net.ssl.SSLContext; 10 | import javax.net.ssl.TrustManagerFactory; 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.lang.ProcessBuilder.Redirect; 14 | import java.net.InetSocketAddress; 15 | import java.security.KeyStore; 16 | 17 | /** 18 | * A HTTPS server using a self-signed TLS 1.2 key and certificate generated by 19 | * the Java keytool command. 20 | *

21 | */ 22 | @SuppressWarnings("restriction") 23 | public class HttpServerCreator { 24 | 25 | private static final File KEYSTORE_FILE = new File(System.getProperty("java.io.tmpdir"), "mpush.jks"); 26 | 27 | private static final String KEYSTORE_PASSWORD = "mpush_2017"; 28 | 29 | private static final String KEY_PASSWORD = "mpush_2017"; 30 | 31 | /** 32 | * Generates a new self-signed certificate in /tmp/test.jks, if it does not 33 | * already exist. 34 | */ 35 | private static void generateCertificate() throws Exception { 36 | if (KEYSTORE_FILE.exists()) return; 37 | 38 | System.setProperty("javax.net.debug", "all"); 39 | 40 | File keytool = new File(System.getProperty("java.home"), "bin/keytool"); 41 | 42 | String[] genkeyCmd = new String[]{ 43 | keytool.toString(), 44 | "-genkey", 45 | "-keyalg", "RSA", 46 | "-alias", "mpush.com", 47 | "-validity", "365", 48 | "-keysize", "2048", 49 | "-dname", "cn=mpush.com,ou=mpush,o=OHUN .Inc,c=CN", 50 | "-keystore", KEYSTORE_FILE.getAbsolutePath(), 51 | "-storepass", KEYSTORE_PASSWORD, 52 | "-keypass", KEY_PASSWORD}; 53 | 54 | System.out.println(String.join(" ", genkeyCmd)); 55 | 56 | ProcessBuilder processBuilder = new ProcessBuilder(genkeyCmd); 57 | processBuilder.redirectErrorStream(true); 58 | processBuilder.redirectOutput(Redirect.INHERIT); 59 | processBuilder.redirectError(Redirect.INHERIT); 60 | Process exec = processBuilder.start(); 61 | exec.waitFor(); 62 | 63 | System.out.println("Exit value: " + exec.exitValue()); 64 | 65 | } 66 | 67 | private static HttpsServer createHttpsServer(int port) throws Exception { 68 | generateCertificate(); 69 | HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(port), 0); 70 | SSLContext sslContext = getSslContext(); 71 | httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); 72 | return httpsServer; 73 | } 74 | 75 | private static HttpServer createHttpServer(int port) throws Exception { 76 | HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0); 77 | return httpServer; 78 | } 79 | 80 | private static SSLContext getSslContext() throws Exception { 81 | KeyStore ks = KeyStore.getInstance("JKS"); 82 | ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray()); 83 | 84 | KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); 85 | kmf.init(ks, KEY_PASSWORD.toCharArray()); 86 | 87 | TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); 88 | tmf.init(ks); 89 | 90 | SSLContext sslContext = SSLContext.getInstance("TLS"); 91 | sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); 92 | 93 | return sslContext; 94 | } 95 | 96 | public static HttpServer createServer(int port, boolean https) { 97 | try { 98 | if (https) { 99 | return HttpServerCreator.createHttpsServer(port); 100 | } else { 101 | return HttpServerCreator.createHttpServer(port); 102 | } 103 | } catch (Exception e) { 104 | throw new RuntimeException(e); 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/IndexPageHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Contributors: 17 | * ohun@live.cn (夜色) 18 | */ 19 | 20 | package com.shinemo.mpush.alloc; 21 | 22 | import com.sun.net.httpserver.HttpExchange; 23 | import com.sun.net.httpserver.HttpHandler; 24 | 25 | import java.io.IOException; 26 | import java.io.InputStream; 27 | import java.io.OutputStream; 28 | import java.nio.charset.StandardCharsets; 29 | 30 | /** 31 | * Created by ohun on 2016/12/5. 32 | * 33 | * @author ohun@live.cn (夜色) 34 | */ 35 | public final class IndexPageHandler implements HttpHandler { 36 | 37 | private byte[] data; 38 | 39 | public IndexPageHandler() { 40 | try (InputStream in = this.getClass().getResourceAsStream("/index.html")) { 41 | this.data = new byte[in.available()]; 42 | in.read(data); 43 | } catch (Exception e) { 44 | throw new RuntimeException(e); 45 | } 46 | } 47 | 48 | @Override 49 | public void handle(HttpExchange httpExchange) throws IOException { 50 | if (data != null && data.length > 0) { 51 | httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8"); 52 | httpExchange.sendResponseHeaders(200, data.length);//200, content-length 53 | OutputStream out = httpExchange.getResponseBody(); 54 | out.write(data); 55 | out.close(); 56 | httpExchange.close(); 57 | } else { 58 | byte[] data = "404 Not Found".getBytes(StandardCharsets.UTF_8); 59 | httpExchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); 60 | httpExchange.sendResponseHeaders(404, data.length); 61 | OutputStream out = httpExchange.getResponseBody(); 62 | out.write(data); 63 | out.close(); 64 | httpExchange.close(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Contributors: 17 | * ohun@live.cn (夜色) 18 | */ 19 | 20 | package com.shinemo.mpush.alloc; 21 | 22 | import com.mpush.tools.log.Logs; 23 | 24 | import java.io.IOException; 25 | 26 | /** 27 | * Created by ohun on 16/9/7. 28 | * 29 | * @author ohun@live.cn (夜色) 30 | */ 31 | public final class Main { 32 | 33 | public static void main(String[] args) { 34 | Logs.init(); 35 | Logs.Console.info("launch alloc server..."); 36 | AllocServer server = new AllocServer(); 37 | server.start(); 38 | addHook(server); 39 | } 40 | 41 | private static void addHook(AllocServer server) { 42 | Runtime.getRuntime().addShutdownHook( 43 | new Thread(() -> { 44 | try { 45 | server.stop(); 46 | } catch (Exception e) { 47 | Logs.Console.error("alloc server stop ex", e); 48 | } 49 | Logs.Console.info("jvm exit, all service stopped..."); 50 | 51 | }, "mpush-shutdown-hook-thread") 52 | ); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/shinemo/mpush/alloc/PushHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2015-2016 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Contributors: 17 | * ohun@live.cn (夜色) 18 | */ 19 | 20 | package com.shinemo.mpush.alloc; 21 | 22 | import com.mpush.api.Constants; 23 | import com.mpush.api.push.*; 24 | import com.mpush.tools.Jsons; 25 | import com.mpush.tools.common.Strings; 26 | import com.sun.net.httpserver.HttpExchange; 27 | import com.sun.net.httpserver.HttpHandler; 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | 31 | import java.io.ByteArrayOutputStream; 32 | import java.io.IOException; 33 | import java.io.InputStream; 34 | import java.io.OutputStream; 35 | import java.util.Map; 36 | import java.util.concurrent.atomic.AtomicInteger; 37 | 38 | 39 | /** 40 | * Created by ohun on 16/9/7. 41 | * 42 | * @author ohun@live.cn (夜色) 43 | */ 44 | /*package*/ final class PushHandler implements HttpHandler { 45 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 46 | private final PushSender pushSender = PushSender.create(); 47 | private final AtomicInteger idSeq = new AtomicInteger(); 48 | 49 | public void start() { 50 | pushSender.start(); 51 | } 52 | 53 | public void stop() { 54 | pushSender.stop(); 55 | } 56 | 57 | @SuppressWarnings("unchecked") 58 | @Override 59 | public void handle(HttpExchange httpExchange) throws IOException { 60 | String body = new String(readBody(httpExchange), Constants.UTF_8); 61 | Map params = Jsons.fromJson(body, Map.class); 62 | 63 | sendPush(params); 64 | 65 | byte[] data = "服务已经开始推送,请注意查收消息".getBytes(Constants.UTF_8); 66 | httpExchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); 67 | httpExchange.sendResponseHeaders(200, data.length);//200, content-length 68 | OutputStream out = httpExchange.getResponseBody(); 69 | out.write(data); 70 | out.close(); 71 | httpExchange.close(); 72 | } 73 | 74 | private void sendPush(Map params) { 75 | String userId = (String) params.get("userId"); 76 | String hello = (String) params.get("hello"); 77 | Boolean broadcast = (Boolean) params.get("broadcast"); 78 | String condition = (String) params.get("condition"); 79 | 80 | 81 | NotificationDO notificationDO = new NotificationDO(); 82 | notificationDO.content = "MPush开源推送," + hello; 83 | notificationDO.title = "MPUSH推送"; 84 | notificationDO.nid = idSeq.get() % 2 + 1; 85 | notificationDO.ticker = "你有一条新的消息,请注意查收"; 86 | PushMsg pushMsg = PushMsg.build(MsgType.NOTIFICATION_AND_MESSAGE, Jsons.toJson(notificationDO)); 87 | pushMsg.setMsgId("msg_" + idSeq.incrementAndGet()); 88 | 89 | pushSender.send(PushContext 90 | .build(pushMsg) 91 | .setUserId(Strings.isBlank(userId) ? null : userId) 92 | .setBroadcast(broadcast != null && broadcast) 93 | .setCondition(Strings.isBlank(condition) ? null : condition) 94 | .setCallback(new PushCallback() { 95 | @Override 96 | public void onResult(PushResult result) { 97 | logger.info(result.toString()); 98 | } 99 | }) 100 | ); 101 | } 102 | 103 | private byte[] readBody(HttpExchange httpExchange) throws IOException { 104 | InputStream in = httpExchange.getRequestBody(); 105 | String length = httpExchange.getRequestHeaders().getFirst("content-length"); 106 | if (length != null && !length.equals("0")) { 107 | byte[] buffer = new byte[Integer.parseInt(length)]; 108 | in.read(buffer); 109 | in.close(); 110 | return buffer; 111 | } else { 112 | ByteArrayOutputStream out = new ByteArrayOutputStream(1024); 113 | byte[] buffer = new byte[1024]; 114 | int len = 0; 115 | while ((len = in.read(buffer)) != -1) { 116 | out.write(buffer, 0, len); 117 | } 118 | in.close(); 119 | return out.toByteArray(); 120 | } 121 | } 122 | 123 | public static final class NotificationDO { 124 | public String msgId; 125 | public String title; 126 | public String content; 127 | public Integer nid; //主要用于聚合通知,非必填 128 | public Byte flags; //特性字段。 0x01:声音 0x02:震动 0x03:闪灯 129 | public String largeIcon; // 大图标 130 | public String ticker; //和title一样 131 | public Integer number; 132 | public Map extras; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/main/resources/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | MPush Message Sender 6 | 7 | 8 |

9 | 13 |
14 | 19 |
20 | 24 |
25 | 29 |
30 | 31 |
32 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${log.home}/mpush.log 11 | true 12 | 13 | ${log.home}/mpush.log.%d{yyyy-MM-dd} 14 | 15 | 10 16 | 17 | 18 | %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 19 | 20 | 21 | 22 | 23 | 24 | ${log.home}/info-mpush.log 25 | 26 | info 27 | ACCEPT 28 | DENY 29 | 30 | true 31 | 32 | ${log.home}/info-mpush.log.%d{yyyy-MM-dd} 33 | 34 | 3 35 | 36 | 37 | %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 38 | 39 | 40 | 41 | 42 | 43 | ${log.home}/debug-mpush.log 44 | 45 | debug 46 | ACCEPT 47 | DENY 48 | 49 | true 50 | 51 | ${log.home}/debug-mpush.log.%d{yyyy-MM-dd} 52 | 53 | 3 54 | 55 | 56 | %d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 57 | 58 | 59 | 60 | 61 | 62 | ${log.home}/monitor-mpush.log 63 | true 64 | 65 | ${log.home}/monitor-mpush.log.%d{yyyy-MM-dd} 66 | 67 | 5 68 | 69 | 70 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 71 | 72 | 73 | 74 | 75 | 76 | ${log.home}/conn-mpush.log 77 | true 78 | 79 | ${log.home}/conn-mpush.log.%d{yyyy-MM-dd} 80 | 81 | 30 82 | 83 | 84 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 85 | 86 | 87 | 88 | 89 | 90 | ${log.home}/push-mpush.log 91 | true 92 | 93 | ${log.home}/push-mpush.log.%d{yyyy-MM-dd} 94 | 95 | 30 96 | 97 | 98 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 99 | 100 | 101 | 102 | 103 | 104 | ${log.home}/heartbeat-mpush.log 105 | true 106 | 107 | ${log.home}/heartbeat-mpush.log.%d{yyyy-MM-dd} 108 | 109 | 30 110 | 111 | 112 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 113 | 114 | 115 | 116 | 117 | 118 | ${log.home}/cache-mpush.log 119 | true 120 | 121 | ${log.home}/cache-mpush.log.%d{yyyy-MM-dd} 122 | 123 | 5 124 | 125 | 126 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 127 | 128 | 129 | 130 | 131 | 132 | ${log.home}/http-mpush.log 133 | true 134 | 135 | ${log.home}/http-mpush.log.%d{yyyy-MM-dd} 136 | 137 | 5 138 | 139 | 140 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 141 | 142 | 143 | 144 | 145 | 146 | ${log.home}/srd-mpush.log 147 | true 148 | 149 | ${log.home}/srd-mpush.log.%d{yyyy-MM-dd} 150 | 151 | 10 152 | 153 | 154 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 155 | 156 | 157 | 158 | 159 | 160 | ${log.home}/profile-mpush.log 161 | true 162 | 163 | ${log.home}/profile-mpush.log.%d{yyyy-MM-dd} 164 | 165 | 10 166 | 167 | 168 | %d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n 169 | 170 | 171 | 172 | 173 | System.out 174 | 175 | DEBUG 176 | 177 | 178 | %d{HH:mm:ss.SSS} - %msg%n 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | -------------------------------------------------------------------------------- /src/main/resources/mpush.conf: -------------------------------------------------------------------------------- 1 | mp.log-level=${log.level} 2 | mp.net.gateway-server-net=tcp // 网关服务使用的网络 udp/tcp 3 | mp.net.alloc-server-port=9999 4 | mp.net.alloc-server-protocol=http 5 | mp.zk.server-address="127.0.0.1:2181" 6 | mp.redis {// redis 集群配置 7 | password:"" 8 | nodes:["127.0.0.1:6379"] //格式是ip:port 9 | cluster-model:single //single, cluster 10 | } -------------------------------------------------------------------------------- /src/test/java/com/shinemo/mpush/alloc/AllocServerMainTest.java: -------------------------------------------------------------------------------- 1 | package com.shinemo.mpush.alloc; 2 | 3 | 4 | import java.io.IOException; 5 | 6 | /** 7 | * Created by ohun on 16/10/14. 8 | * 9 | * @author ohun@live.cn (夜色) 10 | */ 11 | public class AllocServerMainTest { 12 | 13 | public static void main(String[] args) { 14 | Main.main(args); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/resources/application.conf: -------------------------------------------------------------------------------- 1 | mp.log.dir=${user.dir}/alloc/target/logs 2 | mp.log.level=debug 3 | mp.log-conf-path=logback.xml 4 | mp.net.gateway-server-net=tcp // 网关服务使用的网络 udp/tcp 5 | mp.net.alloc-server-port=9999 6 | mp.net.alloc-server-protocol=http 7 | mp.zk.server-address="127.0.0.1:2181" 8 | mp.redis {// redis 集群配置 9 | password:"" 10 | nodes:["127.0.0.1:6379"] //格式是ip:port 11 | cluster-model:single //single, cluster 12 | } -------------------------------------------------------------------------------- /src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | System.err 7 | 8 | WARN 9 | 10 | 11 | %d{HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 12 | 13 | 14 | 15 | 16 | 17 | 18 | info 19 | ACCEPT 20 | DENY 21 | 22 | System.out 23 | 24 | 25 | %d{HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 26 | 27 | 28 | 29 | 30 | 31 | 32 | debug 33 | ACCEPT 34 | DENY 35 | 36 | System.out 37 | 38 | 39 | %d{HH:mm:ss.SSS} - [%thread] %-5level - %logger{35} - %msg%n 40 | 41 | 42 | 43 | 44 | 45 | System.out 46 | 47 | 48 | DEBUG 49 | 50 | 51 | %d{HH:mm:ss.SSS} -[monitor]- %msg%n 52 | 53 | 54 | 55 | 56 | 57 | System.out 58 | 59 | 60 | DEBUG 61 | 62 | 63 | %d{HH:mm:ss.SSS} -[connection]- %msg%n 64 | 65 | 66 | 67 | 68 | 69 | System.out 70 | 71 | 72 | DEBUG 73 | 74 | 75 | %d{HH:mm:ss.SSS} -[push]- %msg%n 76 | 77 | 78 | 79 | 80 | 81 | System.out 82 | 83 | DEBUG 84 | 85 | 86 | %d{HH:mm:ss.SSS} -[heartbeat]- %msg%n 87 | 88 | 89 | 90 | 91 | 92 | System.out 93 | 94 | DEBUG 95 | 96 | 97 | %d{HH:mm:ss.SSS} -[redis]- %msg%n 98 | 99 | 100 | 101 | 102 | 103 | System.out 104 | 105 | DEBUG 106 | 107 | 108 | %d{HH:mm:ss.SSS} -[http]- %msg%n 109 | 110 | 111 | 112 | 113 | 114 | System.out 115 | 116 | DEBUG 117 | 118 | 119 | %d{HH:mm:ss.SSS} -[zk]- %msg%n 120 | 121 | 122 | 123 | 124 | 125 | System.err 126 | 127 | DEBUG 128 | 129 | 130 | %d{HH:mm:ss.SSS} -[profile]- %msg%n 131 | 132 | 133 | 134 | 135 | System.err 136 | 137 | DEBUG 138 | 139 | 140 | %d{HH:mm:ss.SSS} -[console]- %msg%n 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | --------------------------------------------------------------------------------