├── .gitignore ├── README.md ├── _config.yml ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src ├── main │ ├── java │ │ └── org │ │ │ └── jon │ │ │ └── lv │ │ │ ├── SpringbootexampleApplication.java │ │ │ ├── aop │ │ │ └── WebLogAspect.java │ │ │ ├── conf │ │ │ ├── AuthSessionUtils.java │ │ │ ├── CorsFilter.java │ │ │ ├── DruidDataSourceConfiguration.java │ │ │ ├── DruidStatFilter.java │ │ │ ├── DruidStatViewServlet.java │ │ │ └── HttpSessionUtils.java │ │ │ ├── controller │ │ │ ├── KafkaController.java │ │ │ └── UserController.java │ │ │ ├── domain │ │ │ └── User.java │ │ │ ├── dto │ │ │ └── ValidateDTO.java │ │ │ ├── dubbo │ │ │ ├── DubboConfig.java │ │ │ ├── DubboDemoService.java │ │ │ ├── DubboDemoServiceImpl.java │ │ │ ├── DubboProvider.java │ │ │ ├── DubboTestService.java │ │ │ ├── DubboTestServiceImpl.java │ │ │ └── ReferenceTest.java │ │ │ ├── es │ │ │ ├── Book.java │ │ │ ├── BookRepository.java │ │ │ ├── BookService.java │ │ │ ├── BookServiceImpl.java │ │ │ └── Tag.java │ │ │ ├── exception │ │ │ ├── AppWebException.java │ │ │ └── ErrorConstant.java │ │ │ ├── interceptors │ │ │ ├── AppInterceptors.java │ │ │ ├── AppResponseInterceptor.java │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── kafka │ │ │ ├── KafkaConfiguration.java │ │ │ ├── MsgConsumer.java │ │ │ └── MsgProducer.java │ │ │ ├── mapper │ │ │ └── UserMapper.java │ │ │ ├── redis │ │ │ ├── RedisConfig.java │ │ │ ├── RedisUtils.java │ │ │ └── SessionConfig.java │ │ │ ├── result │ │ │ └── ResultDO.java │ │ │ ├── service │ │ │ └── UserService.java │ │ │ ├── spy │ │ │ └── SqlCostInterceptor.java │ │ │ ├── swagger2 │ │ │ └── SwaggerConfig.java │ │ │ └── xml │ │ │ ├── ConfigClass.java │ │ │ └── HelloService.java │ └── resources │ │ ├── application-dev.properties │ │ ├── application-prod.properties │ │ ├── application-test.properties │ │ ├── application.properties │ │ ├── dubbo.properties │ │ ├── logback.xml │ │ ├── mybatis │ │ ├── mappers │ │ │ └── UserMapper.xml │ │ └── mybatis-config.xml │ │ └── xml │ │ └── application-bean.xml └── test │ └── java │ └── org │ └── jon │ └── lv │ ├── MockitoControllerExampleTest.java │ ├── MockitoExampleTest.java │ ├── SpringbootexampleApplicationTests.java │ ├── controller │ └── UserControllerTest.java │ ├── dubbo │ └── DubboDemoServiceTest.java │ ├── es │ └── ESTest.java │ ├── mail │ └── EmailService.java │ ├── redis │ └── RedisTest.java │ ├── service │ └── UserServiceTest.java │ └── xml │ └── XmlTest.java └── user.sql /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springbootexample项目 2 | 此工程是对springboot框架学习以及结合其他框架使用的例子。
3 | 分页插件依赖另外一个项目:https://github.com/L316476844/mybatis-pageplugin
4 | 动态数据源依赖于项目:https://github.com/L316476844/Mybatis-DynamicDataSource 分支 release_05_18
5 | 6 | **QQ交流群:374044564添加QQ群获取springboot、springcloud、dubbo等视频教程及资料** 7 | 8 | + springboot例子 9 | + springboot 自动装载功能和注解方式实现自动装载例子。[boot-custom-autoconfiguration](https://github.com/L316476844/boot-custom-autoconfiguration) 10 | + springboot 自定义注解完成版本号校、登录校验、接口权限校验、接口参数签名校验。[boot-stream](https://github.com/L316476844/boot-stream) 11 | + 包含druid数据源 12 | + druid的sql监控 13 | + druid过滤 14 | + mybatis xml配置 15 | + mybatis分页插件 16 | + mybatis动态数据源插件 17 | + mybatis完整sql(不包含?)输出插件 18 | + logback日志配置 19 | + springboot多环境配置 20 | + 发送邮件 21 | + AOP拦截 22 | + 过滤器 23 | + spring拦截器 24 | + 全局异常 25 | + 统一响应 26 | + 自定义事务 27 | + 动态数据源 28 | + 读写分离 29 | + Redis Session 30 | + redis缓存 31 | + xml注入spring boot无法扫描到的bean 32 | + actuator监控 33 | + kafka消息队列 34 | + Swagger2配置 35 | + Swagger2 所有api请求头header添加X-Token令牌 X-Timestamp 时间戳 X-Sign 签名信息 36 | + dubbo注解方式 dubbo版本2.5.5 37 | + dubboxml配置方式-分支:dubbo_xml_config 38 | + elasticsearch搜索引擎 39 | + 解决ajax跨域 CorsFilter 40 | + HTTP请求监听事件 41 | + Spring boot 开启reponse压缩 42 | + Mockito 调用注入服务/远程服务使用方式 43 | + Mockito mock controller接口 44 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.jon.lv 7 | springbootexample 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springbootexample 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.7 25 | 2.5.5 26 | 3.4.9 27 | 0.1 28 | 29 | 30 | 31 | 32 | com.alibaba 33 | druid 34 | 1.0.25 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-aop 40 | 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-jdbc 46 | 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-actuator 52 | 53 | 54 | 55 | org.mybatis.spring.boot 56 | mybatis-spring-boot-starter 57 | 1.2.1 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-data-redis 64 | 65 | 66 | 67 | 68 | org.springframework.session 69 | spring-session-data-redis 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-mail 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-web 81 | 82 | 83 | 84 | mysql 85 | mysql-connector-java 86 | runtime 87 | 88 | 89 | 90 | org.springframework.boot 91 | spring-boot-starter-test 92 | test 93 | 94 | 95 | 96 | 97 | org.springframework.boot 98 | spring-boot-devtools 99 | true 100 | 101 | 102 | 103 | 104 | org.springframework.kafka 105 | spring-kafka 106 | 107 | 108 | 109 | 110 | org.springframework.boot 111 | spring-boot-starter-data-elasticsearch 112 | 113 | 114 | 115 | org.jon.lv 116 | mybatis-pageplugin 117 | 1.0-SNAPSHOT 118 | 119 | 120 | 121 | com.alibaba 122 | fastjson 123 | 1.2.1 124 | 125 | 126 | 127 | 128 | io.springfox 129 | springfox-swagger-ui 130 | 2.6.1 131 | 132 | 133 | io.springfox 134 | springfox-swagger2 135 | 2.6.1 136 | 137 | 138 | 139 | org.jon.lv 140 | Mybatis-DynamicDataSource 141 | 1.0-SNAPSHOT 142 | 143 | 144 | 145 | 146 | com.alibaba 147 | dubbo 148 | 149 | 150 | org.springframework 151 | spring 152 | 153 | 154 | netty 155 | org.jboss.netty 156 | 157 | 158 | ${com.alibaba.dubbo.version} 159 | 160 | 161 | 162 | 163 | org.apache.zookeeper 164 | zookeeper 165 | ${org.apache.zookeeper.version} 166 | 167 | 168 | io.netty 169 | netty 170 | 171 | 172 | 173 | 174 | 175 | com.github.sgroschupf 176 | zkclient 177 | ${com.github.sgroschupf.zkclient.version} 178 | 179 | 198 | 199 | 200 | 201 | 202 | 203 | org.springframework.boot 204 | spring-boot-maven-plugin 205 | 206 | 207 | 208 | 209 | org.apache.maven.plugins 210 | maven-surefire-plugin 211 | 2.4 212 | 213 | true 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/SpringbootexampleApplication.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.boot.autoconfigure.web.HttpMessageConverters; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.boot.web.servlet.MultipartConfigFactory; 11 | import org.springframework.boot.web.servlet.ServletComponentScan; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.http.converter.ByteArrayHttpMessageConverter; 14 | import org.springframework.transaction.annotation.EnableTransactionManagement; 15 | import org.springframework.web.context.request.RequestContextListener; 16 | import org.springframework.web.filter.CharacterEncodingFilter; 17 | 18 | import javax.servlet.Filter; 19 | import javax.servlet.MultipartConfigElement; 20 | import javax.sql.DataSource; 21 | 22 | 23 | @SpringBootApplication 24 | @ServletComponentScan 25 | //启注解事务管理 26 | @EnableTransactionManagement 27 | @MapperScan("org.jon.lv.mapper") 28 | public class SpringbootexampleApplication{ 29 | 30 | // 用于处理编码问题 31 | @Bean 32 | public Filter characterEncodingFilter() { 33 | CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); 34 | characterEncodingFilter.setEncoding("UTF-8"); 35 | characterEncodingFilter.setForceEncoding(true); 36 | return characterEncodingFilter; 37 | } 38 | 39 | // 文件上传限制 40 | @Bean 41 | public MultipartConfigElement multipartConfigElement() { 42 | MultipartConfigFactory factory = new MultipartConfigFactory(); 43 | // 设置文件大小限制 ,超出设置页面会抛出异常信息, 44 | // 这样在文件上传的地方就需要进行异常信息的处理了; 45 | factory.setMaxFileSize("2560KB"); // KB,MB 46 | /// 设置总上传数据总大小 47 | factory.setMaxRequestSize("5120KB"); 48 | // Sets the directory location where files will be stored. 49 | // factory.setLocation("路径地址"); 50 | return factory.createMultipartConfig(); 51 | } 52 | 53 | //文件下载 54 | @Bean 55 | public HttpMessageConverters restFileDownloadSupport() { 56 | ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); 57 | return new HttpMessageConverters(arrayHttpMessageConverter); 58 | } 59 | 60 | // HTTP请求监听事件 61 | @Bean 62 | public RequestContextListener requestContextListener() { 63 | return new RequestContextListener(); 64 | } 65 | 66 | /** 67 | * 跨域过滤器 68 | * @return 69 | */ 70 | //@Bean 71 | // public FilterRegistrationBean corsFilter() { 72 | // UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 73 | // CorsConfiguration config = new CorsConfiguration(); 74 | // config.addAllowedOrigin("*"); 75 | // config.setAllowCredentials(true); 76 | // config.addAllowedHeader("*"); 77 | // config.addAllowedMethod("*"); 78 | // source.registerCorsConfiguration("/**", config); 79 | 80 | // FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 81 | // bean.setOrder(0); 82 | // return bean; 83 | // } 84 | 85 | public static void main(String[] args) { 86 | SpringApplication.run(SpringbootexampleApplication.class, args); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/aop/WebLogAspect.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.aop; 2 | 3 | import java.util.Arrays; 4 | import java.util.Enumeration; 5 | import javax.servlet.http.HttpServletRequest; 6 | import org.aspectj.lang.JoinPoint; 7 | import org.aspectj.lang.annotation.AfterReturning; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.annotation.Before; 10 | import org.aspectj.lang.annotation.Pointcut; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.core.annotation.Order; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.context.request.RequestContextHolder; 16 | import org.springframework.web.context.request.ServletRequestAttributes; 17 | 18 | /** 19 | * @Package org.jon.lv.aop.WebLogAspect 20 | * @Description: WebLogAspect 21 | * Author lv bin 22 | * @date 2017/5/16 11:18 23 | * version V1.0.0 24 | */ 25 | @Aspect 26 | @Component 27 | @Order(-5) 28 | public class WebLogAspect { 29 | 30 | private Logger logger = LoggerFactory.getLogger(WebLogAspect.class); 31 | 32 | /** 33 | * 定义一个切入点. 34 | * 解释下: 35 | * ~ 第一个 * 代表任意修饰符及任意返回值. 36 | * ~ 第二个 * 任意包名 37 | * ~ 第三个 * 代表任意方法. 38 | * ~ 第四个 * 定义在web包或者子包 39 | * ~ 第五个 * 任意方法 40 | * ~ .. 匹配任意数量的参数. 41 | */ 42 | 43 | @Pointcut("execution(public * org.jon.lv.controller.*.*(..))") 44 | public void webLog() { 45 | } 46 | 47 | @Before("webLog()") 48 | public void doBefore(JoinPoint joinPoint) { 49 | // 接收到请求,记录请求内容 50 | logger.info("WebLogAspect.doBefore()"); 51 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 52 | HttpServletRequest request = attributes.getRequest(); 53 | 54 | // 记录下请求内容 55 | logger.info("URL : " + request.getRequestURL().toString()); 56 | logger.info("HTTP_METHOD : " + request.getMethod()); 57 | logger.info("IP : " + request.getRemoteAddr()); 58 | logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); 59 | logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); 60 | //获取所有参数方法一: 61 | Enumeration enu = request.getParameterNames(); 62 | while (enu.hasMoreElements()) { 63 | String paraName = (String) enu.nextElement(); 64 | System.out.println(paraName + ": " + request.getParameter(paraName)); 65 | } 66 | } 67 | 68 | 69 | @AfterReturning("webLog()") 70 | public void doAfterReturning(JoinPoint joinPoint) { 71 | // 处理完请求,返回内容 72 | logger.info("WebLogAspect.doAfterReturning()"); 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/AuthSessionUtils.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | /** 4 | * @Description: 会话工具类 5 | * @Copyright: Copyright (c) 2016 6 | * Author lv bin 7 | * @date 2016/10/25 9:34 8 | * version V1.0.0 9 | */ 10 | public class AuthSessionUtils { 11 | public static String APP_CURRENT_USER= "APP_CURRENT_USER";//当前人 12 | public static String APP_CURRENT_USER_ID = "APP_CURRENT_USER_ID";//当前人id 13 | public static String APP_CURRENT_USER_TOKEN = "APP_CURRENT_USER_TOKEN";//当前用户token 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/CorsFilter.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import javax.servlet.*; 6 | import javax.servlet.http.HttpServletResponse; 7 | import java.io.IOException; 8 | 9 | /** 10 | * 解决ajax跨域 11 | * @author Author lv bin 12 | * @time 2017年8月16日 13 | */ 14 | @Component 15 | public class CorsFilter implements Filter { 16 | 17 | final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class); 18 | 19 | public void doFilter(ServletRequest req, ServletResponse resp, 20 | FilterChain chain) throws IOException, ServletException { 21 | HttpServletResponse res = (HttpServletResponse) resp; 22 | System.out.println("=================================="+req.getRemoteAddr()); 23 | 24 | // 这里最好不要写通配符,如果允许多个域请求数据的话,可以直接用逗号隔开:"http://www.baidu.com,http://google.com" 25 | 26 | res.setHeader("Access-Control-Allow-Origin", "*"); 27 | 28 | res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); 29 | 30 | res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With"); 31 | 32 | //res.setHeader("Access-Control-Allow-Credentials","false"); 33 | 34 | chain.doFilter(req, resp); 35 | 36 | } 37 | public void init(FilterConfig filterConfig) {} 38 | public void destroy() {} 39 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/DruidDataSourceConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | import org.apache.ibatis.mapping.DatabaseIdProvider; 4 | import org.apache.ibatis.plugin.Interceptor; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.jon.lv.jdbc.dataSource.DynamicDataSource; 7 | import org.jon.lv.jdbc.manager.DynamicDataSourceTransactionManager; 8 | import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; 9 | import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; 10 | import org.mybatis.spring.boot.autoconfigure.MybatisProperties; 11 | import org.springframework.beans.factory.ObjectProvider; 12 | import org.springframework.beans.factory.annotation.Value; 13 | import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; 14 | import org.springframework.boot.context.properties.ConfigurationProperties; 15 | import org.springframework.context.annotation.Bean; 16 | import org.springframework.context.annotation.Configuration; 17 | import org.springframework.context.annotation.Primary; 18 | import org.springframework.core.io.ResourceLoader; 19 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 20 | import org.springframework.transaction.PlatformTransactionManager; 21 | import org.springframework.transaction.annotation.EnableTransactionManagement; 22 | 23 | import javax.sql.DataSource; 24 | import java.util.List; 25 | 26 | /** 27 | * @Package org.jon.lv.conf.DruidDataSourceConfiguration 28 | * @Description: DruidDataSourceConfiguration 29 | * @Copyright: Copyright (c) 2016 30 | * Author lv bin 31 | * @date 2017/5/12 15:15 32 | * version V1.0.0 33 | */ 34 | @Configuration 35 | @EnableTransactionManagement 36 | public class DruidDataSourceConfiguration extends MybatisAutoConfiguration { 37 | 38 | @Value("${datasource.type}") 39 | private Class dataSourceType; 40 | 41 | public DruidDataSourceConfiguration(MybatisProperties properties, ObjectProvider interceptorsProvider, ResourceLoader resourceLoader, ObjectProvider databaseIdProvider, ObjectProvider> configurationCustomizersProvider) { 42 | super(properties, interceptorsProvider, resourceLoader, databaseIdProvider, configurationCustomizersProvider); 43 | } 44 | 45 | @Bean(name = "masterDataSource") 46 | @Primary 47 | @ConfigurationProperties(prefix = "spring.datasource") 48 | public DataSource masterDataSource() { 49 | System.out.println("-------------------- writeDataSource init ---------------------"); 50 | return DataSourceBuilder.create().type(dataSourceType).build(); 51 | } 52 | 53 | @Bean(name = "slaveDataSource") 54 | @ConfigurationProperties(prefix = "slave.datasource") 55 | public DataSource slaveDataSource() { 56 | System.out.println("-------------------- readDataSourceOne init ---------------------"); 57 | return DataSourceBuilder.create().type(dataSourceType).build(); 58 | } 59 | 60 | @Bean 61 | public DynamicDataSource dynamicDataSource(){ 62 | DynamicDataSource dynamicDataSource = new DynamicDataSource(); 63 | dynamicDataSource.setMasterDataSource(masterDataSource()); 64 | dynamicDataSource.setReadDataSource(slaveDataSource()); 65 | return dynamicDataSource; 66 | } 67 | 68 | @Bean(name = "sqlSessionFactory") 69 | public SqlSessionFactory sqlSessionFactoryBean() throws Exception { 70 | return super.sqlSessionFactory(dynamicDataSource()); 71 | } 72 | 73 | 74 | // 默认事务 75 | // @Bean 76 | // public PlatformTransactionManager txManager(DataSource dataSource) { 77 | // return new DataSourceTransactionManager(dataSource); 78 | // } 79 | 80 | 81 | /** 82 | * 配置事务管理器 83 | */ 84 | @Bean 85 | @Primary 86 | public DataSourceTransactionManager transactionManager() throws Exception{ 87 | return new DynamicDataSourceTransactionManager(dynamicDataSource()); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/DruidStatFilter.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | /** 4 | * @Package org.jon.lv.conf.DruidStatFilter 5 | * @Description: DruidStatFilter 6 | * @Copyright: Copyright (c) 2016 7 | * Author lv bin 8 | * @date 2017/5/12 16:45 9 | * version V1.0.0 10 | */ 11 | 12 | import com.alibaba.druid.support.http.WebStatFilter; 13 | 14 | import javax.servlet.annotation.WebFilter; 15 | import javax.servlet.annotation.WebInitParam; 16 | 17 | /** 18 | * druid过滤器. 19 | * 20 | * @author Administrator 21 | */ 22 | @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", 23 | initParams = { 24 | @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源 25 | } 26 | ) 27 | public class DruidStatFilter extends WebStatFilter { 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/DruidStatViewServlet.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | 5 | import javax.servlet.annotation.WebInitParam; 6 | import javax.servlet.annotation.WebServlet; 7 | 8 | /** 9 | * @Package org.jon.lv.conf.DruidStatViewServlet 10 | * @Description: DruidStatViewServlet 11 | * @Copyright: Copyright (c) 2016 12 | * Author lv bin 13 | * @date 2017/5/12 15:16 14 | * version V1.0.0 15 | */ 16 | @WebServlet(urlPatterns = "/druid/*", 17 | initParams={ 18 | @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问) 19 | @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow) 20 | @WebInitParam(name="loginUsername",value="druid"),// 用户名 21 | @WebInitParam(name="loginPassword",value="admin"),// 密码 22 | @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 23 | }) 24 | public class DruidStatViewServlet extends StatViewServlet { 25 | private static final long serialVersionUID = 1L; 26 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/conf/HttpSessionUtils.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.conf; 2 | 3 | import org.springframework.web.context.request.RequestContextHolder; 4 | import org.springframework.web.context.request.ServletRequestAttributes; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpSession; 8 | 9 | /** 10 | * session 会话工具 11 | */ 12 | public class HttpSessionUtils { 13 | 14 | private static HttpServletRequest getRequest() { 15 | ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 16 | return requestAttributes.getRequest(); 17 | } 18 | 19 | private static HttpSession getSession() { 20 | return getRequest().getSession(); 21 | } 22 | 23 | /** 24 | * @Description: 存放会话级别的值 25 | * @Title putObject 26 | * @Author lv bin 27 | * @Date 2016/10/26 16:29 28 | * @param requestKey, obj 29 | * @return void 30 | * @throws 31 | */ 32 | public static void putObject(String requestKey, Object obj){ 33 | getRequest().setAttribute(requestKey, obj); 34 | } 35 | 36 | /** 37 | * @Description: 根据 session key获取会话值 38 | * @Title getObject 39 | * @Author lv bin 40 | * @Date 2016/10/26 16:27 41 | * @param requestKey 42 | * @return T 43 | * @throws 44 | */ 45 | public static T getObject(String requestKey){ 46 | return (T)getRequest().getAttribute(requestKey); 47 | } 48 | 49 | /** 50 | * 获取当前用户id 51 | * @return 52 | */ 53 | public static Long getCurrentAppUserId(){ 54 | 55 | Object object = getRequest().getAttribute(AuthSessionUtils.APP_CURRENT_USER_ID); 56 | 57 | if(object != null) return (Long)object; 58 | 59 | return null; 60 | } 61 | 62 | /** 63 | * 获取当前用户token 64 | * @return 65 | */ 66 | public static String getCurrentAppUserToken() { 67 | Object object = getRequest().getAttribute(AuthSessionUtils.APP_CURRENT_USER_TOKEN); 68 | 69 | if(object != null) return (String)object; 70 | 71 | return null; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/controller/KafkaController.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.controller; 2 | 3 | import org.jon.lv.domain.User; 4 | import org.jon.lv.kafka.MsgProducer; 5 | import org.jon.lv.result.ResultDO; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | /** 10 | * @Package org.jon.lv.controller.KafkaController 11 | * @Description: KafkaController 12 | * @Copyright: Copyright (c) 2016 13 | * Author lv bin 14 | * @date 2017/5/19 10:32 15 | * version V1.0.0 16 | */ 17 | @RestController 18 | @RequestMapping("/kafka") 19 | public class KafkaController { 20 | 21 | @Autowired 22 | private MsgProducer msgProducer; 23 | 24 | @RequestMapping(value = "/send", method = RequestMethod.GET) 25 | public ResultDO get(@RequestParam("content") String content){ 26 | ResultDO resultDO = new ResultDO<>(); 27 | 28 | msgProducer.send(content); 29 | 30 | resultDO.setSuccess(true); 31 | resultDO.setData(content); 32 | return resultDO; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.controller; 2 | 3 | import io.swagger.annotations.ApiImplicitParam; 4 | import io.swagger.annotations.ApiImplicitParams; 5 | import io.swagger.annotations.ApiOperation; 6 | import io.swagger.annotations.ApiResponse; 7 | import org.jon.lv.domain.User; 8 | import org.jon.lv.result.ResultDO; 9 | import org.jon.lv.service.UserService; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | /** 15 | * @Package org.jon.lv.controller.UserController 16 | * @Copyright: Copyright (c) 2016 17 | * Author lv bin 18 | * @date 2017/5/12 15:30 19 | * version V1.0.0 20 | */ 21 | @RestController 22 | @RequestMapping("/user") 23 | public class UserController { 24 | 25 | @Autowired 26 | private UserService userService; 27 | 28 | @ApiOperation(value = "查询单个用户",notes = "根据传入id查找用户",httpMethod = "GET") 29 | @ApiResponse(code = 200,message = "Success") 30 | @RequestMapping(value ="/get/{id}", method = RequestMethod.GET) 31 | public ResultDO get(@PathVariable("id")Integer id){ 32 | ResultDO resultDO = new ResultDO<>(); 33 | resultDO.setSuccess(true); 34 | resultDO.setData(userService.getUserById(id)); 35 | return resultDO; 36 | } 37 | 38 | // @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息") 39 | // @ApiImplicitParams({ 40 | // @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"), 41 | // @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") 42 | // }) 43 | 44 | @RequestMapping(value = "/add", method = RequestMethod.POST) 45 | public ResultDO add(User user){ 46 | ResultDO resultDO = new ResultDO<>(); 47 | resultDO.setSuccess(true); 48 | resultDO.setData(userService.save(user)); 49 | return resultDO; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/domain/User.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @Package: org.jon.lv.domain.User.java 7 | * @Description: InnoDB free: 4096 kB 8 | * @Copyright: Copyright (c) 2017 9 | * All right reserved. 10 | * Author jon lv 11 | * @date 2017/05/12 15:24 12 | * version v1.0.0 13 | */ 14 | public class User implements Serializable{ 15 | private Integer id; 16 | 17 | private String head; 18 | 19 | private String name; 20 | 21 | private String phone; 22 | 23 | private String picture; 24 | 25 | private Integer sex; 26 | 27 | /** 28 | * @return id 29 | */ 30 | public Integer getId() { 31 | return id; 32 | } 33 | 34 | /** 35 | * @param id 36 | */ 37 | public void setId(Integer id) { 38 | this.id = id; 39 | } 40 | 41 | /** 42 | * @return head 43 | */ 44 | public String getHead() { 45 | return head; 46 | } 47 | 48 | /** 49 | * @param head 50 | */ 51 | public void setHead(String head) { 52 | this.head = head == null ? null : head.trim(); 53 | } 54 | 55 | /** 56 | * @return name 57 | */ 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | /** 63 | * @param name 64 | */ 65 | public void setName(String name) { 66 | this.name = name == null ? null : name.trim(); 67 | } 68 | 69 | /** 70 | * @return phone 71 | */ 72 | public String getPhone() { 73 | return phone; 74 | } 75 | 76 | /** 77 | * @param phone 78 | */ 79 | public void setPhone(String phone) { 80 | this.phone = phone == null ? null : phone.trim(); 81 | } 82 | 83 | /** 84 | * @return picture 85 | */ 86 | public String getPicture() { 87 | return picture; 88 | } 89 | 90 | /** 91 | * @param picture 92 | */ 93 | public void setPicture(String picture) { 94 | this.picture = picture == null ? null : picture.trim(); 95 | } 96 | 97 | /** 98 | * @return sex 99 | */ 100 | public Integer getSex() { 101 | return sex; 102 | } 103 | 104 | /** 105 | * @param sex 106 | */ 107 | public void setSex(Integer sex) { 108 | this.sex = sex; 109 | } 110 | 111 | /** 112 | * @Title toString 113 | * @Author jon lv 114 | * @Date 2017/05/12 15:24 115 | * @return java.lang.String 116 | * @throws [] 117 | */ 118 | @Override 119 | public String toString() { 120 | StringBuilder sb = new StringBuilder(); 121 | sb.append(getClass().getSimpleName()); 122 | sb.append(" ["); 123 | sb.append("Hash = ").append(hashCode()); 124 | sb.append(", id=").append(id); 125 | sb.append(", head=").append(head); 126 | sb.append(", name=").append(name); 127 | sb.append(", phone=").append(phone); 128 | sb.append(", picture=").append(picture); 129 | sb.append(", sex=").append(sex); 130 | sb.append("]"); 131 | return sb.toString(); 132 | } 133 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dto/ValidateDTO.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dto; 2 | 3 | import org.hibernate.validator.constraints.Email; 4 | import org.hibernate.validator.constraints.Length; 5 | 6 | import javax.validation.constraints.*; 7 | import java.io.Serializable; 8 | 9 | /** 10 | * @Package org.jon.lv.dto.ValidateDTO 11 | * @Copyright: Copyright (c) 2016 12 | * Author lv bin 13 | * @date 2017/5/18 11:12 14 | * version V1.0.0 15 | */ 16 | public class ValidateDTO implements Serializable{ 17 | // @size(min=3, max=20, message="用户名长度只能在3-20之间") 18 | // private String userName; 19 | // @size(min=6, max=20, message="密码长度只能在6-20之间") 20 | // private String pwd; 21 | // @pattern(regexp="[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}", message="邮件格式错误") 22 | // private String email; 23 | // @Length(min = 5, max = 20, message = "用户名长度必须位于5到20之间") 24 | // private String uName; 25 | // @Email(message = "比如输入正确的邮箱") 26 | // 27 | // @NotNull(message = "用户名称不能为空") 28 | // 29 | // @Max(value = 100, message = "年龄不能大于100岁") 30 | // 31 | // @Min(value= 18 ,message= "必须年满18岁!" ) 32 | // 33 | // @AssertTrue(message = "bln4 must is true") 34 | // 35 | // @AssertFalse(message = "blnf must is falase") 36 | // 37 | // @DecimalMax(value="100",message="decim最大值是100") 38 | // 39 | // @DecimalMin(value="100",message="decim最小值是100") 40 | // 41 | // @NotNull(message = "身份证不能为空") 42 | // 43 | // @Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误") 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboConfig.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | import com.alibaba.dubbo.config.*; 4 | import com.alibaba.dubbo.config.spring.AnnotationBean; 5 | import com.alibaba.dubbo.config.spring.ServiceBean; 6 | import com.alibaba.dubbo.rpc.Exporter; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 11 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.PropertySource; 15 | 16 | import javax.annotation.PreDestroy; 17 | 18 | /** 19 | * @Package org.jon.lv.dubbo.DubboConfig 20 | * @Description: DubboConfig 21 | * @Copyright: Copyright (c) 2016 22 | * Author lv bin 23 | * @date 2017/5/19 16:28 24 | * version V1.0.0 25 | */ 26 | @Configuration 27 | @ConditionalOnClass(Exporter.class) 28 | @PropertySource(value = "classpath:/dubbo.properties") 29 | public class DubboConfig{ 30 | 31 | /** 32 | * 设置dubbo扫描包 33 | * @return 34 | */ 35 | @Bean 36 | public AnnotationBean annotationBean(@Value("${dubbo.annotation.package}") String annotationPackage) { 37 | AnnotationBean annotationBean = new AnnotationBean(); 38 | annotationBean.setPackage(annotationPackage); 39 | return annotationBean; 40 | } 41 | 42 | /** 43 | * 注入dubbo上下文 44 | * @return 45 | */ 46 | @Bean 47 | public ApplicationConfig applicationConfig(@Value("${dubbo.app.name}") String appName){ 48 | // 当前应用配置 49 | ApplicationConfig applicationConfig = new ApplicationConfig(); 50 | applicationConfig.setName(appName); 51 | return applicationConfig; 52 | } 53 | 54 | /** 55 | * 注入dubbo注册中心配置,基于zookeeper 56 | * @return 57 | */ 58 | @Bean 59 | public RegistryConfig registryConfig(@Value("${dubbo.registry.url}") String registryUrl, 60 | @Value("${dubbo.registry.file}") String registryFile) { 61 | System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$" + registryUrl); 62 | // 连接注册中心配置 63 | RegistryConfig registry = new RegistryConfig(); 64 | registry.setDefault(true); 65 | registry.setAddress(registryUrl); 66 | registry.setFile(registryFile); 67 | return registry; 68 | } 69 | 70 | /** 71 | * 默认基于dubbo协议提供服务 72 | * @return 73 | */ 74 | @Bean 75 | public ProtocolConfig protocolConfig(@Value("${dubbo.protocol.port}")Integer protocolPort) { 76 | // 服务提供者协议配置 77 | ProtocolConfig protocolConfig = new ProtocolConfig(); 78 | protocolConfig.setPort(protocolPort); 79 | protocolConfig.setThreads(200); 80 | return protocolConfig; 81 | } 82 | 83 | /** 84 | * 监控 85 | * @return 86 | */ 87 | @Bean 88 | public MonitorConfig monitorConfig() { 89 | MonitorConfig monitorConfig = new MonitorConfig(); 90 | monitorConfig.setProtocol("registry"); 91 | return monitorConfig; 92 | } 93 | 94 | /** 95 | * dubbo服务提供 96 | * @param applicationConfig 97 | * @param registryConfig 98 | * @param protocolConfig 99 | * @param monitorConfig 100 | * @return 101 | */ 102 | @Bean(name="defaultProvider") 103 | public ProviderConfig providerConfig(ApplicationConfig applicationConfig, RegistryConfig registryConfig, 104 | ProtocolConfig protocolConfig, MonitorConfig monitorConfig, 105 | @Value("${dubbo.provider.timeout}") Integer providerTimeout, 106 | @Value("${dubbo.provider.retries}")Integer retries, 107 | @Value("${dubbo.provider.delay}")Integer delay, 108 | @Value("${dubbo.provider.default.version}")String providerVersion) { 109 | ProviderConfig providerConfig = new ProviderConfig(); 110 | providerConfig.setTimeout(providerTimeout); 111 | providerConfig.setRetries(retries); 112 | providerConfig.setMonitor(monitorConfig); 113 | providerConfig.setApplication(applicationConfig); 114 | providerConfig.setRegistry(registryConfig); 115 | providerConfig.setProtocol(protocolConfig); 116 | providerConfig.setDelay(delay); 117 | providerConfig.setVersion(providerVersion); 118 | return providerConfig; 119 | } 120 | 121 | /** 122 | * dubbo消费 123 | * @param applicationConfig 124 | * @param registryConfig 125 | * @param monitorConfig 126 | * @return 127 | */ 128 | @Bean(name="defaultConsumer") 129 | public ConsumerConfig consumerConfig(ApplicationConfig applicationConfig, RegistryConfig registryConfig, 130 | MonitorConfig monitorConfig, 131 | @Value("${dubbo.provider.timeout}") Integer providerTimeout, 132 | @Value("${dubbo.provider.retries}")Integer retries, 133 | @Value("${dubbo.consume.service.check}") Boolean serviceCheck, 134 | @Value("${dubbo.consumer.default.version}")String consumerVersion) { 135 | ConsumerConfig consumerConfig = new ConsumerConfig(); 136 | consumerConfig.setTimeout(providerTimeout); 137 | consumerConfig.setRetries(retries); 138 | consumerConfig.setMonitor(monitorConfig); 139 | consumerConfig.setApplication(applicationConfig); 140 | consumerConfig.setRegistry(registryConfig); 141 | consumerConfig.setCheck(serviceCheck); 142 | consumerConfig.setVersion(consumerVersion); 143 | return consumerConfig; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboDemoService.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | /** 4 | * @Package org.jon.lv.dubbo.DubboDemoService 5 | * @Description: DubboDemoService 6 | * @Copyright: Copyright (c) 2016 7 | * Author lv bin 8 | * @date 2017/5/19 13:34 9 | * version V1.0.0 10 | */ 11 | public interface DubboDemoService { 12 | 13 | void say(String words); 14 | 15 | String info(String content); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboDemoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | 4 | import com.alibaba.dubbo.config.annotation.Service; 5 | 6 | /** 7 | * @Package org.jon.lv.dubbo.DubboDemoServiceImpl 8 | * @Description: DubboDemoServiceImpl 9 | * @Copyright: Copyright (c) 2016 10 | * Author lv bin 11 | * @date 2017/5/19 13:35 12 | * version V1.0.0 13 | */ 14 | @Service 15 | public class DubboDemoServiceImpl implements DubboDemoService{ 16 | @Override 17 | public void say(String words) { 18 | System.out.println("##############" + words); 19 | } 20 | 21 | @Override 22 | public String info(String content) { 23 | return "$$$$$$$$$$$$".concat(content); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboProvider.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | import com.alibaba.dubbo.config.ProviderConfig; 4 | import com.alibaba.dubbo.config.spring.ServiceBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * @Package org.jon.lv.dubbo.DubboProvider 10 | * @Description: DubboProvider 11 | * Author lv bin 12 | * @date 2017/5/22 10:04 13 | * version V1.0.0 14 | */ 15 | @Component 16 | public class DubboProvider { 17 | 18 | /** 19 | * 1、dubbo提供者的使用方式可以是在service的实现类上加入 dubbo的@Service注解 20 | * 21 | * 2、也可以使用此处类中的方式进行提供 在service实现类上使用 spring的@Service注解 22 | */ 23 | 24 | // @Bean 25 | // public ServiceBean dubboDemoService(ProviderConfig providerConfig, DubboDemoService dubboDemoService){ 26 | // ServiceBean serviceBean = new ServiceBean<>(); 27 | // serviceBean.setProvider(providerConfig); 28 | // serviceBean.setInterface(DubboDemoService.class); 29 | // serviceBean.setRef(dubboDemoService); 30 | // return serviceBean; 31 | // } 32 | // 33 | // @Bean 34 | // public ServiceBean dubboTestService(ProviderConfig providerConfig, DubboTestService dubboTestService){ 35 | // ServiceBean serviceBean = new ServiceBean<>(); 36 | // serviceBean.setProvider(providerConfig); 37 | // serviceBean.setInterface(DubboTestService.class); 38 | // serviceBean.setRef(dubboTestService); 39 | // return serviceBean; 40 | // } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboTestService.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | /** 4 | * @Package org.jon.lv.dubbo.DubboTestService 5 | * @Copyright: Copyright (c) 2016 6 | * Author lv bin 7 | * @date 2017/5/22 10:24 8 | * version V1.0.0 9 | */ 10 | public interface DubboTestService { 11 | void say(String words); 12 | 13 | String info(String content); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/DubboTestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | 4 | import com.alibaba.dubbo.config.annotation.Service; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | /** 8 | * @Package org.jon.lv.dubbo.DubboTestServiceImpl 9 | * @Copyright: Copyright (c) 2016 10 | * Author lv bin 11 | * @date 2017/5/22 10:25 12 | * version V1.0.0 13 | */ 14 | @Service 15 | public class DubboTestServiceImpl implements DubboTestService{ 16 | @Autowired 17 | private DubboDemoService dubboDemoService; 18 | 19 | @Override 20 | public void say(String words) { 21 | dubboDemoService.say(words); 22 | System.out.println("test----------##############" + words); 23 | } 24 | 25 | @Override 26 | public String info(String content) { 27 | return "test----------$$$$$$$$$$$$".concat(content); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/dubbo/ReferenceTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | import com.alibaba.dubbo.config.annotation.Reference; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @Package org.jon.lv.dubbo.ReferenceTest 8 | * @Copyright: Copyright (c) 2016 9 | * Author lv bin 10 | * @date 2017/5/22 13:31 11 | * version V1.0.0 12 | */ 13 | //@Component 14 | public class ReferenceTest { 15 | // @Reference 16 | // private DubboDemoService dubboDemoService; 17 | // 18 | // public void testReference(String word){ 19 | // dubboDemoService.info(word); 20 | // } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/es/Book.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.elasticsearch.annotations.Document; 5 | import org.springframework.data.elasticsearch.annotations.Field; 6 | import org.springframework.data.elasticsearch.annotations.FieldIndex; 7 | import org.springframework.data.elasticsearch.annotations.FieldType; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @Package org.jon.lv.es.Book 13 | * @Copyright: Copyright (c) 2016 14 | * Author lv bin 15 | * @date 2017/5/22 13:55 16 | * version V1.0.0 17 | */ 18 | 19 | // indexName 只能为小写 否则启动报错 20 | @Document(indexName = "jon", type = "books") 21 | public class Book { 22 | @Id 23 | private String id; 24 | @Field(type = FieldType.String, index = FieldIndex.not_analyzed, store = true) 25 | private String author; 26 | @Field(type = FieldType.String, index = FieldIndex.not_analyzed, store = true, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word") 27 | private String title; 28 | private String releaseDate; 29 | @Field(type= FieldType.Nested) 30 | private List tags; 31 | 32 | public Book() { 33 | } 34 | 35 | public Book(String id, String title, String author, String releaseDate) { 36 | this.id = id; 37 | this.title = title; 38 | this.author = author; 39 | this.releaseDate = releaseDate; 40 | } 41 | 42 | public String getId() { 43 | return id; 44 | } 45 | 46 | public void setId(String id) { 47 | this.id = id; 48 | } 49 | 50 | public String getTitle() { 51 | return title; 52 | } 53 | 54 | public void setTitle(String title) { 55 | this.title = title; 56 | } 57 | 58 | public String getAuthor() { 59 | return author; 60 | } 61 | 62 | public void setAuthor(String author) { 63 | this.author = author; 64 | } 65 | 66 | public String getReleaseDate() { 67 | return releaseDate; 68 | } 69 | 70 | public void setReleaseDate(String releaseDate) { 71 | this.releaseDate = releaseDate; 72 | } 73 | 74 | public List getTags() { 75 | return tags; 76 | } 77 | 78 | public void setTags(List tags) { 79 | this.tags = tags; 80 | } 81 | 82 | 83 | //getters and setters 84 | 85 | @Override 86 | public String toString() { 87 | return "Book{" + 88 | "id='" + id + '\'' + 89 | ", title='" + title + '\'' + 90 | ", author='" + author + '\'' + 91 | ", releaseDate='" + releaseDate + '\'' + 92 | '}'; 93 | } 94 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/es/BookRepository.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @Package org.jon.lv.es.BookRepository 12 | * @Copyright: Copyright (c) 2016 13 | * Author lv bin 14 | * @date 2017/5/22 13:55 15 | * version V1.0.0 16 | */ 17 | public interface BookRepository extends ElasticsearchRepository { 18 | 19 | Page findByAuthor(String author, Pageable pageable); 20 | 21 | List findByTitle(String title); 22 | 23 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/es/BookService.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.PageRequest; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @Package org.jon.lv.es.BookService 10 | * @Copyright: Copyright (c) 2016 11 | * Author lv bin 12 | * @date 2017/5/22 13:56 13 | * version V1.0.0 14 | */ 15 | public interface BookService { 16 | 17 | Book save(Book book); 18 | 19 | void delete(Book book); 20 | 21 | Book findOne(String id); 22 | 23 | Iterable findAll(); 24 | 25 | Page findByAuthor(String author, PageRequest pageRequest); 26 | 27 | List findByTitle(String title); 28 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/es/BookServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.PageRequest; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @Package org.jon.lv.es.BookServiceImpl 12 | * @Copyright: Copyright (c) 2016 13 | * Author lv bin 14 | * @date 2017/5/22 13:57 15 | * version V1.0.0 16 | */ 17 | @Service 18 | public class BookServiceImpl implements BookService { 19 | @Autowired 20 | private BookRepository bookRepository; 21 | 22 | public Book save(Book book) { 23 | return bookRepository.save(book); 24 | } 25 | 26 | public void delete(Book book) { 27 | bookRepository.delete(book); 28 | } 29 | 30 | public Book findOne(String id) { 31 | return bookRepository.findOne(id); 32 | } 33 | 34 | public Iterable findAll() { 35 | return bookRepository.findAll(); 36 | } 37 | 38 | public Page findByAuthor(String author, PageRequest pageRequest) { 39 | return bookRepository.findByAuthor(author, pageRequest); 40 | } 41 | 42 | public List findByTitle(String title) { 43 | return bookRepository.findByTitle(title); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/es/Tag.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | /** 4 | * @Package org.jon.lv.es.Tag 5 | * @Copyright: Copyright (c) 2016 6 | * Author lv bin 7 | * @date 2017/5/22 14:01 8 | * version V1.0.0 9 | */ 10 | public class Tag { 11 | private String id; 12 | private String name; 13 | 14 | public String getId() { 15 | return id; 16 | } 17 | 18 | public void setId(String id) { 19 | this.id = id; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/exception/AppWebException.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.exception; 2 | 3 | /** 4 | * @Description: AppWebException 5 | * @Copyright: Copyright (c) 2016 6 | * Author lv bin 7 | * @date 2017/3/22 10:10 8 | * version V1.0.0 9 | */ 10 | public class AppWebException extends Exception{ 11 | private static final long serialVersionUID = -8198281171334131008L; 12 | 13 | private int errCode; 14 | 15 | public AppWebException() {} 16 | 17 | public AppWebException(int errCode, String message, 18 | Exception exception) { 19 | super(message, exception); 20 | 21 | this.errCode = errCode; 22 | } 23 | 24 | public AppWebException(int errCode, String message) { 25 | this(errCode, message,null); 26 | } 27 | 28 | public int getErrCode() { 29 | return this.errCode; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/exception/ErrorConstant.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.exception; 2 | 3 | /** 4 | * @Description: 错误对照码 5 | * @Copyright: Copyright (c) 2016 6 | * Author lv bin 7 | * @date 2017/3/17 9:43 8 | * version V1.0.0 9 | */ 10 | public enum ErrorConstant { 11 | BAD_REQUEST(400, "Bad Request!"), 12 | NOT_AUTHORIZATION(401, "NotAuthorization"), 13 | NOT_FOUND_REQUEST(404, "Not Found Request Path"), 14 | METHOD_NOT_ALLOWED(405, "Method Not Allowed"), 15 | NOT_ACCEPTABLE(406, "Not Acceptable"), 16 | INTERNAL_SERVER_ERROR(500, "Internal Server Error"), 17 | 18 | LOGIN_FIRST(999, "[服务器]请登录"), 19 | 20 | RUNTIME_EXCEPTION(1000, "[服务器]运行时异常"), 21 | NULL_POINTER_EXCEPTION(1001, "[服务器]空值异常"), 22 | CLASS_CAST_EXCEPTION(1002, "[服务器]数据类型转换异常"), 23 | IO_EXCEPTION(1003, "[服务器]IO异常"), 24 | NO_SUCH_METHOD_EXCEPTION(1004, "[服务器]未知方法异常"), 25 | INDEX_OUT_OF_BOUNDS_EXCEPTION(1005, "[服务器]数组越界异常"), 26 | CONNECT_EXCEPTION(1006, "[服务器]网络异常"), 27 | ERROR_MEDIA_TYPE(1007, "[服务器]Content-type错误,请使用application/json"), 28 | EMPTY_REQUEST_BOYD(1008, "[服务器]request请求body不能为空"), 29 | ERROR_REQUEST_BOYD(1009, "[服务器]request请求body非json对象"), 30 | ERROR_VERSION(2000, "[服务器]版本号错误"), 31 | ERROR_FORMAT_PARAMETER(2001, "[服务器]参数格式错误"); 32 | 33 | 34 | 35 | private final int code; 36 | private final String msg; 37 | 38 | public int getCode() { 39 | return code; 40 | } 41 | 42 | public String getMsg() { 43 | return msg; 44 | } 45 | 46 | ErrorConstant(int code, String msg) { 47 | this.code = code; 48 | this.msg = msg; 49 | } 50 | 51 | public static String getNameByValue(Integer val) { 52 | if (val != null) { 53 | int value = val; 54 | for (ErrorConstant constant : ErrorConstant.values()) { 55 | if (constant.code == value) { 56 | return constant.msg; 57 | } 58 | } 59 | } 60 | return ""; 61 | } 62 | 63 | public ErrorConstant getTypeByValue(int value) { 64 | for (ErrorConstant constant : ErrorConstant.values()) { 65 | if (constant.code == value) { 66 | return constant; 67 | } 68 | } 69 | return null; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/interceptors/AppInterceptors.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.interceptors; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 6 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.util.Date; 11 | 12 | /** 13 | * @Package org.jon.lv.interceptors.AppInterceptors 14 | * @Description: AppInterceptors 15 | * Author lv bin 16 | * @date 2017/5/16 13:12 17 | * version V1.0.0 18 | */ 19 | @Configuration 20 | public class AppInterceptors extends WebMvcConfigurerAdapter { 21 | 22 | public static String REQUEST_TIME = "http_request_time"; 23 | 24 | public void addInterceptors(InterceptorRegistry registry) { 25 | registry.addInterceptor(new HandlerInterceptorAdapter() { 26 | @Override 27 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 28 | Object handler) throws Exception { 29 | request.setAttribute(REQUEST_TIME, new Date()); 30 | System.out.println("interceptor====1111111111111"); 31 | return true; 32 | } 33 | }).addPathPatterns("/user/**", "/kafka/**"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/interceptors/AppResponseInterceptor.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.interceptors; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import org.jon.lv.result.ResultDO; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.core.MethodParameter; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.http.server.ServerHttpRequest; 10 | import org.springframework.http.server.ServerHttpResponse; 11 | import org.springframework.http.server.ServletServerHttpRequest; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | import java.lang.reflect.Method; 17 | import java.util.Date; 18 | 19 | /** 20 | * @Description: 统一响应结果处理 21 | * Author lv bin 22 | * @date 2017/3/17 10:45 23 | * version V1.0.0 24 | */ 25 | @ControllerAdvice 26 | public class AppResponseInterceptor implements ResponseBodyAdvice { 27 | 28 | private Logger logger = LoggerFactory.getLogger(AppResponseInterceptor.class); 29 | 30 | @Override 31 | public boolean supports(MethodParameter methodParameter, Class aClass) { 32 | 33 | return true; 34 | } 35 | 36 | @Override 37 | public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, 38 | ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { 39 | // 响应结果执行 40 | if(mediaType != null && o != null 41 | && mediaType.includes(MediaType.APPLICATION_JSON) 42 | && o instanceof ResultDO){ 43 | 44 | if(serverHttpRequest instanceof ServletServerHttpRequest){ 45 | 46 | ServletServerHttpRequest request = (ServletServerHttpRequest)serverHttpRequest; 47 | 48 | HttpServletRequest httpServletRequest = request.getServletRequest(); 49 | 50 | Date requestTime = (Date) httpServletRequest.getAttribute(AppInterceptors.REQUEST_TIME); 51 | 52 | long useTime = System.currentTimeMillis() - requestTime.getTime(); 53 | 54 | Method method = methodParameter.getMethod(); 55 | 56 | logger.debug("request controller:" + method.getDeclaringClass() + " request method:" + method.getName()); 57 | 58 | logger.debug("request link:" + serverHttpRequest.getURI() + " times:" + useTime); 59 | } 60 | 61 | 62 | logger.debug("response content:" + JSON.toJSONString(o)); 63 | } 64 | 65 | return o; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/interceptors/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.interceptors; 2 | 3 | import com.fasterxml.jackson.databind.JsonMappingException; 4 | import org.jon.lv.exception.AppWebException; 5 | import org.jon.lv.exception.ErrorConstant; 6 | import org.jon.lv.result.ResultDO; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.ConversionNotSupportedException; 10 | import org.springframework.beans.TypeMismatchException; 11 | import org.springframework.http.converter.HttpMessageNotReadableException; 12 | import org.springframework.http.converter.HttpMessageNotWritableException; 13 | import org.springframework.web.HttpMediaTypeNotAcceptableException; 14 | import org.springframework.web.HttpRequestMethodNotSupportedException; 15 | import org.springframework.web.bind.MissingServletRequestParameterException; 16 | import org.springframework.web.bind.annotation.ControllerAdvice; 17 | import org.springframework.web.bind.annotation.ExceptionHandler; 18 | import org.springframework.web.bind.annotation.ResponseBody; 19 | 20 | import javax.servlet.ServletException; 21 | import java.io.IOException; 22 | import java.net.ConnectException; 23 | 24 | /** 25 | * @Description: 全局异常 26 | * Author lv bin 27 | * @date 2017/3/17 9:35 28 | * version V1.0.0 29 | */ 30 | @ControllerAdvice 31 | public class GlobalExceptionHandler { 32 | 33 | protected static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); 34 | 35 | //运行时异常 36 | @ExceptionHandler(RuntimeException.class) 37 | @ResponseBody 38 | public ResultDO runtimeExceptionHandler(RuntimeException runtimeException) { 39 | return result(ErrorConstant.RUNTIME_EXCEPTION.getCode(), ErrorConstant.RUNTIME_EXCEPTION.getMsg(), runtimeException); 40 | } 41 | 42 | //空指针异常 43 | @ExceptionHandler(NullPointerException.class) 44 | @ResponseBody 45 | public ResultDO nullPointerExceptionHandler(NullPointerException ex) { 46 | return result(ErrorConstant.NULL_POINTER_EXCEPTION.getCode(), ErrorConstant.NULL_POINTER_EXCEPTION.getMsg(), ex); 47 | } 48 | 49 | //类型转换异常 50 | @ExceptionHandler(ClassCastException.class) 51 | @ResponseBody 52 | public ResultDO classCastExceptionHandler(ClassCastException ex) { 53 | return result(ErrorConstant.CLASS_CAST_EXCEPTION.getCode(), ErrorConstant.CLASS_CAST_EXCEPTION.getMsg(), ex); 54 | } 55 | 56 | //IO异常 57 | @ExceptionHandler(IOException.class) 58 | @ResponseBody 59 | public ResultDO iOExceptionHandler(IOException ex) { 60 | return result(ErrorConstant.IO_EXCEPTION.getCode(), ErrorConstant.IO_EXCEPTION.getMsg(), ex); 61 | } 62 | 63 | //未知方法异常 64 | @ExceptionHandler(NoSuchMethodException.class) 65 | @ResponseBody 66 | public ResultDO noSuchMethodExceptionHandler(NoSuchMethodException ex) { 67 | return result(ErrorConstant.NO_SUCH_METHOD_EXCEPTION.getCode(), ErrorConstant.NO_SUCH_METHOD_EXCEPTION.getMsg(), ex); 68 | } 69 | 70 | //数组越界异常 71 | @ExceptionHandler(IndexOutOfBoundsException.class) 72 | @ResponseBody 73 | public ResultDO indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) { 74 | return result(ErrorConstant.INDEX_OUT_OF_BOUNDS_EXCEPTION.getCode(), ErrorConstant.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMsg(), ex); 75 | } 76 | 77 | //网络异常 78 | @ExceptionHandler(ConnectException.class) 79 | @ResponseBody 80 | public ResultDO connectException(ConnectException ex) { 81 | return result(ErrorConstant.CONNECT_EXCEPTION.getCode(), ErrorConstant.CONNECT_EXCEPTION.getMsg(), ex); 82 | } 83 | 84 | //400错误 85 | @ExceptionHandler({HttpMessageNotReadableException.class}) 86 | @ResponseBody 87 | public ResultDO requestNotReadable(HttpMessageNotReadableException ex) { 88 | return result(ErrorConstant.BAD_REQUEST.getCode(), ErrorConstant.BAD_REQUEST.getMsg(), ex); 89 | } 90 | 91 | //400错误 92 | @ExceptionHandler({TypeMismatchException.class}) 93 | @ResponseBody 94 | public ResultDO requestTypeMismatch(TypeMismatchException ex) { 95 | return result(ErrorConstant.BAD_REQUEST.getCode(), ErrorConstant.BAD_REQUEST.getMsg(), ex); 96 | } 97 | 98 | //400错误 99 | @ExceptionHandler({MissingServletRequestParameterException.class}) 100 | @ResponseBody 101 | public ResultDO requestMissingServletRequest(MissingServletRequestParameterException ex) { 102 | return result(ErrorConstant.BAD_REQUEST.getCode(), ErrorConstant.BAD_REQUEST.getMsg(), ex); 103 | } 104 | 105 | @ExceptionHandler({ ServletException.class }) 106 | @ResponseBody 107 | public ResultDO http404(ServletException ex) { 108 | return result(ErrorConstant.NOT_FOUND_REQUEST.getCode(), ErrorConstant.NOT_FOUND_REQUEST.getMsg(), ex); 109 | } 110 | 111 | //405错误 112 | @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) 113 | @ResponseBody 114 | public ResultDO request405(HttpRequestMethodNotSupportedException ex) { 115 | return result(ErrorConstant.METHOD_NOT_ALLOWED.getCode(), ErrorConstant.METHOD_NOT_ALLOWED.getMsg(), ex); 116 | } 117 | 118 | //406错误 119 | @ExceptionHandler({HttpMediaTypeNotAcceptableException.class}) 120 | @ResponseBody 121 | public ResultDO request406(HttpMediaTypeNotAcceptableException ex) { 122 | return result(ErrorConstant.NOT_ACCEPTABLE.getCode(), ErrorConstant.NOT_ACCEPTABLE.getMsg(), ex); 123 | } 124 | 125 | //500错误 126 | @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class}) 127 | @ResponseBody 128 | public ResultDO server500(RuntimeException runtimeException) { 129 | return result(ErrorConstant.INTERNAL_SERVER_ERROR.getCode(), ErrorConstant.INTERNAL_SERVER_ERROR.getMsg(), runtimeException); 130 | } 131 | 132 | //app web 异常 133 | @ExceptionHandler({AppWebException.class}) 134 | @ResponseBody 135 | public ResultDO appWebException(AppWebException appWebException) { 136 | return result(appWebException.getErrCode(), appWebException.getMessage(), appWebException); 137 | } 138 | 139 | @ExceptionHandler({JsonMappingException.class}) 140 | @ResponseBody 141 | public ResultDO jsonMappingException(JsonMappingException jsonMappingException) { 142 | return result(ErrorConstant.ERROR_FORMAT_PARAMETER.getCode(), ErrorConstant.ERROR_FORMAT_PARAMETER.getMsg(), jsonMappingException); 143 | } 144 | 145 | 146 | /** 147 | * 结果集 148 | * @param errCode 149 | * @param errMsg 150 | * @param e 151 | * @return 152 | */ 153 | private ResultDO result(int errCode, String errMsg, Exception e){ 154 | ResultDO resultDO = new ResultDO(); 155 | resultDO.setErrCode(errCode); 156 | resultDO.setErrMsg(errMsg); 157 | 158 | logException(e); 159 | 160 | return resultDO; 161 | } 162 | 163 | /** 164 | * 异常记录 165 | * @param e 166 | */ 167 | private void logException(Exception e){ 168 | if(e instanceof AppWebException){ 169 | LOGGER.warn(e.getMessage(), e); 170 | }else{ 171 | LOGGER.error(e.getMessage(), e); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/kafka/KafkaConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.kafka; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.kafka.annotation.EnableKafka; 5 | 6 | /** 7 | * @Package org.jon.lv.kafka.KafkaConfiguration 8 | * @Copyright: Copyright (c) 2016 9 | * Author lv bin 10 | * @date 2017/5/18 16:12 11 | * version V1.0.0 12 | */ 13 | @Configuration 14 | @EnableKafka 15 | public class KafkaConfiguration { 16 | // kafka配置 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/kafka/MsgConsumer.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.kafka; 2 | 3 | import org.springframework.kafka.annotation.KafkaListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @Package org.jon.lv.kafka.MsgConsumer 8 | * @Description: 消息消费者 9 | * @Copyright: Copyright (c) 2016 10 | * Author lv bin 11 | * @date 2017/5/18 16:15 12 | * version V1.0.0 13 | */ 14 | @Component 15 | public class MsgConsumer { 16 | 17 | @KafkaListener(topics = {"jon-replicated-topic","jon-replicated-topic2"}) 18 | public void processMessage(String content) { 19 | System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$" + content); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/kafka/MsgProducer.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.kafka; 2 | 3 | 4 | import org.apache.kafka.clients.producer.Producer; 5 | import org.apache.kafka.clients.producer.RecordMetadata; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.kafka.core.KafkaOperations; 8 | import org.springframework.kafka.core.KafkaTemplate; 9 | import org.springframework.kafka.support.ProducerListener; 10 | import org.springframework.stereotype.Component; 11 | 12 | /** 13 | * @Package org.jon.lv.kafka.MsgProducer 14 | * @Description: 消息生产者 15 | * @Copyright: Copyright (c) 2016 16 | * Author lv bin 17 | * @date 2017/5/18 16:13 18 | * version V1.0.0 19 | */ 20 | @Component 21 | public class MsgProducer { 22 | @Autowired 23 | private KafkaTemplate kafkaTemplate; 24 | 25 | public void send(String content) { 26 | kafkaTemplate.send("jon-replicated-topic", content); 27 | kafkaTemplate.send("jon-replicated-topic2","测试消息:" + content); 28 | kafkaTemplate.metrics(); 29 | kafkaTemplate.execute(new KafkaOperations.ProducerCallback() { 30 | @Override 31 | public Object doInKafka(Producer producer) { 32 | //这里可以编写kafka原生的api操作 33 | return null; 34 | } 35 | }); 36 | 37 | //消息发送的监听器,用于回调返回信息 38 | kafkaTemplate.setProducerListener(new ProducerListener() { 39 | @Override 40 | public void onSuccess(String topic, Integer partition, String key, String value, RecordMetadata recordMetadata) { 41 | } 42 | 43 | @Override 44 | public void onError(String topic, Integer partition, String key, String value, Exception exception) { 45 | } 46 | 47 | @Override 48 | public boolean isInterestedInSuccess() { 49 | return false; 50 | } 51 | }); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.mapper; 2 | 3 | import org.apache.ibatis.annotations.Mapper; 4 | import org.jon.lv.domain.User; 5 | import org.jon.lv.pagination.Page; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @Package: org.jon.lv.mapper.UserMapper.java 12 | * @Description: InnoDB free: 4096 kB 13 | * @Copyright: Copyright (c) 2017 14 | * All right reserved. 15 | * Author jon lv 16 | * @date 2017/05/12 15:24 17 | * version v1.0.0 18 | */ 19 | //@Mapper 20 | public interface UserMapper { 21 | /** 22 | * @Description: 根据主键删除数据库的记录 23 | * @Title deleteByPrimaryKey 24 | * @Author jon lv 25 | * @Date 2017/05/12 15:24 26 | * @param id 27 | * @return int 28 | * @throws [] 29 | */ 30 | int deleteByPrimaryKey(Integer id); 31 | 32 | /** 33 | * @Description: 插入数据库记录 34 | * @Title insert 35 | * @Author jon lv 36 | * @Date 2017/05/12 15:24 37 | * @param record 38 | * @return int 39 | * @throws [] 40 | */ 41 | int insert(User record); 42 | 43 | /** 44 | * @Description: 选择性插入数据库记录 45 | * @Title insertSelective 46 | * @Author jon lv 47 | * @Date 2017/05/12 15:24 48 | * @param record 49 | * @return int 50 | * @throws [] 51 | */ 52 | int insertSelective(User record); 53 | 54 | /** 55 | * @Description: 根据主键获取一条数据库记录 56 | * @Title selectByPrimaryKey 57 | * @Author jon lv 58 | * @Date 2017/05/12 15:24 59 | * @param id 60 | * @return org.jon.lv.domain.User 61 | * @throws [] 62 | */ 63 | User selectByPrimaryKey(Integer id); 64 | 65 | /** 66 | * @Description: 根据主键来更新对应数据库字段 67 | * @Title updateByPrimaryKeySelective 68 | * @Author jon lv 69 | * @Date 2017/05/12 15:24 70 | * @param record 71 | * @return int 72 | * @throws [] 73 | */ 74 | int updateByPrimaryKeySelective(User record); 75 | 76 | /** 77 | * @Description: 根据主键来更新数据库记录 78 | * @Title updateByPrimaryKey 79 | * @Author jon lv 80 | * @Date 2017/05/12 15:24 81 | * @param record 82 | * @return int 83 | * @throws [] 84 | */ 85 | int updateByPrimaryKey(User record); 86 | 87 | List queryPage(Page page); 88 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/redis/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.redis; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.PropertyAccessor; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | import org.springframework.cache.CacheManager; 9 | import org.springframework.cache.annotation.CachingConfigurerSupport; 10 | import org.springframework.cache.annotation.EnableCaching; 11 | import org.springframework.cache.interceptor.KeyGenerator; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.PropertySource; 15 | import org.springframework.data.redis.cache.RedisCacheManager; 16 | import org.springframework.data.redis.connection.RedisConnectionFactory; 17 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 18 | import org.springframework.data.redis.core.RedisTemplate; 19 | import org.springframework.data.redis.core.StringRedisTemplate; 20 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 21 | import org.springframework.data.redis.serializer.StringRedisSerializer; 22 | 23 | import java.lang.reflect.Method; 24 | 25 | /** 26 | * @Package org.jon.lv.redis.RedisConfig 27 | * @Description: RedisConfig 28 | * @Copyright: Copyright (c) 2016 29 | * Author lv bin 30 | * @date 2017/5/18 13:58 31 | * version V1.0.0 32 | */ 33 | @Configuration 34 | @EnableCaching 35 | public class RedisConfig extends CachingConfigurerSupport { 36 | @Bean 37 | public KeyGenerator keyGenerator() { 38 | return new KeyGenerator() { 39 | @Override 40 | public Object generate(Object target, Method method, Object... params) { 41 | StringBuilder sb = new StringBuilder(); 42 | sb.append(target.getClass().getName()); 43 | sb.append(method.getName()); 44 | for (Object obj : params) { 45 | sb.append(obj.toString()); 46 | } 47 | return sb.toString(); 48 | } 49 | }; 50 | } 51 | 52 | /** 53 | * RedisTemplate配置 54 | * @return 55 | */ 56 | @Bean 57 | public RedisTemplate redisTemplate(RedisConnectionFactory factory) { 58 | RedisTemplate redisTemplate = new RedisTemplate(); 59 | redisTemplate.setConnectionFactory(factory); 60 | // 开启事务支持 61 | redisTemplate.setEnableTransactionSupport(true); 62 | // 使用String格式序列化缓存键 63 | StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); 64 | redisTemplate.setKeySerializer(stringRedisSerializer); 65 | redisTemplate.setHashKeySerializer(stringRedisSerializer); 66 | 67 | // 设置缓存 68 | RedisUtils.setRedisTemplate(redisTemplate); 69 | 70 | return redisTemplate; 71 | } 72 | 73 | /** 74 | * 管理缓存 75 | * 设置缓存对象的序列化方式,不设置会报错 76 | * 另外对于json序列化,对象要提供默认空构造器 77 | * @param redisTemplate 78 | * @return 79 | */ 80 | @Bean 81 | public CacheManager cacheManager(RedisTemplate redisTemplate) { 82 | Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 83 | ObjectMapper om = new ObjectMapper(); 84 | om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 85 | om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 86 | jackson2JsonRedisSerializer.setObjectMapper(om); 87 | redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); 88 | 89 | RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); 90 | cacheManager.setDefaultExpiration(300);//秒 91 | return cacheManager; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/redis/RedisUtils.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.redis; 2 | 3 | import org.springframework.data.redis.core.RedisTemplate; 4 | import org.springframework.data.redis.core.ValueOperations; 5 | 6 | import java.io.Serializable; 7 | import java.util.Set; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * @Package org.jon.lv.redis.RedisUtils 12 | * @Description: RedisUtils 13 | * @Copyright: Copyright (c) 2016 14 | * Author lv bin 15 | * @date 2017/5/18 14:08 16 | * version V1.0.0 17 | */ 18 | public class RedisUtils { 19 | 20 | private static RedisTemplate redisTemplate; 21 | 22 | /** 23 | * 批量删除对应的value 24 | * 25 | * @param keys 26 | */ 27 | public static void remove(final String... keys) { 28 | for (String key : keys) { 29 | remove(key); 30 | } 31 | } 32 | /** 33 | * 批量删除key 34 | * 35 | * @param pattern 36 | */ 37 | public static void removePattern(final String pattern) { 38 | Set keys = redisTemplate.keys(pattern); 39 | if (keys.size() > 0) 40 | redisTemplate.delete(keys); 41 | } 42 | /** 43 | * 删除对应的value 44 | * 45 | * @param key 46 | */ 47 | public static void remove(final String key) { 48 | if (exists(key)) { 49 | redisTemplate.delete(key); 50 | } 51 | } 52 | /** 53 | * 判断缓存中是否有对应的value 54 | * 55 | * @param key 56 | * @return 57 | */ 58 | public static boolean exists(final String key) { 59 | return redisTemplate.hasKey(key); 60 | } 61 | /** 62 | * 读取缓存 63 | * 64 | * @param key 65 | * @return 66 | */ 67 | public static Object get(final String key) { 68 | Object result = null; 69 | ValueOperations operations = redisTemplate.opsForValue(); 70 | result = operations.get(key); 71 | return result; 72 | } 73 | /** 74 | * 写入缓存 75 | * 76 | * @param key 77 | * @param value 78 | * @return 79 | */ 80 | public static boolean set(final String key, Object value) { 81 | boolean result = false; 82 | try { 83 | ValueOperations operations = redisTemplate.opsForValue(); 84 | operations.set(key, value); 85 | result = true; 86 | } catch (Exception e) { 87 | e.printStackTrace(); 88 | } 89 | return result; 90 | } 91 | /** 92 | * 写入缓存 93 | * 94 | * @param key 95 | * @param value 96 | * @return 97 | */ 98 | public static boolean set(final String key, Object value, Long expireTime) { 99 | boolean result = false; 100 | try { 101 | ValueOperations operations = redisTemplate.opsForValue(); 102 | operations.set(key, value); 103 | redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); 104 | result = true; 105 | } catch (Exception e) { 106 | e.printStackTrace(); 107 | } 108 | return result; 109 | } 110 | 111 | /** 112 | * 缓存设置 113 | * @param redisTemplate 114 | */ 115 | public static void setRedisTemplate(RedisTemplate redisTemplate){ 116 | RedisUtils.redisTemplate = redisTemplate; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/redis/SessionConfig.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.redis; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; 5 | 6 | /** 7 | * @Package org.jon.lv.redis.SessionConfig 8 | * @Copyright: Copyright (c) 2016 9 | * Author lv bin 10 | * @date 2017/5/18 14:14 11 | * version V1.0.0 12 | */ 13 | @Configuration 14 | @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) 15 | public class SessionConfig { 16 | // maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/result/ResultDO.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.result; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @Package org.jon.lv.result.ResultDO 7 | * Author lv bin 8 | * @date 2017/5/16 13:29 9 | * version V1.0.0 10 | */ 11 | public class ResultDO implements Serializable { 12 | 13 | /** 14 | * serialVersionUID 15 | */ 16 | private static final long serialVersionUID = 4227833010077730477L; 17 | 18 | /** 19 | * 是否成功,默认失败 20 | */ 21 | private boolean success = false; 22 | 23 | /** 24 | * 返回消息 25 | */ 26 | private String errMsg; 27 | 28 | /** 29 | * 返回CODE 30 | */ 31 | private int errCode; 32 | 33 | /** 34 | * 返回结果封装器 35 | */ 36 | private T data; 37 | 38 | 39 | public boolean isSuccess() { 40 | return success; 41 | } 42 | 43 | 44 | public void setSuccess(boolean success) { 45 | this.success = success; 46 | } 47 | 48 | public String getErrMsg() { 49 | return errMsg; 50 | } 51 | 52 | public void setErrMsg(String errMsg) { 53 | this.errMsg = errMsg; 54 | } 55 | 56 | public int getErrCode() { 57 | return errCode; 58 | } 59 | 60 | public void setErrCode(int errCode) { 61 | this.errCode = errCode; 62 | } 63 | 64 | public T getData() { 65 | return data; 66 | } 67 | 68 | public void setData(T data) { 69 | this.data = data; 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/service/UserService.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.service; 2 | 3 | import org.jon.lv.domain.User; 4 | import org.jon.lv.mapper.UserMapper; 5 | import org.jon.lv.pagination.Page; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | /** 11 | * @Package org.jon.lv.service.UserService 12 | * @Description: UserService 13 | * @Copyright: Copyright (c) 2016 14 | * Author lv bin 15 | * @date 2017/5/12 15:30 16 | * version V1.0.0 17 | */ 18 | @Service 19 | public class UserService { 20 | @Autowired 21 | private UserMapper userMapper; 22 | 23 | @Transactional 24 | public Integer saveDouble(User user){ 25 | userMapper.insert(user); 26 | user.setId(null); 27 | userMapper.insert(user); 28 | 29 | return user.getId(); 30 | } 31 | 32 | 33 | public Integer save(User user){ 34 | userMapper.insert(user); 35 | 36 | return user.getId(); 37 | } 38 | 39 | 40 | public User getUserById(Integer id){ 41 | return userMapper.selectByPrimaryKey(id); 42 | } 43 | 44 | 45 | public Page queryPage(Integer pageNumber, Integer pageSize){ 46 | Page page = new Page<>(pageNumber, pageSize); 47 | userMapper.queryPage(page); 48 | return page; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/jon/lv/spy/SqlCostInterceptor.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.spy; 2 | 3 | import org.apache.ibatis.executor.statement.StatementHandler; 4 | import org.apache.ibatis.mapping.BoundSql; 5 | import org.apache.ibatis.mapping.ParameterMapping; 6 | import org.apache.ibatis.plugin.*; 7 | import org.apache.ibatis.session.ResultHandler; 8 | import org.apache.ibatis.session.defaults.DefaultSqlSession.StrictMap; 9 | 10 | import java.lang.reflect.Field; 11 | import java.sql.Statement; 12 | import java.util.Collection; 13 | import java.util.List; 14 | import java.util.Map; 15 | import java.util.Properties; 16 | 17 | /** 18 | * Sql执行时间记录拦截器 19 | */ 20 | @Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), 21 | @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), 22 | @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})}) 23 | public class SqlCostInterceptor implements Interceptor { 24 | 25 | @Override 26 | public Object intercept(Invocation invocation) throws Throwable { 27 | Object target = invocation.getTarget(); 28 | 29 | long startTime = System.currentTimeMillis(); 30 | StatementHandler statementHandler = (StatementHandler) target; 31 | try { 32 | return invocation.proceed(); 33 | } finally { 34 | long endTime = System.currentTimeMillis(); 35 | long sqlCost = endTime - startTime; 36 | 37 | BoundSql boundSql = statementHandler.getBoundSql(); 38 | String sql = boundSql.getSql(); 39 | Object parameterObject = boundSql.getParameterObject(); 40 | List parameterMappingList = boundSql.getParameterMappings(); 41 | 42 | // 格式化Sql语句,去除换行符,替换参数 43 | sql = formatSql(sql, parameterObject, parameterMappingList); 44 | 45 | System.out.println("SQL:[" + sql + "]执行耗时[" + sqlCost + "ms]"); 46 | } 47 | } 48 | 49 | @Override 50 | public Object plugin(Object target) { 51 | return Plugin.wrap(target, this); 52 | } 53 | 54 | @Override 55 | public void setProperties(Properties properties) { 56 | 57 | } 58 | 59 | @SuppressWarnings("unchecked") 60 | private String formatSql(String sql, Object parameterObject, List parameterMappingList) { 61 | // 输入sql字符串空判断 62 | if (sql == null || sql.length() == 0) { 63 | return ""; 64 | } 65 | 66 | // 美化sql 67 | sql = beautifySql(sql); 68 | 69 | // 不传参数的场景,直接把Sql美化一下返回出去 70 | if (parameterObject == null || parameterMappingList == null || parameterMappingList.size() == 0) { 71 | return sql; 72 | } 73 | 74 | // 定义一个没有替换过占位符的sql,用于出异常时返回 75 | String sqlWithoutReplacePlaceholder = sql; 76 | 77 | try { 78 | if (parameterMappingList != null) { 79 | Class parameterObjectClass = parameterObject.getClass(); 80 | 81 | // 如果参数是StrictMap且Value类型为Collection,获取key="list"的属性,这里主要是为了处理循环时传入List这种参数的占位符替换 82 | // 例如select * from xxx where id in ... 83 | if (isStrictMap(parameterObjectClass)) { 84 | StrictMap> strictMap = (StrictMap>) parameterObject; 85 | 86 | if (isList(strictMap.get("list").getClass())) { 87 | sql = handleListParameter(sql, strictMap.get("list")); 88 | } 89 | } else if (isMap(parameterObjectClass)) { 90 | // 如果参数是Map则直接强转,通过map.get(key)方法获取真正的属性值 91 | // 这里主要是为了处理 16 | select 17 | 18 | from user 19 | where id = #{id,jdbcType=INTEGER} 20 | 21 | 22 | delete from user 23 | where id = #{id,jdbcType=INTEGER} 24 | 25 | 26 | insert into user (id, head, name, 27 | phone, picture, sex 28 | ) 29 | values (#{id,jdbcType=INTEGER}, #{head,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 30 | #{phone,jdbcType=VARCHAR}, #{picture,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER} 31 | ) 32 | 33 | 34 | insert into user 35 | 36 | 37 | id, 38 | 39 | 40 | head, 41 | 42 | 43 | name, 44 | 45 | 46 | phone, 47 | 48 | 49 | picture, 50 | 51 | 52 | sex, 53 | 54 | 55 | 56 | 57 | #{id,jdbcType=INTEGER}, 58 | 59 | 60 | #{head,jdbcType=VARCHAR}, 61 | 62 | 63 | #{name,jdbcType=VARCHAR}, 64 | 65 | 66 | #{phone,jdbcType=VARCHAR}, 67 | 68 | 69 | #{picture,jdbcType=VARCHAR}, 70 | 71 | 72 | #{sex,jdbcType=INTEGER}, 73 | 74 | 75 | 76 | 77 | update user 78 | 79 | 80 | head = #{head,jdbcType=VARCHAR}, 81 | 82 | 83 | name = #{name,jdbcType=VARCHAR}, 84 | 85 | 86 | phone = #{phone,jdbcType=VARCHAR}, 87 | 88 | 89 | picture = #{picture,jdbcType=VARCHAR}, 90 | 91 | 92 | sex = #{sex,jdbcType=INTEGER}, 93 | 94 | 95 | where id = #{id,jdbcType=INTEGER} 96 | 97 | 98 | update user 99 | set head = #{head,jdbcType=VARCHAR}, 100 | name = #{name,jdbcType=VARCHAR}, 101 | phone = #{phone,jdbcType=VARCHAR}, 102 | picture = #{picture,jdbcType=VARCHAR}, 103 | sex = #{sex,jdbcType=INTEGER} 104 | where id = #{id,jdbcType=INTEGER} 105 | 106 | 107 | 112 | -------------------------------------------------------------------------------- /src/main/resources/mybatis/mybatis-config.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/main/resources/xml/application-bean.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/MockitoControllerExampleTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Before; 2 | import org.junit.Test; 3 | import org.mockito.InjectMocks; 4 | import org.mockito.Matchers; 5 | import org.mockito.Mock; 6 | import org.mockito.Mockito; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.mock.web.MockMultipartFile; 9 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 10 | import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 11 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | 14 | import java.io.ByteArrayInputStream; 15 | import java.io.InputStream; 16 | 17 | /** 18 | * Description: 描述 19 | * Copyright: Copyright (c) 2017 20 | * @author lv bin 21 | * Version: V1.0.0 22 | */ 23 | public class MockitoControllerExampleTest { 24 | 25 | // public MockMvc mockMvc; 26 | 27 | // @InjectMocks 28 | // private FileController fileController; 29 | 30 | // @Mock 31 | // private FileService fileService; 32 | 33 | // @Before 34 | // public void init(){ 35 | // MockitoAnnotations.initMocks(this); 36 | //构造MockMvc 37 | // mockMvc = MockMvcBuilders.standaloneSetup(fileController).build(); 38 | // } 39 | 40 | // @Test 41 | // public void avatar() throws Exception { 42 | // Mockito.when(fileService.upload(Matchers.anyObject(), Matchers.anyString())).thenReturn(new String()); 43 | 44 | // InputStream inputStream = new ByteArrayInputStream(new String("test").getBytes()); 45 | // mockMvc.perform( 46 | // MockMvcRequestBuilders.fileUpload("/file"). 47 | // file(new MockMultipartFile("file", inputStream)). 48 | // header(TOKEN_NAME, token).header(UID, uid)) 49 | // .andExpect(MockMvcResultMatchers.status().isOk()) 50 | // .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 51 | // .andExpect(MockMvcResultMatchers.content().json("{\"code\":\"000000\",\"message\":\"success\",\"data\":\"\"}")) 52 | // .andDo(MockMvcResultHandlers.print()).andReturn(); 53 | 54 | // } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/MockitoExampleTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv; 2 | 3 | import org.jon.lv.service.UserService; 4 | import org.junit.Assert; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.mockito.*; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | 10 | 11 | public class MockitoExampleTest extends SpringbootexampleApplicationTests { 12 | 13 | // @Mock //需要mock的bean 14 | // private UserService userService; 15 | 16 | // @Autowired 17 | // @InjectMocks //被注入mock对象的类一般是被测试类 18 | // private UserAO userAO; 19 | 20 | 21 | // @Before 22 | // public void setUp() { 23 | // MockitoAnnotations.initMocks(this); 24 | // Mockito.when(userService.getUserByName("zhangsan")).thenReturn("zhangsan"); 25 | // 方法调用时,如果不想指定一个明确的参数,就可以用下面这样的写法来表示任意的参数。 26 | // Mockito.when(userService.getUserByName(Matchers.anyString())).thenReturn("zhangsan"); 27 | // } 28 | 29 | // @Test 30 | // public void getUserByName() throws Exception { 31 | // System.out.println("----------------------"); 32 | // System.out.println("----------------------" + userAO.getUserByName("lisi")); 33 | // Assert.assertTrue(userAO.getUserByName("lisi").equals("zhangsan")); 34 | // System.out.println("----------------------"); 35 | // } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/SpringbootexampleApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv; 2 | 3 | import com.alibaba.dubbo.config.ProtocolConfig; 4 | import org.junit.After; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.test.web.servlet.MockMvc; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | import org.springframework.web.context.WebApplicationContext; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | public class SpringbootexampleApplicationTests { 18 | 19 | @Autowired 20 | private WebApplicationContext webApplicationContext; 21 | 22 | public MockMvc mockMvc; 23 | 24 | @Before 25 | public void setUp() throws Exception { 26 | mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 27 | } 28 | 29 | @Test 30 | public void contextLoads() { 31 | System.out.println("hello world"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/controller/UserControllerTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.controller; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.junit.Test; 5 | import org.springframework.http.MediaType; 6 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 7 | import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 8 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 9 | 10 | /** 11 | * @Package org.jon.lv.controller.UserControllerTest 12 | * @Copyright: Copyright (c) 2016 13 | * Author lv bin 14 | * @date 2017/5/16 13:14 15 | * version V1.0.0 16 | */ 17 | public class UserControllerTest extends SpringbootexampleApplicationTests { 18 | @Test 19 | public void testGet() throws Exception { 20 | mockMvc.perform(MockMvcRequestBuilders.post("/user/get/38710") 21 | .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 22 | .andExpect(MockMvcResultMatchers.status().isOk()) 23 | .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 24 | .andDo(MockMvcResultHandlers.print()) 25 | .andReturn(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/dubbo/DubboDemoServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.dubbo; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.junit.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @Package org.jon.lv.dubbo.DubboDemoServiceTest 10 | * @Description: DubboDemoServiceTest 11 | * @Copyright: Copyright (c) 2016 12 | * Author lv bin 13 | * @date 2017/5/22 8:48 14 | * version V1.0.0 15 | */ 16 | @Service 17 | public class DubboDemoServiceTest extends SpringbootexampleApplicationTests { 18 | // 19 | // @Autowired 20 | // private DubboDemoService dubboDemoService; 21 | // 22 | // @Autowired 23 | // private DubboTestService dubboTestService; 24 | // 25 | // @Test 26 | // public void say() throws InterruptedException { 27 | // dubboDemoService.say("sdhksdkjs四大皆空手机登录速度快"); 28 | // System.out.println("--------------------------------------------"); 29 | // dubboTestService.say("圣诞节快乐速度肯定是副科级"); 30 | // System.out.println("--------------------------------------------"); 31 | // } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/es/ESTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.es; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; 8 | 9 | import java.util.Arrays; 10 | import java.util.List; 11 | 12 | /** 13 | * @Package org.jon.lv.es.ESTest 14 | * @Copyright: Copyright (c) 2016 15 | * Author lv bin 16 | * @date 2017/5/22 14:08 17 | * version V1.0.0 18 | */ 19 | public class ESTest extends SpringbootexampleApplicationTests{ 20 | 21 | @Autowired 22 | private BookService bookService; 23 | 24 | @Test 25 | public void testSave() throws Exception { 26 | Tag tag = new Tag(); 27 | tag.setId("1"); 28 | tag.setName("tech"); 29 | Tag tag2 = new Tag(); 30 | tag2.setId("2"); 31 | tag2.setName("elasticsearch"); 32 | Book book = new Book("1003", "spring boot从入门到放弃", "jon lv", "23-FEB-2017"); 33 | book.setTags(Arrays.asList(tag, tag2)); 34 | bookService.save(book); 35 | } 36 | 37 | @Test 38 | public void testFindOne(){ 39 | Book book = bookService.findOne("1003"); 40 | 41 | System.out.println(book); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/mail/EmailService.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.mail; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.junit.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.core.io.FileSystemResource; 7 | import org.springframework.mail.SimpleMailMessage; 8 | import org.springframework.mail.javamail.JavaMailSender; 9 | import org.springframework.mail.javamail.MimeMessageHelper; 10 | 11 | import javax.mail.MessagingException; 12 | import javax.mail.internet.MimeMessage; 13 | import java.io.File; 14 | 15 | /** 16 | * @Package org.jon.lv.mail.EmailService 17 | * @Description: EmailService 18 | * @Company:上海房产 19 | * @Copyright: Copyright (c) 2016 20 | * Author lv bin 21 | * @date 2017/5/16 11:02 22 | * version V1.0.0 23 | */ 24 | public class EmailService extends SpringbootexampleApplicationTests { 25 | 26 | @Autowired 27 | private JavaMailSender mailSender; 28 | /** 29 | * 修改application.properties的用户,才能发送。 30 | */ 31 | @Test 32 | public void sendSimpleEmail(){ 33 | SimpleMailMessage message = new SimpleMailMessage(); 34 | message.setFrom("316476844@qq.com");//发送者. 35 | message.setTo("lvbin@oriental-finance.com");//接收者. 36 | message.setSubject("测试邮件(邮件主题)");//邮件主题. 37 | message.setText("这是邮件内容");//邮件内容. 38 | 39 | mailSender.send(message);//发送邮件 40 | } 41 | 42 | /** 43 | * 测试发送附件.(这里发送图片.) 44 | * @throws MessagingException 45 | */ 46 | @Test 47 | public void sendAttachmentsEmail() throws MessagingException { 48 | //这个是javax.mail.internet.MimeMessage下的,不要搞错了。 49 | MimeMessage mimeMessage = mailSender.createMimeMessage(); 50 | MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); 51 | //基本设置. 52 | helper.setFrom("316476844@qq.com");//发送者. 53 | helper.setTo("lvbin@oriental-finance.com");//接收者. 54 | helper.setSubject("测试附件(邮件主题)");//邮件主题. 55 | helper.setText("这是邮件内容(有附件哦.)");//邮件内容. 56 | //附件1,获取文件对象. 57 | FileSystemResource file1 = new FileSystemResource(new File("D:/41654.jpg")); 58 | //添加附件,这里第一个参数是在邮件中显示的名称,也可以直接是head.jpg,但是一定要有文件后缀,不然就无法显示图片了。 59 | helper.addAttachment("头像1.jpg", file1); 60 | //附件2 61 | FileSystemResource file2 = new FileSystemResource(new File("D:/api.html")); 62 | helper.addAttachment("api.html", file2); 63 | mailSender.send(mimeMessage); 64 | } 65 | 66 | /** 67 | * 邮件中使用静态资源. 68 | * @throws Exception 69 | */ 70 | @Test 71 | public void sendInlineMail() throws Exception { 72 | MimeMessage mimeMessage = mailSender.createMimeMessage(); 73 | MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); 74 | //基本设置. 75 | helper.setFrom("316476844@qq.com");//发送者. 76 | helper.setTo("lvbin@oriental-finance.com");//接收者. 77 | helper.setSubject("测试静态资源(邮件主题)");//邮件主题. 78 | // 邮件内容,第二个参数指定发送的是HTML格式 79 | //说明:嵌入图片,其中cid:是固定的写法,而aaa是一个contentId。 80 | helper.setText("这是图片:", true); 81 | FileSystemResource file = new FileSystemResource(new File("D:/41654.jpg")); 82 | helper.addInline("head",file); 83 | mailSender.send(mimeMessage); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/redis/RedisTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.redis; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.jon.lv.domain.User; 5 | import org.junit.Test; 6 | 7 | /** 8 | * @Package org.jon.lv.redis.RedisTest 9 | * @Company:上海房产 10 | * @Copyright: Copyright (c) 2016 11 | * Author lv bin 12 | * @date 2017/5/18 15:01 13 | * version V1.0.0 14 | */ 15 | public class RedisTest extends SpringbootexampleApplicationTests { 16 | 17 | @Test 18 | public void setVal(){ 19 | // RedisUtils.set("springboottest111111", "中国式", 10000L); 20 | User user = new User(); 21 | user.setName("测试"); 22 | user.setPhone("123444444444"); 23 | RedisUtils.set("springboottest", user, 10000L); 24 | } 25 | 26 | @Test 27 | public void getVal(){ 28 | System.out.println("**************************" + RedisUtils.get("springboottest")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/service/UserServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.service; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.jon.lv.domain.User; 5 | import org.jon.lv.pagination.Page; 6 | import org.junit.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | 9 | /** 10 | * @Package org.jon.lv.service.UserServiceTest 11 | * @Description: UserServiceTest 12 | * @Copyright: Copyright (c) 2016 13 | * Author lv bin 14 | * @date 2017/5/12 17:21 15 | * version V1.0.0 16 | */ 17 | public class UserServiceTest extends SpringbootexampleApplicationTests { 18 | 19 | @Autowired 20 | private UserService userService; 21 | 22 | @Test 23 | public void testSaveDouble(){ 24 | User user = new User(); 25 | user.setHead("测试121212"); 26 | user.setName("hello world"); 27 | userService.saveDouble(user); 28 | 29 | System.out.println(user); 30 | } 31 | 32 | @Test 33 | public void testSave(){ 34 | User user = new User(); 35 | user.setHead("dev world"); 36 | user.setName("dev world"); 37 | userService.save(user); 38 | System.out.println(user); 39 | } 40 | 41 | @Test 42 | public void testQueryPage(){ 43 | Page page = userService.queryPage(1,2); 44 | System.out.println(page); 45 | } 46 | 47 | @Test 48 | public void testGetOne(){ 49 | User user = userService.getUserById(82006); 50 | System.out.println(user); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/org/jon/lv/xml/XmlTest.java: -------------------------------------------------------------------------------- 1 | package org.jon.lv.xml; 2 | 3 | import org.jon.lv.SpringbootexampleApplicationTests; 4 | import org.junit.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | /** 8 | * @Package org.jon.lv.xml.XmlTest 9 | * @Copyright: Copyright (c) 2016 10 | * Author lv bin 11 | * @date 2017/5/18 15:40 12 | * version V1.0.0 13 | */ 14 | public class XmlTest extends SpringbootexampleApplicationTests { 15 | 16 | @Autowired 17 | private HelloService helloService; 18 | 19 | @Test 20 | public void testSay(){ 21 | helloService.say("你好吗?"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /user.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `user` ( 2 | `id` INT(5) NOT NULL AUTO_INCREMENT, 3 | `head` VARCHAR(300) NULL DEFAULT NULL, 4 | `name` VARCHAR(20) NOT NULL, 5 | `phone` VARCHAR(14) NULL DEFAULT NULL, 6 | `picture` VARCHAR(3000) NULL DEFAULT NULL, 7 | `sex` INT(11) NULL DEFAULT NULL, 8 | PRIMARY KEY (`id`), 9 | UNIQUE INDEX `name` (`name`) 10 | ) 11 | ENGINE=InnoDB 12 | ROW_FORMAT=DEFAULT 13 | AUTO_INCREMENT=1 --------------------------------------------------------------------------------