From e4fcd6124f549952a31cd8d8f5237f40371cafae Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 11 Mar 2020 20:37:43 +0800 Subject: [PATCH 01/49] =?UTF-8?q?=E6=B7=BB=E5=8A=A0.gitignore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 11 +++++++++++ springboot-mybatis-tx/pom.xml | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..63ecbe0 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,11 @@ +# Default ignored files +/workspace.xml +/compiler.xml +/encodings.xml +/misc.xml +/modules.xml +/SpringBootLearning.iml +/vcs.xml +/inspectionProfiles/ +/sonarlint/ +/libraries/ diff --git a/springboot-mybatis-tx/pom.xml b/springboot-mybatis-tx/pom.xml index d7ff404..2a695fb4 100755 --- a/springboot-mybatis-tx/pom.xml +++ b/springboot-mybatis-tx/pom.xml @@ -4,11 +4,11 @@ 4.0.0 com.forezp - springboot-mybatis + springboot-mybatis-tx 0.0.1-SNAPSHOT jar - springboot-mybatis + springboot-mybatis-tx Demo project for Spring Boot -- Gitee From 9072e80459f80b5ce6a0c78f5b3b331f545608a4 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 18 Mar 2020 19:10:55 +0800 Subject: [PATCH 02/49] =?UTF-8?q?ignore=E6=95=B0=E6=8D=AE=E6=BA=90?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 5 +++++ .idea/dataSources.xml | 14 ++++++++++++++ .idea/sqldialects.xml | 6 ++++++ 3 files changed, 25 insertions(+) create mode 100644 .idea/dataSources.xml create mode 100644 .idea/sqldialects.xml diff --git a/.idea/.gitignore b/.idea/.gitignore index 63ecbe0..a2dfc4b 100644 --- a/.idea/.gitignore +++ b/.idea/.gitignore @@ -9,3 +9,8 @@ /inspectionProfiles/ /sonarlint/ /libraries/ +# Datasource local storage ignored files +/dataSources.local.xml +/dataSources/ +dataSources.xml +sqldialects.xml diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..c066f9a --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,14 @@ + + + + + mysql.8 + true + com.mysql.cj.jdbc.Driver + jdbc:mysql://localhost:3306/test + + + + + + \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml new file mode 100644 index 0000000..91ea6a9 --- /dev/null +++ b/.idea/sqldialects.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file -- Gitee From 1c6126a9bf8e0e0a760793b15079fba133e84763 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 18 Mar 2020 19:12:10 +0800 Subject: [PATCH 03/49] =?UTF-8?q?ignore=E6=95=B0=E6=8D=AE=E6=BA=90?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 2 +- .idea/dataSources.xml | 14 -------------- .idea/sqldialects.xml | 6 ------ 3 files changed, 1 insertion(+), 21 deletions(-) delete mode 100644 .idea/dataSources.xml delete mode 100644 .idea/sqldialects.xml diff --git a/.idea/.gitignore b/.idea/.gitignore index a2dfc4b..5f8578f 100644 --- a/.idea/.gitignore +++ b/.idea/.gitignore @@ -13,4 +13,4 @@ /dataSources.local.xml /dataSources/ dataSources.xml -sqldialects.xml +sqldialects.xml \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index c066f9a..0000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - mysql.8 - true - com.mysql.cj.jdbc.Driver - jdbc:mysql://localhost:3306/test - - - - - - \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml deleted file mode 100644 index 91ea6a9..0000000 --- a/.idea/sqldialects.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file -- Gitee From f7330c989e6b58908817b7215d4f2e5c1eb39fb6 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 18 Mar 2020 21:42:30 +0800 Subject: [PATCH 04/49] =?UTF-8?q?=E6=B7=BB=E5=8A=A0springboot-Redis?= =?UTF-8?q?=E7=9A=84demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-redis-message/pom.xml | 4 +- .../main/java/com/forezp/dao/RedisDao.java | 7 +- .../SpringbootRedisApplicationTests.java | 7 +- springboot-redis/.gitignore | 32 ++ springboot-redis/mvnw | 310 ++++++++++++++++++ springboot-redis/mvnw.cmd | 182 ++++++++++ springboot-redis/pom.xml | 55 ++++ .../SpringbootRedisApplication.java | 13 + .../springbootredis/config/RedisConfig.java | 24 ++ .../example/springbootredis/entity/Days.java | 18 + .../src/main/resources/application.properties | 4 + .../SpringbootRedisApplicationTests.java | 38 +++ 12 files changed, 686 insertions(+), 8 deletions(-) create mode 100644 springboot-redis/.gitignore create mode 100644 springboot-redis/mvnw create mode 100644 springboot-redis/mvnw.cmd create mode 100644 springboot-redis/pom.xml create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java create mode 100644 springboot-redis/src/main/resources/application.properties create mode 100644 springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java diff --git a/springboot-redis-message/pom.xml b/springboot-redis-message/pom.xml index 9c707d1..3793add 100755 --- a/springboot-redis-message/pom.xml +++ b/springboot-redis-message/pom.xml @@ -4,11 +4,11 @@ 4.0.0 com.forezp - springboot-redis + springboot-redis-message 0.0.1-SNAPSHOT jar - springboot-redis + springboot-redis-message Demo project for Spring Boot diff --git a/springboot-redis-message/src/main/java/com/forezp/dao/RedisDao.java b/springboot-redis-message/src/main/java/com/forezp/dao/RedisDao.java index eea096b..4bc80ad 100755 --- a/springboot-redis-message/src/main/java/com/forezp/dao/RedisDao.java +++ b/springboot-redis-message/src/main/java/com/forezp/dao/RedisDao.java @@ -1,10 +1,10 @@ package com.forezp.dao; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Repository; +import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** @@ -13,12 +13,13 @@ import java.util.concurrent.TimeUnit; @Repository public class RedisDao { - @Autowired + @Resource private StringRedisTemplate template; public void setKey(String key,String value){ ValueOperations ops = template.opsForValue(); - ops.set(key,value,1, TimeUnit.MINUTES);//1分钟过期 + //1分钟过期 + ops.set(key,value,1, TimeUnit.MINUTES); } public String getValue(String key){ diff --git a/springboot-redis-message/src/test/java/com/forezp/SpringbootRedisApplicationTests.java b/springboot-redis-message/src/test/java/com/forezp/SpringbootRedisApplicationTests.java index 8b14870..bbca0c9 100755 --- a/springboot-redis-message/src/test/java/com/forezp/SpringbootRedisApplicationTests.java +++ b/springboot-redis-message/src/test/java/com/forezp/SpringbootRedisApplicationTests.java @@ -5,10 +5,11 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import javax.annotation.Resource; + @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootRedisApplicationTests { @@ -18,8 +19,8 @@ public class SpringbootRedisApplicationTests { public void contextLoads() { } - @Autowired - RedisDao redisDao; + @Resource + private RedisDao redisDao; @Test public void testRedis(){ redisDao.setKey("name","forezp"); diff --git a/springboot-redis/.gitignore b/springboot-redis/.gitignore new file mode 100644 index 0000000..7bd258a --- /dev/null +++ b/springboot-redis/.gitignore @@ -0,0 +1,32 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ +.mvn \ No newline at end of file diff --git a/springboot-redis/mvnw b/springboot-redis/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/springboot-redis/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-redis/mvnw.cmd b/springboot-redis/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-redis/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-redis/pom.xml b/springboot-redis/pom.xml new file mode 100644 index 0000000..45250a2 --- /dev/null +++ b/springboot-redis/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-redis + 0.0.1-SNAPSHOT + springboot-redis + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.alibaba + fastjson + 1.2.62 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java b/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java new file mode 100644 index 0000000..c76ab5c --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java @@ -0,0 +1,13 @@ +package com.example.springbootredis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootRedisApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootRedisApplication.class, args); + } + +} diff --git a/springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java b/springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java new file mode 100644 index 0000000..6493261 --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java @@ -0,0 +1,24 @@ +package com.example.springbootredis.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import javax.annotation.Resource; + +@Configuration +public class RedisConfig{ + @Resource + private RedisTemplate redisTemplate; + + @Autowired(required = false) + public void setRedisTemplate(RedisTemplate redisTemplate) { + StringRedisSerializer stringSerializer = new StringRedisSerializer(); + redisTemplate.setKeySerializer(stringSerializer); + redisTemplate.setValueSerializer(stringSerializer); + redisTemplate.setHashKeySerializer(stringSerializer); + redisTemplate.setHashValueSerializer(stringSerializer); + this.redisTemplate = redisTemplate; + } +} diff --git a/springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java b/springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java new file mode 100644 index 0000000..53137f9 --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java @@ -0,0 +1,18 @@ +package com.example.springbootredis.entity; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class Days implements Serializable { + private static final long serialVersionUID = -5625743904227623649L; + private String openId; + private String daysId; + // 每天的标题 + private String title; + // 代办事项的数量 + private int itemNumber; + //日程 + private String date; +} diff --git a/springboot-redis/src/main/resources/application.properties b/springboot-redis/src/main/resources/application.properties new file mode 100644 index 0000000..5193cd6 --- /dev/null +++ b/springboot-redis/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.redis.host=localhost +spring.redis.port=6379 +spring.redis.password= +spring.redis.database=0 \ No newline at end of file diff --git a/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java b/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java new file mode 100644 index 0000000..26fdd63 --- /dev/null +++ b/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java @@ -0,0 +1,38 @@ +package com.example.springbootredis; + +import com.alibaba.fastjson.JSONObject; +import com.example.springbootredis.entity.Days; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.RedisTemplate; + +@SpringBootTest +class SpringbootRedisApplicationTests { + + @Test + void contextLoads() { + + } + + @Autowired + private RedisTemplate redisTemplate; + @Test + public void testString(){ + redisTemplate.opsForValue().set("myKey","myValue"); + System.out.println(redisTemplate.opsForValue().get("myKey")); + } + + @Test + public void testObject(){ + Days days = new Days(); + days.setDate("123"); + days.setDaysId("456"); + days.setItemNumber(123); + days.setOpenId("dawda"); + days.setTitle("title"); + this.redisTemplate.opsForValue().set("days", JSONObject.toJSONString(days)); + System.out.println((redisTemplate.opsForValue().get("days"))); + } + +} -- Gitee From 08d589cc9c13e42819f5de183cf84031ef5fe0f7 Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 22:19:14 +0800 Subject: [PATCH 05/49] update README.md. --- README.md | 31 ++----------------------------- 1 file changed, 2 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 02aa14c..039e604 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,5 @@ ->转载请标明出处: -> 原文首发于:https://www.fangzhipeng.com/spring-boot.html -> -> 本文出自[方志朋的博客](https://www.fangzhipeng.com) -> - -#### 获取SpringCloud 、Spring Boot视频:https://www.fangzhipeng.com/share/2017/10/01/resource-sharing.html - -
-

- -
- 扫一扫,支持下作者吧 -

-

- (转载本站文章请注明作者和出处 方志朋的博客 -

-
+项目结构: +springboot-redis:自己搭建的springboot整合redis,为知笔记内链: @@ -104,17 +88,6 @@ ## 未完结 * 待续。。。 -
-

- -
- 扫码关注有惊喜 -

-

- (转载本站文章请注明作者和出处 方志朋的博客 -

-
- -- Gitee From f15849b22b7d4b32fa077d0b350287c2b507bcec Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 22:20:18 +0800 Subject: [PATCH 06/49] update README.md. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 039e604..b058243 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -项目结构: +# 项目结构: springboot-redis:自己搭建的springboot整合redis,为知笔记内链: -- Gitee From 8a01211f3747d41e3ef8481f057876b2b4779c6d Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 23:43:22 +0800 Subject: [PATCH 07/49] update README.md. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b058243..8b086b8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # 项目结构: springboot-redis:自己搭建的springboot整合redis,为知笔记内链: - +SpringBoot教程2.2.5版本:整合Redis +https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C -- Gitee From 047e82d2916ee87e9ad19908758b345ccbc7e25b Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 23:44:59 +0800 Subject: [PATCH 08/49] update README.md. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8b086b8..41d74e9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # 项目结构: springboot-redis:自己搭建的springboot整合redis,为知笔记内链: + SpringBoot教程2.2.5版本:整合Redis https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C -- Gitee From c0f770c9f6b11430eef751b73cf0f470c2f1976a Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 23:45:56 +0800 Subject: [PATCH 09/49] update README.md. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41d74e9..c683207 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ springboot-redis:自己搭建的springboot整合redis,为知笔记内链: SpringBoot教程2.2.5版本:整合Redis https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C - +SpringBoot教程2.2.5版本:整合Redis # SpringBoot非官方教程 | 终章:文章汇总 -- Gitee From a78d02aa4baff776260e3a3787a7b036db9bde4d Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 18 Mar 2020 23:55:18 +0800 Subject: [PATCH 10/49] =?UTF-8?q?=E4=BF=AE=E6=94=B9readme=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index c683207..7e02f49 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,14 @@ -# 项目结构: -springboot-redis:自己搭建的springboot整合redis,为知笔记内链: - -SpringBoot教程2.2.5版本:整合Redis +#SpringBoot2.2.5版本 +##SpringBoot教程2.2.5版本:整合Redis(springboot-redis) https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C -SpringBoot教程2.2.5版本:整合Redis - # SpringBoot非官方教程 | 终章:文章汇总 - springboot非官方教程,可能最接近于官方的一个教程,大多数案例都来自于官方文档,为了更好的理解,加入了个人的改造。 +springboot非官方教程,可能最接近于官方的一个教程,大多数案例都来自于官方文档,为了更好的理解,加入了个人的改造。 码云下载:[https://git.oschina.net/forezp/SpringBootLearning](https://git.oschina.net/forezp/SpringBootLearning) - 源码下载:[https://github.com/forezp/SpringBootLearning](https://github.com/forezp/SpringBootLearning),谢谢支持,记得star哦。 - - +源码下载:[https://github.com/forezp/SpringBootLearning](https://github.com/forezp/SpringBootLearning),谢谢支持,记得star哦。 欢迎访问我的个人博客:https://www.fangzhipeng.com/springboot/2017/07/11/springboot-all/ -- Gitee From 6c4e94df5b8c8fa0e5f6f54e8ccdf01f30b140a8 Mon Sep 17 00:00:00 2001 From: yanghaojie002 <13486032976@163.com> Date: Wed, 18 Mar 2020 23:56:25 +0800 Subject: [PATCH 11/49] update README.md. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7e02f49..710dd0e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ #SpringBoot2.2.5版本 + ##SpringBoot教程2.2.5版本:整合Redis(springboot-redis) https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C -- Gitee From e5ca83f7dd0fca20648a8ff649934b05f6fb4e57 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 18 Mar 2020 23:57:43 +0800 Subject: [PATCH 12/49] =?UTF-8?q?=E6=9B=B4=E6=96=B0readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 710dd0e..490e20a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ -#SpringBoot2.2.5版本 - -##SpringBoot教程2.2.5版本:整合Redis(springboot-redis) +# SpringBoot2.2.5版本 +## SpringBoot教程2.2.5版本:整合Redis(springboot-redis) https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C # SpringBoot非官方教程 | 终章:文章汇总 -- Gitee From bb2f9a16933e1bede813cdc6d85bf22497420222 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 19 Mar 2020 00:41:52 +0800 Subject: [PATCH 13/49] =?UTF-8?q?=E4=BD=BF=E7=94=A8RedisTemplate=E9=9B=86?= =?UTF-8?q?=E6=88=90=20Redis=20=E4=BD=BF=E7=94=A8=20Spring=20Cache=20?= =?UTF-8?q?=E9=9B=86=E6=88=90=20Redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-redis/pom.xml | 5 ++ .../SpringbootRedisApplication.java | 2 + .../controller/UserController.java | 56 +++++++++++++++++++ .../example/springbootredis/entity/User.java | 18 ++++++ .../springbootredis/service/UserService.java | 11 ++++ .../service/UserServiceImpl.java | 47 ++++++++++++++++ .../SpringbootRedisApplicationTests.java | 9 +-- 7 files changed, 142 insertions(+), 6 deletions(-) create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/entity/User.java create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java create mode 100644 springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java diff --git a/springboot-redis/pom.xml b/springboot-redis/pom.xml index 45250a2..37c2a7b 100644 --- a/springboot-redis/pom.xml +++ b/springboot-redis/pom.xml @@ -36,6 +36,11 @@ test + + org.springframework.boot + spring-boot-starter-web + + com.alibaba fastjson diff --git a/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java b/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java index c76ab5c..13b7125 100644 --- a/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java +++ b/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java @@ -2,8 +2,10 @@ package com.example.springbootredis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication +@EnableCaching public class SpringbootRedisApplication { public static void main(String[] args) { diff --git a/springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java b/springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java new file mode 100644 index 0000000..cc61764 --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java @@ -0,0 +1,56 @@ +package com.example.springbootredis.controller; + +import com.alibaba.fastjson.JSONObject; +import com.example.springbootredis.entity.User; +import com.example.springbootredis.service.UserService; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/user") +public class UserController { + + public static Logger logger = LogManager.getLogger(UserController.class); + + @Resource + private RedisTemplate redisCacheTemplate; + + @Resource + private UserService userService; + + @RequestMapping("/test") + public Object test() { + redisCacheTemplate.opsForValue().set("userkey", JSONObject.toJSONString(new User(1, "张三", 25))); + Object user = redisCacheTemplate.opsForValue().get("userkey"); + logger.info("当前获取对象:{}", user); + return user; + } + + @RequestMapping("/add") + public void add() { + User user = userService.save(new User(4, "李现", 30)); + logger.info("添加的用户信息:{}",user.toString()); + } + + @RequestMapping("/delete") + public void delete() { + userService.delete(4); + } + + @RequestMapping("/get/{id}") + public void get(@PathVariable("id") String idStr) throws Exception{ + if (StringUtils.isEmpty(idStr)) { + throw new Exception("id为空"); + } + Integer id = Integer.parseInt(idStr); + User user = userService.get(id); + logger.info("获取的用户信息:{}",user.toString()); + } +} \ No newline at end of file diff --git a/springboot-redis/src/main/java/com/example/springbootredis/entity/User.java b/springboot-redis/src/main/java/com/example/springbootredis/entity/User.java new file mode 100644 index 0000000..5c980ed --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/entity/User.java @@ -0,0 +1,18 @@ +package com.example.springbootredis.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +public class User implements Serializable { + private static final long serialVersionUID = 966312196259333201L; + private Integer id; + + private String name; + + private Integer age; + +} diff --git a/springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java b/springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java new file mode 100644 index 0000000..1a93225 --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java @@ -0,0 +1,11 @@ +package com.example.springbootredis.service; + +import com.example.springbootredis.entity.User; + +public interface UserService { + User save(User user); + + void delete(int id); + + User get(Integer id); +} diff --git a/springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java b/springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java new file mode 100644 index 0000000..5ef608c --- /dev/null +++ b/springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java @@ -0,0 +1,47 @@ +package com.example.springbootredis.service; + +import com.example.springbootredis.entity.User; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +@Service +public class UserServiceImpl implements UserService { + public static Logger logger = LogManager.getLogger(UserServiceImpl.class); + + private static Map userMap = new HashMap<>(); + static { + userMap.put(1, new User(1, "肖战", 25)); + userMap.put(2, new User(2, "王一博", 26)); + userMap.put(3, new User(3, "杨紫", 24)); + } + + + @CachePut(value ="user", key = "#user.id") + @Override + public User save(User user) { + userMap.put(user.getId(), user); + logger.info("进入save方法,当前存储对象:{}", user.toString()); + return user; + } + + @CacheEvict(value="user", key = "#id") + @Override + public void delete(int id) { + userMap.remove(id); + logger.info("进入delete方法,删除成功"); + } + + @Cacheable(value = "user", key = "#id") + @Override + public User get(Integer id) { + logger.info("进入get方法,当前获取对象:{}", userMap.get(id)==null?null:userMap.get(id).toString()); + return userMap.get(id); + } +} diff --git a/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java b/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java index 26fdd63..3334881 100644 --- a/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java +++ b/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java @@ -7,14 +7,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; +import java.util.concurrent.TimeUnit; + @SpringBootTest class SpringbootRedisApplicationTests { - @Test - void contextLoads() { - - } - @Autowired private RedisTemplate redisTemplate; @Test @@ -31,7 +28,7 @@ class SpringbootRedisApplicationTests { days.setItemNumber(123); days.setOpenId("dawda"); days.setTitle("title"); - this.redisTemplate.opsForValue().set("days", JSONObject.toJSONString(days)); + redisTemplate.opsForValue().set("days", JSONObject.toJSONString(days),60,TimeUnit.SECONDS); System.out.println((redisTemplate.opsForValue().get("days"))); } -- Gitee From 621e4a6cfbdbd564372617d6e57cc595ea540ea8 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 19 Mar 2020 12:40:03 +0800 Subject: [PATCH 14/49] =?UTF-8?q?=E4=BC=98=E5=8C=96springboot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC-=E6=95=B4=E5=90=88redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-redis/.gitignore | 32 ++ springboot-225-redis/mvnw | 310 ++++++++++++++++++ springboot-225-redis/mvnw.cmd | 182 ++++++++++ .../pom.xml | 4 +- .../SpringbootRedisApplication.java | 0 .../springbootredis/config/RedisConfig.java | 0 .../controller/UserController.java | 0 .../example/springbootredis/entity/Days.java | 0 .../example/springbootredis/entity/User.java | 0 .../springbootredis/service/UserService.java | 1 + .../service/UserServiceImpl.java | 0 .../src/main/resources/application.properties | 0 .../SpringbootRedisApplicationTests.java | 0 13 files changed, 527 insertions(+), 2 deletions(-) create mode 100644 springboot-225-redis/.gitignore create mode 100644 springboot-225-redis/mvnw create mode 100644 springboot-225-redis/mvnw.cmd rename {springboot-redis => springboot-225-redis}/pom.xml (95%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/config/RedisConfig.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/controller/UserController.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/entity/Days.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/entity/User.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/service/UserService.java (99%) rename {springboot-redis => springboot-225-redis}/src/main/java/com/example/springbootredis/service/UserServiceImpl.java (100%) rename {springboot-redis => springboot-225-redis}/src/main/resources/application.properties (100%) rename {springboot-redis => springboot-225-redis}/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java (100%) diff --git a/springboot-225-redis/.gitignore b/springboot-225-redis/.gitignore new file mode 100644 index 0000000..7bd258a --- /dev/null +++ b/springboot-225-redis/.gitignore @@ -0,0 +1,32 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ +.mvn \ No newline at end of file diff --git a/springboot-225-redis/mvnw b/springboot-225-redis/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/springboot-225-redis/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-redis/mvnw.cmd b/springboot-225-redis/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-redis/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-redis/pom.xml b/springboot-225-redis/pom.xml similarity index 95% rename from springboot-redis/pom.xml rename to springboot-225-redis/pom.xml index 37c2a7b..44b85cb 100644 --- a/springboot-redis/pom.xml +++ b/springboot-225-redis/pom.xml @@ -9,9 +9,9 @@
com.example - springboot-redis + springboot-225-redis 0.0.1-SNAPSHOT - springboot-redis + springboot-225-redis Demo project for Spring Boot diff --git a/springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java b/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java diff --git a/springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java diff --git a/springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/controller/UserController.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java diff --git a/springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/entity/Days.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java diff --git a/springboot-redis/src/main/java/com/example/springbootredis/entity/User.java b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/entity/User.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java diff --git a/springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java similarity index 99% rename from springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java index 1a93225..d32f799 100644 --- a/springboot-redis/src/main/java/com/example/springbootredis/service/UserService.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java @@ -1,5 +1,6 @@ package com.example.springbootredis.service; + import com.example.springbootredis.entity.User; public interface UserService { diff --git a/springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java similarity index 100% rename from springboot-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java rename to springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java diff --git a/springboot-redis/src/main/resources/application.properties b/springboot-225-redis/src/main/resources/application.properties similarity index 100% rename from springboot-redis/src/main/resources/application.properties rename to springboot-225-redis/src/main/resources/application.properties diff --git a/springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java b/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java similarity index 100% rename from springboot-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java rename to springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java -- Gitee From 3304bf7384faefca1ca47f72748ae1785847cf54 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 19 Mar 2020 12:42:59 +0800 Subject: [PATCH 15/49] =?UTF-8?q?=E4=BC=98=E5=8C=96springboot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC-=E6=95=B4=E5=90=88rabbitmq?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.gitignore | 0 .../mvnw | 0 .../mvnw.cmd | 0 springboot-225-rabbitmq/pom.xml | 58 +++++++++++++++++++ .../Springboot225RabbitmqApplication.java | 13 +++++ .../src/main/resources/application.properties | 1 + ...Springboot225RabbitmqApplicationTests.java | 13 +++++ 7 files changed, 85 insertions(+) rename {springboot-redis => springboot-225-rabbitmq}/.gitignore (100%) rename {springboot-redis => springboot-225-rabbitmq}/mvnw (100%) rename {springboot-redis => springboot-225-rabbitmq}/mvnw.cmd (100%) create mode 100644 springboot-225-rabbitmq/pom.xml create mode 100644 springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java create mode 100644 springboot-225-rabbitmq/src/main/resources/application.properties create mode 100644 springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java diff --git a/springboot-redis/.gitignore b/springboot-225-rabbitmq/.gitignore similarity index 100% rename from springboot-redis/.gitignore rename to springboot-225-rabbitmq/.gitignore diff --git a/springboot-redis/mvnw b/springboot-225-rabbitmq/mvnw similarity index 100% rename from springboot-redis/mvnw rename to springboot-225-rabbitmq/mvnw diff --git a/springboot-redis/mvnw.cmd b/springboot-225-rabbitmq/mvnw.cmd similarity index 100% rename from springboot-redis/mvnw.cmd rename to springboot-225-rabbitmq/mvnw.cmd diff --git a/springboot-225-rabbitmq/pom.xml b/springboot-225-rabbitmq/pom.xml new file mode 100644 index 0000000..00c7b8a --- /dev/null +++ b/springboot-225-rabbitmq/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-rabbitmq + 0.0.1-SNAPSHOT + springboot-225-rabbitmq + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.amqp + spring-rabbit-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java b/springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java new file mode 100644 index 0000000..8c7d058 --- /dev/null +++ b/springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmq; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225RabbitmqApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225RabbitmqApplication.class, args); + } + +} diff --git a/springboot-225-rabbitmq/src/main/resources/application.properties b/springboot-225-rabbitmq/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/springboot-225-rabbitmq/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java b/springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java new file mode 100644 index 0000000..f7e64af --- /dev/null +++ b/springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmq; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225RabbitmqApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 61bb491726810ff333278541584069193370eae4 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 19 Mar 2020 14:10:25 +0800 Subject: [PATCH 16/49] =?UTF-8?q?=E4=BC=98=E5=8C=96springboot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC-=E6=95=B4=E5=90=88rabbitmq?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/uiDesigner.xml | 124 +++++++ springboot-225-rabbitmq-consumer/.gitignore | 31 ++ .../.mvn/wrapper/MavenWrapperDownloader.java | 115 +++++++ .../.mvn/wrapper/maven-wrapper.jar | Bin 0 -> 50710 bytes .../.mvn/wrapper/maven-wrapper.properties | 2 + springboot-225-rabbitmq-consumer/mvnw | 322 ++++++++++++++++++ .../mvnw.cmd | 0 springboot-225-rabbitmq-consumer/pom.xml | 63 ++++ .../DirectReceiver.java | 18 + ...ingboot225RabbitmqConsumerApplication.java | 13 + .../config/DirectRabbitConfig.java | 33 ++ .../src/main/resources/application.yml | 14 + ...ot225RabbitmqConsumerApplicationTests.java | 13 + .../.gitignore | 0 .../mvnw | 0 springboot-225-rabbitmq-provider/mvnw.cmd | 182 ++++++++++ .../pom.xml | 4 +- ...ingboot225RabbitmqProviderApplication.java | 4 +- .../config/DirectRabbitConfig.java | 33 ++ .../controller/SendMessageController.java | 35 ++ .../src/main/resources/application.yml | 14 + ...ot225RabbitmqProviderApplicationTests.java | 2 +- .../src/main/resources/application.properties | 1 - 23 files changed, 1017 insertions(+), 6 deletions(-) create mode 100644 .idea/uiDesigner.xml create mode 100644 springboot-225-rabbitmq-consumer/.gitignore create mode 100644 springboot-225-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.jar create mode 100644 springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.properties create mode 100644 springboot-225-rabbitmq-consumer/mvnw rename {springboot-225-rabbitmq => springboot-225-rabbitmq-consumer}/mvnw.cmd (100%) create mode 100644 springboot-225-rabbitmq-consumer/pom.xml create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplication.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/DirectRabbitConfig.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/resources/application.yml create mode 100644 springboot-225-rabbitmq-consumer/src/test/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplicationTests.java rename {springboot-225-rabbitmq => springboot-225-rabbitmq-provider}/.gitignore (100%) rename {springboot-225-rabbitmq => springboot-225-rabbitmq-provider}/mvnw (100%) create mode 100644 springboot-225-rabbitmq-provider/mvnw.cmd rename {springboot-225-rabbitmq => springboot-225-rabbitmq-provider}/pom.xml (94%) rename springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java => springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java (63%) create mode 100644 springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/DirectRabbitConfig.java create mode 100644 springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java create mode 100644 springboot-225-rabbitmq-provider/src/main/resources/application.yml rename springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java => springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java (78%) delete mode 100644 springboot-225-rabbitmq/src/main/resources/application.properties diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/.gitignore b/springboot-225-rabbitmq-consumer/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java b/springboot-225-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..d6d1381 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,115 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.jar b/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..2cc7d4a55c0cd0092912bf49ae38b3a9e3fd0054 GIT binary patch literal 50710 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 EfAhh=DF6Tf literal 0 HcmV?d00001 diff --git a/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.properties b/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/springboot-225-rabbitmq-consumer/mvnw b/springboot-225-rabbitmq-consumer/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-rabbitmq/mvnw.cmd b/springboot-225-rabbitmq-consumer/mvnw.cmd similarity index 100% rename from springboot-225-rabbitmq/mvnw.cmd rename to springboot-225-rabbitmq-consumer/mvnw.cmd diff --git a/springboot-225-rabbitmq-consumer/pom.xml b/springboot-225-rabbitmq-consumer/pom.xml new file mode 100644 index 0000000..e25f0b7 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-rabbitmq-consumer + 0.0.1-SNAPSHOT + springboot-225-rabbitmq-consumer + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.amqp + spring-rabbit-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java new file mode 100644 index 0000000..10ba069 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java @@ -0,0 +1,18 @@ +package com.example.springboot225rabbitmqconsumer; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "TestDirectQueue")//监听的队列名称 TestDirectQueue +public class DirectReceiver { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("DirectReceiver消费者收到消息 : " + testMessage.toString()); + } + +} diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplication.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplication.java new file mode 100644 index 0000000..dc294fe --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmqconsumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225RabbitmqConsumerApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225RabbitmqConsumerApplication.class, args); + } + +} diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/DirectRabbitConfig.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/DirectRabbitConfig.java new file mode 100644 index 0000000..6de4990 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/DirectRabbitConfig.java @@ -0,0 +1,33 @@ +package com.example.springboot225rabbitmqconsumer.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 直连型交换机 + */ +@Configuration +public class DirectRabbitConfig { + + //队列 起名:TestDirectQueue + @Bean + public Queue TestDirectQueue() { + return new Queue("TestDirectQueue",true); //true 是否持久 + } + + //Direct交换机 起名:TestDirectExchange + @Bean + DirectExchange TestDirectExchange() { + return new DirectExchange("TestDirectExchange"); + } + + //绑定 将队列和交换机绑定, 并设置用于匹配键:TestDirectRouting + @Bean + Binding bindingDirect() { + return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting"); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/resources/application.yml b/springboot-225-rabbitmq-consumer/src/main/resources/application.yml new file mode 100644 index 0000000..582c219 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/resources/application.yml @@ -0,0 +1,14 @@ +server: + port: 8022 +spring: + #给项目来个名字 + application: + name: rabbitmq-consumer + #配置rabbitMq 服务器 + rabbitmq: + host: 127.0.0.1 + port: 5672 + username: guest + password: guest + #虚拟host 可以不设置,使用server默认host + virtual-host: / \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/test/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplicationTests.java b/springboot-225-rabbitmq-consumer/src/test/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplicationTests.java new file mode 100644 index 0000000..5141515 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/test/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmqconsumer; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225RabbitmqConsumerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-225-rabbitmq/.gitignore b/springboot-225-rabbitmq-provider/.gitignore similarity index 100% rename from springboot-225-rabbitmq/.gitignore rename to springboot-225-rabbitmq-provider/.gitignore diff --git a/springboot-225-rabbitmq/mvnw b/springboot-225-rabbitmq-provider/mvnw similarity index 100% rename from springboot-225-rabbitmq/mvnw rename to springboot-225-rabbitmq-provider/mvnw diff --git a/springboot-225-rabbitmq-provider/mvnw.cmd b/springboot-225-rabbitmq-provider/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-rabbitmq-provider/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-225-rabbitmq/pom.xml b/springboot-225-rabbitmq-provider/pom.xml similarity index 94% rename from springboot-225-rabbitmq/pom.xml rename to springboot-225-rabbitmq-provider/pom.xml index 00c7b8a..9319a00 100644 --- a/springboot-225-rabbitmq/pom.xml +++ b/springboot-225-rabbitmq-provider/pom.xml @@ -9,9 +9,9 @@ com.example - springboot-225-rabbitmq + springboot-225-rabbitmq-provider 0.0.1-SNAPSHOT - springboot-225-rabbitmq + springboot-225-rabbitmq-provider Demo project for Spring Boot diff --git a/springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java similarity index 63% rename from springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java rename to springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java index 8c7d058..8523e86 100644 --- a/springboot-225-rabbitmq/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplication.java +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java @@ -4,10 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class Springboot225RabbitmqApplication { +public class Springboot225RabbitmqProviderApplication { public static void main(String[] args) { - SpringApplication.run(Springboot225RabbitmqApplication.class, args); + SpringApplication.run(Springboot225RabbitmqProviderApplication.class, args); } } diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/DirectRabbitConfig.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/DirectRabbitConfig.java new file mode 100644 index 0000000..fede519 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/DirectRabbitConfig.java @@ -0,0 +1,33 @@ +package com.example.springboot225rabbitmq.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 直连型交换机 + */ +@Configuration +public class DirectRabbitConfig { + + //队列 起名:TestDirectQueue + @Bean + public Queue TestDirectQueue() { + return new Queue("TestDirectQueue",true); //true 是否持久 + } + + //Direct交换机 起名:TestDirectExchange + @Bean + DirectExchange TestDirectExchange() { + return new DirectExchange("TestDirectExchange"); + } + + //绑定 将队列和交换机绑定, 并设置用于匹配键:TestDirectRouting + @Bean + Binding bindingDirect() { + return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting"); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java new file mode 100644 index 0000000..741fe50 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java @@ -0,0 +1,35 @@ +package com.example.springboot225rabbitmq.controller; + +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@RestController +public class SendMessageController { + + @Autowired + RabbitTemplate rabbitTemplate; //使用RabbitTemplate,这提供了接收/发送等等方法 + + @GetMapping("/sendDirectMessage") + public String sendDirectMessage() { + String messageId = String.valueOf(UUID.randomUUID()); + String messageData = "test message, hello!"; + String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Map map=new HashMap<>(); + map.put("messageId",messageId); + map.put("messageData",messageData); + map.put("createTime",createTime); + //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange + rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map); + return "ok"; + } + + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/resources/application.yml b/springboot-225-rabbitmq-provider/src/main/resources/application.yml new file mode 100644 index 0000000..ef044b6 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/resources/application.yml @@ -0,0 +1,14 @@ +server: + port: 8021 +spring: + #给项目来个名字 + application: + name: rabbitmq-provider + #配置rabbitMq 服务器 + rabbitmq: + host: 127.0.0.1 + port: 5672 + username: guest + password: guest + #虚拟host 可以不设置,使用server默认host + virtual-host: / \ No newline at end of file diff --git a/springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java b/springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java similarity index 78% rename from springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java rename to springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java index f7e64af..1ce3402 100644 --- a/springboot-225-rabbitmq/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqApplicationTests.java +++ b/springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class Springboot225RabbitmqApplicationTests { +class Springboot225RabbitmqProviderApplicationTests { @Test void contextLoads() { diff --git a/springboot-225-rabbitmq/src/main/resources/application.properties b/springboot-225-rabbitmq/src/main/resources/application.properties deleted file mode 100644 index 8b13789..0000000 --- a/springboot-225-rabbitmq/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - -- Gitee From 25dc1525992d5f21c920fe8b6e1380ff53d8ca19 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 19 Mar 2020 16:16:25 +0800 Subject: [PATCH 17/49] =?UTF-8?q?=E4=BC=98=E5=8C=96springboot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC-=E6=95=B4=E5=90=88rabbitmq?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/FanoutRabbitConfig.java | 58 +++++++++++++++++++ .../config/TopicRabbitConfig.java | 49 ++++++++++++++++ .../{ => receiver}/DirectReceiver.java | 2 +- .../receiver/FanoutReceiverA.java | 18 ++++++ .../receiver/FanoutReceiverB.java | 18 ++++++ .../receiver/FanoutReceiverC.java | 18 ++++++ .../receiver/TopicManReceiver.java | 17 ++++++ .../receiver/TopicTotalReceiver.java | 17 ++++++ .../config/FanoutRabbitConfig.java | 57 ++++++++++++++++++ .../config/RabbitConfig.java | 43 ++++++++++++++ .../config/TopicRabbitConfig.java | 49 ++++++++++++++++ .../controller/SendMessageController.java | 51 ++++++++++++++++ .../src/main/resources/application.yml | 8 ++- 13 files changed, 403 insertions(+), 2 deletions(-) create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/FanoutRabbitConfig.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/TopicRabbitConfig.java rename springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/{ => receiver}/DirectReceiver.java (89%) create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverA.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverB.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverC.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicManReceiver.java create mode 100644 springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicTotalReceiver.java create mode 100644 springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/FanoutRabbitConfig.java create mode 100644 springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/RabbitConfig.java create mode 100644 springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/TopicRabbitConfig.java diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/FanoutRabbitConfig.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/FanoutRabbitConfig.java new file mode 100644 index 0000000..a5b172d --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/FanoutRabbitConfig.java @@ -0,0 +1,58 @@ +package com.example.springboot225rabbitmqconsumer.config; + + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 扇形交换机 + */ +@Configuration +public class FanoutRabbitConfig { + + /** + * 创建三个队列 :fanout.A fanout.B fanout.C + * 将三个队列都绑定在交换机 fanoutExchange 上 + * 因为是扇型交换机, 路由键无需配置,配置也不起作用 + */ + + + @Bean + public Queue queueA() { + return new Queue("fanout.A"); + } + + @Bean + public Queue queueB() { + return new Queue("fanout.B"); + } + + @Bean + public Queue queueC() { + return new Queue("fanout.C"); + } + + @Bean + FanoutExchange fanoutExchange() { + return new FanoutExchange("fanoutExchange"); + } + + @Bean + Binding bindingExchangeA() { + return BindingBuilder.bind(queueA()).to(fanoutExchange()); + } + + @Bean + Binding bindingExchangeB() { + return BindingBuilder.bind(queueB()).to(fanoutExchange()); + } + + @Bean + Binding bindingExchangeC() { + return BindingBuilder.bind(queueC()).to(fanoutExchange()); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/TopicRabbitConfig.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/TopicRabbitConfig.java new file mode 100644 index 0000000..a8c11f2 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/config/TopicRabbitConfig.java @@ -0,0 +1,49 @@ +package com.example.springboot225rabbitmqconsumer.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.TopicExchange; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 主题交换机 + */ +@Configuration +public class TopicRabbitConfig { + //绑定键 + public final static String man = "topic.man"; + public final static String woman = "topic.woman"; + + @Bean + public Queue firstQueue() { + return new Queue(TopicRabbitConfig.man); + } + + @Bean + public Queue secondQueue() { + return new Queue(TopicRabbitConfig.woman); + } + + @Bean + TopicExchange exchange() { + return new TopicExchange("topicExchange"); + } + + + //将firstQueue和topicExchange绑定,而且绑定的键值为topic.man + //这样只要是消息携带的路由键是topic.man,才会分发到该队列 + @Bean + Binding bindingExchangeMessage() { + return BindingBuilder.bind(firstQueue()).to(exchange()).with(man); + } + + //将secondQueue和topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.# + // 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列 + @Bean + Binding bindingExchangeMessage2() { + return BindingBuilder.bind(secondQueue()).to(exchange()).with("topic.#"); + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/DirectReceiver.java similarity index 89% rename from springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java rename to springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/DirectReceiver.java index 10ba069..bbc7ce0 100644 --- a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/DirectReceiver.java +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/DirectReceiver.java @@ -1,4 +1,4 @@ -package com.example.springboot225rabbitmqconsumer; +package com.example.springboot225rabbitmqconsumer.receiver; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverA.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverA.java new file mode 100644 index 0000000..ff8d822 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverA.java @@ -0,0 +1,18 @@ +package com.example.springboot225rabbitmqconsumer.receiver; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "fanout.A") +public class FanoutReceiverA { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("FanoutReceiverA消费者收到消息 : " +testMessage.toString()); + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverB.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverB.java new file mode 100644 index 0000000..1151663 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverB.java @@ -0,0 +1,18 @@ +package com.example.springboot225rabbitmqconsumer.receiver; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "fanout.B") +public class FanoutReceiverB { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("FanoutReceiverB消费者收到消息 : " +testMessage.toString()); + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverC.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverC.java new file mode 100644 index 0000000..e3f788f --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverC.java @@ -0,0 +1,18 @@ +package com.example.springboot225rabbitmqconsumer.receiver; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "fanout.C") +public class FanoutReceiverC { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("FanoutReceiverC消费者收到消息 : " +testMessage.toString()); + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicManReceiver.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicManReceiver.java new file mode 100644 index 0000000..9ef3e77 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicManReceiver.java @@ -0,0 +1,17 @@ +package com.example.springboot225rabbitmqconsumer.receiver; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "topic.man") +public class TopicManReceiver { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("TopicManReceiver消费者收到消息 : " + testMessage.toString()); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicTotalReceiver.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicTotalReceiver.java new file mode 100644 index 0000000..9181887 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/TopicTotalReceiver.java @@ -0,0 +1,17 @@ +package com.example.springboot225rabbitmqconsumer.receiver; + +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@RabbitListener(queues = "topic.woman") +public class TopicTotalReceiver { + + @RabbitHandler + public void process(Map testMessage) { + System.out.println("TopicTotalReceiver消费者收到消息 : " + testMessage.toString()); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/FanoutRabbitConfig.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/FanoutRabbitConfig.java new file mode 100644 index 0000000..3ec3b97 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/FanoutRabbitConfig.java @@ -0,0 +1,57 @@ +package com.example.springboot225rabbitmq.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 扇形交换机 + */ +@Configuration +public class FanoutRabbitConfig { + + /** + * 创建三个队列 :fanout.A fanout.B fanout.C + * 将三个队列都绑定在交换机 fanoutExchange 上 + * 因为是扇型交换机, 路由键无需配置,配置也不起作用 + */ + + + @Bean + public Queue queueA() { + return new Queue("fanout.A"); + } + + @Bean + public Queue queueB() { + return new Queue("fanout.B"); + } + + @Bean + public Queue queueC() { + return new Queue("fanout.C"); + } + + @Bean + FanoutExchange fanoutExchange() { + return new FanoutExchange("fanoutExchange"); + } + + @Bean + Binding bindingExchangeA() { + return BindingBuilder.bind(queueA()).to(fanoutExchange()); + } + + @Bean + Binding bindingExchangeB() { + return BindingBuilder.bind(queueB()).to(fanoutExchange()); + } + + @Bean + Binding bindingExchangeC() { + return BindingBuilder.bind(queueC()).to(fanoutExchange()); + } +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/RabbitConfig.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/RabbitConfig.java new file mode 100644 index 0000000..c90d0fa --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/RabbitConfig.java @@ -0,0 +1,43 @@ +package com.example.springboot225rabbitmq.config; + +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.connection.CorrelationData; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitConfig { + + @Bean + public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){ + RabbitTemplate rabbitTemplate = new RabbitTemplate(); + rabbitTemplate.setConnectionFactory(connectionFactory); + //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数 + rabbitTemplate.setMandatory(true); + + rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { + @Override + public void confirm(CorrelationData correlationData, boolean ack, String cause) { + System.out.println("ConfirmCallback: "+"相关数据:"+correlationData); + System.out.println("ConfirmCallback: "+"确认情况:"+ack); + System.out.println("ConfirmCallback: "+"原因:"+cause); + } + }); + + rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() { + @Override + public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { + System.out.println("ReturnCallback: "+"消息:"+message); + System.out.println("ReturnCallback: "+"回应码:"+replyCode); + System.out.println("ReturnCallback: "+"回应信息:"+replyText); + System.out.println("ReturnCallback: "+"交换机:"+exchange); + System.out.println("ReturnCallback: "+"路由键:"+routingKey); + } + }); + + return rabbitTemplate; + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/TopicRabbitConfig.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/TopicRabbitConfig.java new file mode 100644 index 0000000..1a496e8 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/TopicRabbitConfig.java @@ -0,0 +1,49 @@ +package com.example.springboot225rabbitmq.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.TopicExchange; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 主题交换机 + */ +@Configuration +public class TopicRabbitConfig { + //绑定键 + public final static String man = "topic.man"; + public final static String woman = "topic.woman"; + + @Bean + public Queue firstQueue() { + return new Queue(TopicRabbitConfig.man); + } + + @Bean + public Queue secondQueue() { + return new Queue(TopicRabbitConfig.woman); + } + + @Bean + TopicExchange exchange() { + return new TopicExchange("topicExchange"); + } + + + //将firstQueue和topicExchange绑定,而且绑定的键值为topic.man + //这样只要是消息携带的路由键是topic.man,才会分发到该队列 + @Bean + Binding bindingExchangeMessage() { + return BindingBuilder.bind(firstQueue()).to(exchange()).with(man); + } + + //将secondQueue和topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.# + // 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列 + @Bean + Binding bindingExchangeMessage2() { + return BindingBuilder.bind(secondQueue()).to(exchange()).with("topic.#"); + } + +} \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java index 741fe50..e3100b7 100644 --- a/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java @@ -31,5 +31,56 @@ public class SendMessageController { return "ok"; } + @GetMapping("/sendTopicMessage1") + public String sendTopicMessage1() { + String messageId = String.valueOf(UUID.randomUUID()); + String messageData = "message: M A N "; + String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Map manMap = new HashMap<>(); + manMap.put("messageId", messageId); + manMap.put("messageData", messageData); + manMap.put("createTime", createTime); + rabbitTemplate.convertAndSend("topicExchange", "topic.man", manMap); + return "ok"; + } + + @GetMapping("/sendTopicMessage2") + public String sendTopicMessage2() { + String messageId = String.valueOf(UUID.randomUUID()); + String messageData = "message: woman is all "; + String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Map womanMap = new HashMap<>(); + womanMap.put("messageId", messageId); + womanMap.put("messageData", messageData); + womanMap.put("createTime", createTime); + rabbitTemplate.convertAndSend("topicExchange", "topic.woman", womanMap); + return "ok"; + } + + @GetMapping("/sendFanoutMessage") + public String sendFanoutMessage() { + String messageId = String.valueOf(UUID.randomUUID()); + String messageData = "message: testFanoutMessage "; + String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Map map = new HashMap<>(); + map.put("messageId", messageId); + map.put("messageData", messageData); + map.put("createTime", createTime); + rabbitTemplate.convertAndSend("fanoutExchange", null, map); + return "ok"; + } + + @GetMapping("/TestMessageAck") + public String TestMessageAck() { + String messageId = String.valueOf(UUID.randomUUID()); + String messageData = "message: non-existent-exchange test message "; + String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + Map map = new HashMap<>(); + map.put("messageId", messageId); + map.put("messageData", messageData); + map.put("createTime", createTime); + rabbitTemplate.convertAndSend("non-existent-exchange", "TestDirectRouting", map); + return "ok"; + } } \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/main/resources/application.yml b/springboot-225-rabbitmq-provider/src/main/resources/application.yml index ef044b6..c634549 100644 --- a/springboot-225-rabbitmq-provider/src/main/resources/application.yml +++ b/springboot-225-rabbitmq-provider/src/main/resources/application.yml @@ -11,4 +11,10 @@ spring: username: guest password: guest #虚拟host 可以不设置,使用server默认host - virtual-host: / \ No newline at end of file + virtual-host: / + #消息确认配置项 + #确认消息已发送到交换机(Exchange) + publisher-confirms: on +# publisher-confirm-type: simple + #确认消息已发送到队列(Queue) + publisher-returns: on \ No newline at end of file -- Gitee From 0c82063f6b1e042d3bfda9c56b35f98e23faf573 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Fri, 20 Mar 2020 17:04:53 +0800 Subject: [PATCH 18/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88elasticsearch7.x?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-elasticsearch/.gitignore | 31 ++ springboot-225-elasticsearch/HELP.md | 20 ++ springboot-225-elasticsearch/mvnw | 322 ++++++++++++++++++ springboot-225-elasticsearch/mvnw.cmd | 182 ++++++++++ springboot-225-elasticsearch/pom.xml | 58 ++++ ...Springboot225ElasticsearchApplication.java | 13 + .../controller/ElasticController.java | 39 +++ .../dao/ElasticRepository.java | 22 ++ .../entity/DocBean.java | 39 +++ .../service/ElasticServiceImpl.java | 69 ++++ .../service/IElasticService.java | 28 ++ .../src/main/resources/application.yml | 10 + ...gboot225ElasticsearchApplicationTests.java | 13 + 13 files changed, 846 insertions(+) create mode 100644 springboot-225-elasticsearch/.gitignore create mode 100644 springboot-225-elasticsearch/HELP.md create mode 100644 springboot-225-elasticsearch/mvnw create mode 100644 springboot-225-elasticsearch/mvnw.cmd create mode 100644 springboot-225-elasticsearch/pom.xml create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplication.java create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/controller/ElasticController.java create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/dao/ElasticRepository.java create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/entity/DocBean.java create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/ElasticServiceImpl.java create mode 100644 springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/IElasticService.java create mode 100644 springboot-225-elasticsearch/src/main/resources/application.yml create mode 100644 springboot-225-elasticsearch/src/test/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplicationTests.java diff --git a/springboot-225-elasticsearch/.gitignore b/springboot-225-elasticsearch/.gitignore new file mode 100644 index 0000000..0054eae --- /dev/null +++ b/springboot-225-elasticsearch/.gitignore @@ -0,0 +1,31 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ +.mvn \ No newline at end of file diff --git a/springboot-225-elasticsearch/HELP.md b/springboot-225-elasticsearch/HELP.md new file mode 100644 index 0000000..5ee9cc7 --- /dev/null +++ b/springboot-225-elasticsearch/HELP.md @@ -0,0 +1,20 @@ +# Getting Started + +## SpringBoot2.2.5版本:整合elasticsearch7.x +https://note.wiz.cn/web/web?dc=12aecd91-6e6f-4956-9ea1-861dbd1956a2&kb=&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/maven-plugin/) +* [Spring Data Elasticsearch (Access+Driver)](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-elasticsearch) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) + diff --git a/springboot-225-elasticsearch/mvnw b/springboot-225-elasticsearch/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/springboot-225-elasticsearch/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-elasticsearch/mvnw.cmd b/springboot-225-elasticsearch/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-elasticsearch/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-225-elasticsearch/pom.xml b/springboot-225-elasticsearch/pom.xml new file mode 100644 index 0000000..03ab5b0 --- /dev/null +++ b/springboot-225-elasticsearch/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-elasticsearch + 0.0.1-SNAPSHOT + springboot-225-elasticsearch + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-elasticsearch + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplication.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplication.java new file mode 100644 index 0000000..5fff9f1 --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225elasticsearch; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225ElasticsearchApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225ElasticsearchApplication.class, args); + } + +} diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/controller/ElasticController.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/controller/ElasticController.java new file mode 100644 index 0000000..5af86bf --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/controller/ElasticController.java @@ -0,0 +1,39 @@ +package com.example.springboot225elasticsearch.controller; + +import com.example.springboot225elasticsearch.entity.DocBean; +import com.example.springboot225elasticsearch.service.IElasticService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +@Log4j2 +@RestController +@RequestMapping("/elastic") +public class ElasticController { + + @Autowired + private IElasticService elasticService; + + @GetMapping("/init") + public void init(){ + elasticService.createIndex(); + List list =new ArrayList<>(); + list.add(new DocBean(1L,"XX0193","XX8064","xxxxxx",1)); + list.add(new DocBean(2L,"XX0210","XX7475","xxxxxxxxxx",1)); + list.add(new DocBean(3L,"XX0257","XX8097","xxxxxxxxxxxxxxxxxx",1)); + elasticService.saveAll(list); + + } + + @GetMapping("/all") + public Iterator all(){ + return elasticService.findAll(); + } + +} \ No newline at end of file diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/dao/ElasticRepository.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/dao/ElasticRepository.java new file mode 100644 index 0000000..aa87baa --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/dao/ElasticRepository.java @@ -0,0 +1,22 @@ +package com.example.springboot225elasticsearch.dao; + +import com.example.springboot225elasticsearch.entity.DocBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.elasticsearch.annotations.Query; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +public interface ElasticRepository extends ElasticsearchRepository { + + //默认的注释 + //@Query("{\"bool\" : {\"must\" : {\"field\" : {\"content\" : \"?\"}}}}") + Page findByContent(String content, Pageable pageable); + + @Query("{\"bool\" : {\"must\" : {\"field\" : {\"firstCode.keyword\" : \"?\"}}}}") + Page findByFirstCode(String firstCode, Pageable pageable); + + @Query("{\"bool\" : {\"must\" : {\"field\" : {\"secordCode.keyword\" : \"?\"}}}}") + Page findBySecordCode(String secordCode, Pageable pageable); + + +} \ No newline at end of file diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/entity/DocBean.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/entity/DocBean.java new file mode 100644 index 0000000..a900d64 --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/entity/DocBean.java @@ -0,0 +1,39 @@ +package com.example.springboot225elasticsearch.entity; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; + +@Data +@NoArgsConstructor +@Accessors(chain = true) +@Document(indexName = "ems",type = "_doc", shards = 1, replicas = 0) +public class DocBean { + + @Id + private Long id; + + @Field(type = FieldType.Keyword) + private String firstCode; + + @Field(type = FieldType.Keyword) + private String secordCode; + + @Field(type = FieldType.Text, analyzer = "ik_max_word") + private String content; + + @Field(type = FieldType.Integer) + private Integer type; + + public DocBean(Long id,String firstCode,String secordCode,String content,Integer type){ + this.id=id; + this.firstCode=firstCode; + this.secordCode=secordCode; + this.content=content; + this.type=type; + } +} \ No newline at end of file diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/ElasticServiceImpl.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/ElasticServiceImpl.java new file mode 100644 index 0000000..d0aeb8c --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/ElasticServiceImpl.java @@ -0,0 +1,69 @@ +package com.example.springboot225elasticsearch.service; + +import com.example.springboot225elasticsearch.entity.DocBean; +import com.example.springboot225elasticsearch.dao.ElasticRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Iterator; +import java.util.List; + +@Service +public class ElasticServiceImpl implements IElasticService { + + @Resource + private ElasticsearchRestTemplate elasticsearchTemplate; + @Resource + private ElasticRepository elasticRepository; + + private Pageable pageable = PageRequest.of(0,10); + + @Override + public void createIndex() { + elasticsearchTemplate.createIndex(DocBean.class); + } + + @Override + public void deleteIndex(String index) { + elasticsearchTemplate.deleteIndex(index); + } + + @Override + public void save(DocBean docBean) { + elasticRepository.save(docBean); + } + + @Override + public void saveAll(List list) { + elasticRepository.saveAll(list); + } + + @Override + public Iterator findAll() { + return elasticRepository.findAll().iterator(); + } + + @Override + public Page findByContent(String content) { + return elasticRepository.findByContent(content,pageable); + } + + @Override + public Page findByFirstCode(String firstCode) { + return elasticRepository.findByFirstCode(firstCode,pageable); + } + + @Override + public Page findBySecordCode(String secordCode) { + return elasticRepository.findBySecordCode(secordCode,pageable); + } + + @Override + public Page query(String key) { + return elasticRepository.findByContent(key,pageable); + } +} \ No newline at end of file diff --git a/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/IElasticService.java b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/IElasticService.java new file mode 100644 index 0000000..d452153 --- /dev/null +++ b/springboot-225-elasticsearch/src/main/java/com/example/springboot225elasticsearch/service/IElasticService.java @@ -0,0 +1,28 @@ +package com.example.springboot225elasticsearch.service; + +import com.example.springboot225elasticsearch.entity.DocBean; +import org.springframework.data.domain.Page; + +import java.util.Iterator; +import java.util.List; + +public interface IElasticService { + + void createIndex(); + + void deleteIndex(String index); + + void save(DocBean docBean); + + void saveAll(List list); + + Iterator findAll(); + + Page findByContent(String content); + + Page findByFirstCode(String firstCode); + + Page findBySecordCode(String secordCode); + + Page query(String key); +} \ No newline at end of file diff --git a/springboot-225-elasticsearch/src/main/resources/application.yml b/springboot-225-elasticsearch/src/main/resources/application.yml new file mode 100644 index 0000000..eefadb8 --- /dev/null +++ b/springboot-225-elasticsearch/src/main/resources/application.yml @@ -0,0 +1,10 @@ +server: + port: 8080 + servlet: + context-path: /ems +spring: + elasticsearch: + rest: + uris: http://localhost:9200 +# username: elastic +# password: 123456 diff --git a/springboot-225-elasticsearch/src/test/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplicationTests.java b/springboot-225-elasticsearch/src/test/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplicationTests.java new file mode 100644 index 0000000..5f3d6da --- /dev/null +++ b/springboot-225-elasticsearch/src/test/java/com/example/springboot225elasticsearch/Springboot225ElasticsearchApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225elasticsearch; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225ElasticsearchApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 68fb3ea50dc510016601aec2fe7630c2b24df4f7 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Fri, 20 Mar 2020 17:06:54 +0800 Subject: [PATCH 19/49] =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8DREADME?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-elasticsearch/{HELP.md => README.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename springboot-225-elasticsearch/{HELP.md => README.md} (100%) diff --git a/springboot-225-elasticsearch/HELP.md b/springboot-225-elasticsearch/README.md similarity index 100% rename from springboot-225-elasticsearch/HELP.md rename to springboot-225-elasticsearch/README.md -- Gitee From 3222307933d1f503c17270a9bf62c75a8e8c3068 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sat, 21 Mar 2020 00:13:55 +0800 Subject: [PATCH 20/49] =?UTF-8?q?=E4=BF=AE=E6=94=B9README=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-elasticsearch/README.md | 1 - springboot-225-rabbitmq-consumer/.gitignore | 1 - springboot-225-rabbitmq-consumer/README.md | 20 ++++++++++++++++++++ springboot-225-rabbitmq-provider/.gitignore | 1 - springboot-225-rabbitmq-provider/README.md | 20 ++++++++++++++++++++ springboot-225-redis/.gitignore | 1 - springboot-225-redis/README.md | 18 ++++++++++++++++++ 7 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 springboot-225-rabbitmq-consumer/README.md create mode 100644 springboot-225-rabbitmq-provider/README.md create mode 100644 springboot-225-redis/README.md diff --git a/springboot-225-elasticsearch/README.md b/springboot-225-elasticsearch/README.md index 5ee9cc7..abeb30a 100644 --- a/springboot-225-elasticsearch/README.md +++ b/springboot-225-elasticsearch/README.md @@ -1,5 +1,4 @@ # Getting Started - ## SpringBoot2.2.5版本:整合elasticsearch7.x https://note.wiz.cn/web/web?dc=12aecd91-6e6f-4956-9ea1-861dbd1956a2&kb=&cmd=km%2C diff --git a/springboot-225-rabbitmq-consumer/.gitignore b/springboot-225-rabbitmq-consumer/.gitignore index a2a3040..3a568a5 100644 --- a/springboot-225-rabbitmq-consumer/.gitignore +++ b/springboot-225-rabbitmq-consumer/.gitignore @@ -1,4 +1,3 @@ -HELP.md target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** diff --git a/springboot-225-rabbitmq-consumer/README.md b/springboot-225-rabbitmq-consumer/README.md new file mode 100644 index 0000000..5eb7492 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/README.md @@ -0,0 +1,20 @@ +# Getting Started +## SpringBoot2.2.5版本:整合Rabbitmq +https://note.wiz.cn/web/web?dc=75e96ad4-d818-47a3-b566-62f41bc425c4&kb=&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/maven-plugin/) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) +* [Spring for RabbitMQ](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-amqp) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) +* [Messaging with RabbitMQ](https://spring.io/guides/gs/messaging-rabbitmq/) + diff --git a/springboot-225-rabbitmq-provider/.gitignore b/springboot-225-rabbitmq-provider/.gitignore index 7bd258a..0054eae 100644 --- a/springboot-225-rabbitmq-provider/.gitignore +++ b/springboot-225-rabbitmq-provider/.gitignore @@ -1,4 +1,3 @@ -HELP.md target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** diff --git a/springboot-225-rabbitmq-provider/README.md b/springboot-225-rabbitmq-provider/README.md new file mode 100644 index 0000000..5eb7492 --- /dev/null +++ b/springboot-225-rabbitmq-provider/README.md @@ -0,0 +1,20 @@ +# Getting Started +## SpringBoot2.2.5版本:整合Rabbitmq +https://note.wiz.cn/web/web?dc=75e96ad4-d818-47a3-b566-62f41bc425c4&kb=&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/maven-plugin/) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) +* [Spring for RabbitMQ](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-amqp) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) +* [Messaging with RabbitMQ](https://spring.io/guides/gs/messaging-rabbitmq/) + diff --git a/springboot-225-redis/.gitignore b/springboot-225-redis/.gitignore index 7bd258a..0054eae 100644 --- a/springboot-225-redis/.gitignore +++ b/springboot-225-redis/.gitignore @@ -1,4 +1,3 @@ -HELP.md target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** diff --git a/springboot-225-redis/README.md b/springboot-225-redis/README.md new file mode 100644 index 0000000..9781f90 --- /dev/null +++ b/springboot-225-redis/README.md @@ -0,0 +1,18 @@ +# Getting Started +## SpringBoot2.2.5版本:整合Redis +https://note.wiz.cn/web/web?dc=ab5e4c80-98d2-4752-956a-ee6947d0a490&kb=&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/maven-plugin/) +* [Spring Data Reactive Redis](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-redis) +* [Spring Data Redis (Access+Driver)](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-redis) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Messaging with Redis](https://spring.io/guides/gs/messaging-redis/) +* [Messaging with Redis](https://spring.io/guides/gs/messaging-redis/) + -- Gitee From 04738efd5b36388bb985959b9a82510f2e622e55 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sat, 21 Mar 2020 09:09:55 +0800 Subject: [PATCH 21/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88jpa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-jpa/.gitignore | 31 ++ springboot-225-jpa/README.md | 20 ++ springboot-225-jpa/mvnw | 322 ++++++++++++++++++ springboot-225-jpa/mvnw.cmd | 182 ++++++++++ springboot-225-jpa/pom.xml | 63 ++++ .../Springboot225JpaApplication.java | 13 + .../controller/AccountController.java | 52 +++ .../springboot225jpa/dao/AccountDao.java | 7 + .../springboot225jpa/entity/Account.java | 17 + .../src/main/resources/application.yml | 11 + .../Springboot225JpaApplicationTests.java | 13 + 11 files changed, 731 insertions(+) create mode 100644 springboot-225-jpa/.gitignore create mode 100644 springboot-225-jpa/README.md create mode 100644 springboot-225-jpa/mvnw create mode 100644 springboot-225-jpa/mvnw.cmd create mode 100644 springboot-225-jpa/pom.xml create mode 100644 springboot-225-jpa/src/main/java/com/example/springboot225jpa/Springboot225JpaApplication.java create mode 100644 springboot-225-jpa/src/main/java/com/example/springboot225jpa/controller/AccountController.java create mode 100644 springboot-225-jpa/src/main/java/com/example/springboot225jpa/dao/AccountDao.java create mode 100644 springboot-225-jpa/src/main/java/com/example/springboot225jpa/entity/Account.java create mode 100644 springboot-225-jpa/src/main/resources/application.yml create mode 100644 springboot-225-jpa/src/test/java/com/example/springboot225jpa/Springboot225JpaApplicationTests.java diff --git a/springboot-225-jpa/.gitignore b/springboot-225-jpa/.gitignore new file mode 100644 index 0000000..0054eae --- /dev/null +++ b/springboot-225-jpa/.gitignore @@ -0,0 +1,31 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ +.mvn \ No newline at end of file diff --git a/springboot-225-jpa/README.md b/springboot-225-jpa/README.md new file mode 100644 index 0000000..3c16566 --- /dev/null +++ b/springboot-225-jpa/README.md @@ -0,0 +1,20 @@ +# Getting Started +## SpringBoot2.2.5版本:整合jpa +https://note.wiz.cn/web/web?dc=63d49cdb-209e-41de-aeec-6e64a2040545&kb=&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/maven-plugin/) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-jpa-and-spring-data) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) + diff --git a/springboot-225-jpa/mvnw b/springboot-225-jpa/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/springboot-225-jpa/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-jpa/mvnw.cmd b/springboot-225-jpa/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-jpa/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-225-jpa/pom.xml b/springboot-225-jpa/pom.xml new file mode 100644 index 0000000..6f21f13 --- /dev/null +++ b/springboot-225-jpa/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-jpa + 0.0.1-SNAPSHOT + springboot-225-jpa + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + mysql + mysql-connector-java + runtime + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-jpa/src/main/java/com/example/springboot225jpa/Springboot225JpaApplication.java b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/Springboot225JpaApplication.java new file mode 100644 index 0000000..b6c4735 --- /dev/null +++ b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/Springboot225JpaApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225jpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225JpaApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225JpaApplication.class, args); + } + +} diff --git a/springboot-225-jpa/src/main/java/com/example/springboot225jpa/controller/AccountController.java b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/controller/AccountController.java new file mode 100644 index 0000000..9dc9538 --- /dev/null +++ b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/controller/AccountController.java @@ -0,0 +1,52 @@ +package com.example.springboot225jpa.controller; + +import com.example.springboot225jpa.dao.AccountDao; +import com.example.springboot225jpa.entity.Account; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +@RestController +@RequestMapping("/account") +public class AccountController { + + @Resource + AccountDao accountDao; + + @RequestMapping(value = "/list", method = RequestMethod.GET) + public List getAccounts() { + return accountDao.findAll(); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + public Account getAccountById(@PathVariable("id") int id) { + return accountDao.getOne(id); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name, + @RequestParam(value = "money", required = true) double money) { + Account account = new Account(); + account.setMoney(money); + account.setName(name); + account.setId(id); + Account account1 = accountDao.saveAndFlush(account); + + return account1.toString(); + + } + + @RequestMapping(value = "", method = RequestMethod.POST) + public String postAccount(@RequestParam(value = "name") String name, + @RequestParam(value = "money") double money) { + Account account = new Account(); + account.setMoney(money); + account.setName(name); + Account account1 = accountDao.save(account); + return account1.toString(); + + } + + +} \ No newline at end of file diff --git a/springboot-225-jpa/src/main/java/com/example/springboot225jpa/dao/AccountDao.java b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/dao/AccountDao.java new file mode 100644 index 0000000..0b36b31 --- /dev/null +++ b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/dao/AccountDao.java @@ -0,0 +1,7 @@ +package com.example.springboot225jpa.dao; + +import com.example.springboot225jpa.entity.Account; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface AccountDao extends JpaRepository { +} diff --git a/springboot-225-jpa/src/main/java/com/example/springboot225jpa/entity/Account.java b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/entity/Account.java new file mode 100644 index 0000000..6689616 --- /dev/null +++ b/springboot-225-jpa/src/main/java/com/example/springboot225jpa/entity/Account.java @@ -0,0 +1,17 @@ +package com.example.springboot225jpa.entity; + +import lombok.Data; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +@Data +public class Account { + @Id + @GeneratedValue + private int id ; + private String name ; + private double money; +} diff --git a/springboot-225-jpa/src/main/resources/application.yml b/springboot-225-jpa/src/main/resources/application.yml new file mode 100644 index 0000000..0a8508e --- /dev/null +++ b/springboot-225-jpa/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&serverTimezone=UTC + username: root + password: 123456 + + jpa: + hibernate: + ddl-auto: update # 第一次建表create 后面用update + show-sql: true \ No newline at end of file diff --git a/springboot-225-jpa/src/test/java/com/example/springboot225jpa/Springboot225JpaApplicationTests.java b/springboot-225-jpa/src/test/java/com/example/springboot225jpa/Springboot225JpaApplicationTests.java new file mode 100644 index 0000000..b8f521f --- /dev/null +++ b/springboot-225-jpa/src/test/java/com/example/springboot225jpa/Springboot225JpaApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225jpa; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225JpaApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From d05c1e1d5202585d9ca89f243a1043a63fabb9be Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sun, 22 Mar 2020 18:24:53 +0800 Subject: [PATCH 22/49] =?UTF-8?q?=E4=BC=98=E5=8C=96SpringBoot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC=EF=BC=9A=E6=95=B4=E5=90=88redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-redis/pom.xml | 10 +++---- .../springbootredis/config/RedisConfig.java | 26 ++++++++--------- .../controller/UserController.java | 25 ++++++++++++---- .../example/springbootredis/entity/Days.java | 18 ------------ .../example/springbootredis/entity/User.java | 2 ++ .../src/main/resources/application.properties | 18 ++++++++++-- .../SpringbootRedisApplicationTests.java | 29 +------------------ 7 files changed, 56 insertions(+), 72 deletions(-) delete mode 100644 springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java diff --git a/springboot-225-redis/pom.xml b/springboot-225-redis/pom.xml index 44b85cb..2e30568 100644 --- a/springboot-225-redis/pom.xml +++ b/springboot-225-redis/pom.xml @@ -23,6 +23,11 @@ org.springframework.boot spring-boot-starter-data-redis + + + org.apache.commons + commons-pool2 + org.projectlombok @@ -41,11 +46,6 @@ spring-boot-starter-web - - com.alibaba - fastjson - 1.2.62 - diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java index 6493261..354f6ce 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java @@ -1,24 +1,24 @@ package com.example.springbootredis.config; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; -import javax.annotation.Resource; +import java.io.Serializable; @Configuration +// @AutoConfigureAfter 在加载配置的类之后再加载当前类; 这里就是在加载RedisAutoConfiguration之后,再加载RedisConfig +//@AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig{ - @Resource - private RedisTemplate redisTemplate; - - @Autowired(required = false) - public void setRedisTemplate(RedisTemplate redisTemplate) { - StringRedisSerializer stringSerializer = new StringRedisSerializer(); - redisTemplate.setKeySerializer(stringSerializer); - redisTemplate.setValueSerializer(stringSerializer); - redisTemplate.setHashKeySerializer(stringSerializer); - redisTemplate.setHashValueSerializer(stringSerializer); - this.redisTemplate = redisTemplate; + @Bean + public RedisTemplate redisCacheTemplate(LettuceConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setKeySerializer(new StringRedisSerializer()); + template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); + template.setConnectionFactory(connectionFactory); + return template; } } diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java index cc61764..6764a52 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java @@ -1,17 +1,18 @@ package com.example.springbootredis.controller; -import com.alibaba.fastjson.JSONObject; import com.example.springbootredis.entity.User; import com.example.springbootredis.service.UserService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; +import java.io.Serializable; @RestController @RequestMapping("/user") @@ -19,16 +20,28 @@ public class UserController { public static Logger logger = LogManager.getLogger(UserController.class); + // String类型 @Resource - private RedisTemplate redisCacheTemplate; + private StringRedisTemplate stringRedisTemplate; + // Hash list set zset类型 + @Resource + private RedisTemplate redisCacheTemplate; @Resource private UserService userService; - @RequestMapping("/test") - public Object test() { - redisCacheTemplate.opsForValue().set("userkey", JSONObject.toJSONString(new User(1, "张三", 25))); - Object user = redisCacheTemplate.opsForValue().get("userkey"); + @RequestMapping("/testStr") + public String testStr() { + stringRedisTemplate.opsForValue().set("strKey", "strValue"); + String strValue = stringRedisTemplate.opsForValue().get("strKey"); + logger.info("当前获取对象:{}", strValue); + return strValue; + } + + @RequestMapping("/testObj") + public User testObj() { + redisCacheTemplate.opsForValue().set("userkey", new User(1, "张三", 25)); + User user = (User) redisCacheTemplate.opsForValue().get("userkey"); logger.info("当前获取对象:{}", user); return user; } diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java deleted file mode 100644 index 53137f9..0000000 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/entity/Days.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.example.springbootredis.entity; - -import lombok.Data; - -import java.io.Serializable; - -@Data -public class Days implements Serializable { - private static final long serialVersionUID = -5625743904227623649L; - private String openId; - private String daysId; - // 每天的标题 - private String title; - // 代办事项的数量 - private int itemNumber; - //日程 - private String date; -} diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java index 5c980ed..d465ec7 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java @@ -2,11 +2,13 @@ package com.example.springbootredis.entity; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor +@NoArgsConstructor public class User implements Serializable { private static final long serialVersionUID = 966312196259333201L; private Integer id; diff --git a/springboot-225-redis/src/main/resources/application.properties b/springboot-225-redis/src/main/resources/application.properties index 5193cd6..5981b68 100644 --- a/springboot-225-redis/src/main/resources/application.properties +++ b/springboot-225-redis/src/main/resources/application.properties @@ -1,4 +1,18 @@ +# redis +# 连接设置 +spring.cache.type=redis spring.redis.host=localhost spring.redis.port=6379 -spring.redis.password= -spring.redis.database=0 \ No newline at end of file +spring.redis.password=123456 +# redis默认情况下有16个分片,这里配置具体使用的分片,默认为0 +spring.redis.database=0 + +# 连接池设置 +# 连接池中“空闲”连接的最大数量。使用负值表示无限数量的空闲连接。 +spring.redis.lettuce.pool.max-idle=8 +# 目标要在连接池中维护的最小空闲连接数。仅当此设置和逐次运行之间的时间都为正时,此设置才有效。 +spring.redis.lettuce.pool.min-idle=0 +# 当连接池耗尽时,在引发异常之前,连接分配应阻塞的最长时间。使用负值无限期阻止。 +spring.redis.lettuce.pool.max-wait= +# 连接池最大连接数(使用负数表示没有限制),默认8 +spring.redis.lettuce.pool.max-active=8 \ No newline at end of file diff --git a/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java b/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java index 3334881..62a9c2b 100644 --- a/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java +++ b/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java @@ -1,35 +1,8 @@ package com.example.springbootredis; -import com.alibaba.fastjson.JSONObject; -import com.example.springbootredis.entity.Days; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.redis.core.RedisTemplate; - -import java.util.concurrent.TimeUnit; @SpringBootTest -class SpringbootRedisApplicationTests { - - @Autowired - private RedisTemplate redisTemplate; - @Test - public void testString(){ - redisTemplate.opsForValue().set("myKey","myValue"); - System.out.println(redisTemplate.opsForValue().get("myKey")); - } - - @Test - public void testObject(){ - Days days = new Days(); - days.setDate("123"); - days.setDaysId("456"); - days.setItemNumber(123); - days.setOpenId("dawda"); - days.setTitle("title"); - redisTemplate.opsForValue().set("days", JSONObject.toJSONString(days),60,TimeUnit.SECONDS); - System.out.println((redisTemplate.opsForValue().get("days"))); - } +public class SpringbootRedisApplicationTests { } -- Gitee From 8c74ee43a117dcd6ceaa161079d6e30ea54321cd Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sun, 22 Mar 2020 21:51:55 +0800 Subject: [PATCH 23/49] =?UTF-8?q?=E4=BC=98=E5=8C=96SpringBoot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC=EF=BC=9A=E6=95=B4=E5=90=88redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/springbootredis/SpringbootRedisApplication.java | 3 ++- .../java/com/example/springbootredis/config/RedisConfig.java | 4 +++- .../com/example/springbootredis/service/UserServiceImpl.java | 1 + 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java b/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java index 13b7125..2b6bb52 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java @@ -2,9 +2,10 @@ package com.example.springbootredis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cache.annotation.EnableCaching; -@SpringBootApplication +@SpringBootApplication(exclude= DataSourceAutoConfiguration.class) @EnableCaching public class SpringbootRedisApplication { diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java index 354f6ce..992d1a4 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java @@ -1,5 +1,7 @@ package com.example.springbootredis.config; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @@ -11,7 +13,7 @@ import java.io.Serializable; @Configuration // @AutoConfigureAfter 在加载配置的类之后再加载当前类; 这里就是在加载RedisAutoConfiguration之后,再加载RedisConfig -//@AutoConfigureAfter(RedisAutoConfiguration.class) +@AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig{ @Bean public RedisTemplate redisCacheTemplate(LettuceConnectionFactory connectionFactory) { diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java index 5ef608c..5c30d52 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java @@ -20,6 +20,7 @@ public class UserServiceImpl implements UserService { userMap.put(1, new User(1, "肖战", 25)); userMap.put(2, new User(2, "王一博", 26)); userMap.put(3, new User(3, "杨紫", 24)); + userMap.put(4, new User(4, "李现", 30)); } -- Gitee From 3d2160cacf41e534f2d259c989db19689f07b74b Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 24 Mar 2020 10:35:32 +0800 Subject: [PATCH 24/49] =?UTF-8?q?=E4=BC=98=E5=8C=96SpringBoot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC=EF=BC=9A=E6=95=B4=E5=90=88redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/springbootredis/controller/UserController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java index 6764a52..fe137d7 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java @@ -20,10 +20,10 @@ public class UserController { public static Logger logger = LogManager.getLogger(UserController.class); - // String类型 + // String(字符串) @Resource private StringRedisTemplate stringRedisTemplate; - // Hash list set zset类型 + // Hash(散列),List(列表),Set(集合),Sorted Set(有序不重复集合) @Resource private RedisTemplate redisCacheTemplate; -- Gitee From 9088e9829dfbcbae97b821199746dd63b572cfb2 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 24 Mar 2020 12:44:25 +0800 Subject: [PATCH 25/49] =?UTF-8?q?=E4=BC=98=E5=8C=96SpringBoot2.2.5?= =?UTF-8?q?=E7=89=88=E6=9C=AC=EF=BC=9A=E6=95=B4=E5=90=88redis,=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Hash=E7=B1=BB=E5=9E=8B=E7=9A=84=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../springbootredis/config/RedisConfig.java | 4 ++++ .../controller/UserController.java | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java index 992d1a4..1d409fe 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java @@ -18,8 +18,12 @@ public class RedisConfig{ @Bean public RedisTemplate redisCacheTemplate(LettuceConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); + // 设置String类型存储序列化 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); + // 设置Hash类型存储序列化 + template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer()); + template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(connectionFactory); return template; } diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java index fe137d7..52bbd6c 100644 --- a/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java @@ -2,6 +2,7 @@ package com.example.springbootredis.controller; import com.example.springbootredis.entity.User; import com.example.springbootredis.service.UserService; +import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.data.redis.core.RedisTemplate; @@ -13,9 +14,11 @@ import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.io.Serializable; +import java.util.HashMap; @RestController @RequestMapping("/user") +@Slf4j public class UserController { public static Logger logger = LogManager.getLogger(UserController.class); @@ -46,6 +49,18 @@ public class UserController { return user; } + @RequestMapping("/testHash") + public void testHash() { + HashMap userMap = new HashMap<>(); + userMap.put(1, new User(1, "肖战", 25)); + userMap.put(2, new User(2, "王一博", 26)); + userMap.put(3, new User(3, "杨紫", 24)); + userMap.put(4, new User(4, "李现", 30)); + redisCacheTemplate.opsForHash().putAll("HashKey",userMap); + Object user = redisCacheTemplate.opsForHash().get("HashKey", 1); + logger.info("当前获取对象:{}",user); + } + @RequestMapping("/add") public void add() { User user = userService.save(new User(4, "李现", 30)); -- Gitee From 0643450751c3b6954545031692bad6ced523d2c7 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 24 Mar 2020 18:28:40 +0800 Subject: [PATCH 26/49] =?UTF-8?q?=E8=87=AA=E5=B7=B1=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E4=B8=80=E4=B8=AAspring-boot-starter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring-boot-starter-demo | 1 + 1 file changed, 1 insertion(+) create mode 160000 spring-boot-starter-demo diff --git a/spring-boot-starter-demo b/spring-boot-starter-demo new file mode 160000 index 0000000..21bc5ce --- /dev/null +++ b/spring-boot-starter-demo @@ -0,0 +1 @@ +Subproject commit 21bc5ce38b11ed245fd0d262494b853c9b3484a3 -- Gitee From f321ca6aeb56af04048820b50beb28c723076628 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sun, 5 Apr 2020 15:17:41 +0800 Subject: [PATCH 27/49] =?UTF-8?q?springboot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88MongoDB=EF=BC=88=E6=9C=89=E5=AF=86?= =?UTF-8?q?=E7=A0=81=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-mongodb/.gitignore | 30 ++ springboot-225-mongodb/README.md | 17 + springboot-225-mongodb/mvnw | 322 ++++++++++++++++++ springboot-225-mongodb/mvnw.cmd | 182 ++++++++++ springboot-225-mongodb/pom.xml | 58 ++++ .../springboot225mongodb/BaseController.java | 33 ++ .../example/springboot225mongodb/Book.java | 24 ++ .../springboot225mongodb/MongoDbService.java | 117 +++++++ .../Springboot225MongodbApplication.java | 13 + .../src/main/resources/application.properties | 6 + .../Springboot225MongodbApplicationTests.java | 44 +++ .../dao/CustomerRepository.java | 13 + .../springboot225mongodb/entity/Customer.java | 28 ++ 13 files changed, 887 insertions(+) create mode 100644 springboot-225-mongodb/.gitignore create mode 100644 springboot-225-mongodb/README.md create mode 100644 springboot-225-mongodb/mvnw create mode 100644 springboot-225-mongodb/mvnw.cmd create mode 100644 springboot-225-mongodb/pom.xml create mode 100644 springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/BaseController.java create mode 100644 springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java create mode 100644 springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/MongoDbService.java create mode 100644 springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Springboot225MongodbApplication.java create mode 100644 springboot-225-mongodb/src/main/resources/application.properties create mode 100644 springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java create mode 100644 springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java create mode 100644 springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java diff --git a/springboot-225-mongodb/.gitignore b/springboot-225-mongodb/.gitignore new file mode 100644 index 0000000..3a568a5 --- /dev/null +++ b/springboot-225-mongodb/.gitignore @@ -0,0 +1,30 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-mongodb/README.md b/springboot-225-mongodb/README.md new file mode 100644 index 0000000..eb0a7af --- /dev/null +++ b/springboot-225-mongodb/README.md @@ -0,0 +1,17 @@ +# Getting Started +SpringBoot2.2.5版本:整合MongoDB(有密码) + +https://www.wiz.cn/wapp/recent/?docGuid=21ab1437-c59d-45cc-9890-f3f0abde22f1&cmd=km%2C + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/maven-plugin/) +* [Spring Data MongoDB](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-mongodb) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Accessing Data with MongoDB](https://spring.io/guides/gs/accessing-data-mongodb/) + diff --git a/springboot-225-mongodb/mvnw b/springboot-225-mongodb/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/springboot-225-mongodb/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-mongodb/mvnw.cmd b/springboot-225-mongodb/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-mongodb/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-225-mongodb/pom.xml b/springboot-225-mongodb/pom.xml new file mode 100644 index 0000000..1ae9bac --- /dev/null +++ b/springboot-225-mongodb/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-mongodb + 0.0.1-SNAPSHOT + springboot-225-mongodb + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/BaseController.java b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/BaseController.java new file mode 100644 index 0000000..49c2e88 --- /dev/null +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/BaseController.java @@ -0,0 +1,33 @@ +package com.example.springboot225mongodb; + +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +@RestController +public class BaseController { + @Resource + private MongoDbService mongoDbService; + + @PostMapping("/mongo/save") + public String saveObj(@RequestBody Book book) {return mongoDbService.saveObj(book);} + + @GetMapping("/mongo/findAll") + public List findAll() {return mongoDbService.findAll();} + + @GetMapping("/mongo/findOne") + public Book findOne(@RequestParam String id) {return mongoDbService.getBookById(id);} + + @GetMapping("/mongo/findOneByName") + public Book findOneByName(@RequestParam String name) {return mongoDbService.getBookByName(name);} + + @PostMapping("/mongo/update") + public String update(@RequestBody Book book) {return mongoDbService.updateBook(book);} + + @PostMapping("/mongo/delOne") + public String delOne(@RequestBody Book book) {return mongoDbService.deleteBook(book);} + + @GetMapping("/mongo/delById") + public String delById(@RequestParam String id) {return mongoDbService.deleteBookById(id);} +} diff --git a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java new file mode 100644 index 0000000..a63560b --- /dev/null +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java @@ -0,0 +1,24 @@ +package com.example.springboot225mongodb; + +import lombok.Data; +import org.springframework.data.annotation.Id; + +import java.util.Date; + +@Data +public class Book { + @Id + private String id; + //价格 + private Integer price; + //书名 + private String name; + //简介 + private String info; + //出版社 + private String publish; + //创建时间 + private Date createTime; + //修改时间 + private Date updateTime; +} diff --git a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/MongoDbService.java b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/MongoDbService.java new file mode 100644 index 0000000..308076c --- /dev/null +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/MongoDbService.java @@ -0,0 +1,117 @@ +package com.example.springboot225mongodb; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; + +@Service +public class MongoDbService { + private static final Logger logger = LoggerFactory.getLogger(MongoDbService.class); + + @Resource + private MongoTemplate mongoTemplate; + + /** + * 保存对象 + * + * @param book + * @return + */ + public String saveObj(Book book) { + logger.info("--------------------->[MongoDB save start]"); + book.setCreateTime(new Date()); + book.setUpdateTime(new Date()); + mongoTemplate.save(book); + return "添加成功"; + } + + + /** + * 查询所有 + * + * @return + */ + public List findAll() { + logger.info("--------------------->[MongoDB find start]"); + return mongoTemplate.findAll(Book.class); + } + + + /*** + * 根据id查询 + * @param id + * @return + */ + public Book getBookById(String id) { + logger.info("--------------------->[MongoDB find start]"); + Query query = new Query(Criteria.where("_id").is(id)); + return mongoTemplate.findOne(query, Book.class); + } + + /** + * 根据名称查询 + * + * @param name + * @return + */ + public Book getBookByName(String name) { + logger.info("--------------------->[MongoDB find start]"); + Query query = new Query(Criteria.where("name").is(name)); + return mongoTemplate.findOne(query, Book.class); + } + + /** + * 更新对象 + * + * @param book + * @return + */ + public String updateBook(Book book) { + logger.info("--------------------->[MongoDB update start]"); + Query query = new Query(Criteria.where("_id").is(book.getId())); + Update update = new Update().set("publish", book.getPublish()) + .set("info", book.getInfo()) + .set("updateTime", new Date()); + //updateFirst 更新查询返回结果集的第一条 + mongoTemplate.updateFirst(query, update, Book.class); + //updateMulti 更新查询返回结果集的全部 +// mongoTemplate.updateMulti(query,update,Book.class); + //upsert 更新对象不存在则去添加 +// mongoTemplate.upsert(query,update,Book.class); + return "success"; + } + + /*** + * 删除对象 + * @param book + * @return + */ + public String deleteBook(Book book) { + logger.info("--------------------->[MongoDB delete start]"); + mongoTemplate.remove(book); + return "success"; + } + + /** + * 根据id删除 + * + * @param id + * @return + */ + public String deleteBookById(String id) { + logger.info("--------------------->[MongoDB delete start]"); + //findOne + Book book = getBookById(id); + //delete + deleteBook(book); + return "success"; + } +} diff --git a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Springboot225MongodbApplication.java b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Springboot225MongodbApplication.java new file mode 100644 index 0000000..8830331 --- /dev/null +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Springboot225MongodbApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225mongodb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225MongodbApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225MongodbApplication.class, args); + } + +} diff --git a/springboot-225-mongodb/src/main/resources/application.properties b/springboot-225-mongodb/src/main/resources/application.properties new file mode 100644 index 0000000..c705c92 --- /dev/null +++ b/springboot-225-mongodb/src/main/resources/application.properties @@ -0,0 +1,6 @@ +#spring.data.mongodb.uri=mongodb://admin:123456@localhost:27017/admin +spring.data.mongodb.host=127.0.0.1 +spring.data.mongodb.port=27017 +spring.data.mongodb.database=admin +spring.data.mongodb.username=admin +spring.data.mongodb.password=123456 diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java new file mode 100644 index 0000000..151ab58 --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java @@ -0,0 +1,44 @@ +package com.example.springboot225mongodb; + +import com.example.springboot225mongodb.dao.CustomerRepository; +import com.example.springboot225mongodb.entity.Customer; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; + +@SpringBootTest +class Springboot225MongodbApplicationTests { + + @Resource + private CustomerRepository repository; + + @Test + void contextLoads() { + repository.deleteAll(); + + // save a couple of customers + repository.save(new Customer("Alice", "Smith")); + repository.save(new Customer("Bob", "Smith")); + + // fetch all customers + System.out.println("Customers found with findAll():"); + System.out.println("-------------------------------"); + for (Customer customer : repository.findAll()) { + System.out.println(customer); + } + System.out.println(); + + // fetch an individual customer + System.out.println("Customer found with findByFirstName('Alice'):"); + System.out.println("--------------------------------"); + System.out.println(repository.findByFirstName("Alice")); + + System.out.println("Customers found with findByLastName('Smith'):"); + System.out.println("--------------------------------"); + for (Customer customer : repository.findByLastName("Smith")) { + System.out.println(customer); + } + } + +} diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java new file mode 100644 index 0000000..b93be35 --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java @@ -0,0 +1,13 @@ +package com.example.springboot225mongodb.dao; + +import com.example.springboot225mongodb.entity.Customer; +import org.springframework.data.mongodb.repository.MongoRepository; + +import java.util.List; + +public interface CustomerRepository extends MongoRepository { + + Customer findByFirstName(String firstName); + List findByLastName(String lastName); + +} \ No newline at end of file diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java new file mode 100644 index 0000000..a84a1e1 --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java @@ -0,0 +1,28 @@ +package com.example.springboot225mongodb.entity; + +import org.springframework.data.annotation.Id; + + +public class Customer { + + @Id + public String id; + + public String firstName; + public String lastName; + + public Customer() {} + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + @Override + public String toString() { + return String.format( + "Customer[id=%s, firstName='%s', lastName='%s']", + id, firstName, lastName); + } + +} \ No newline at end of file -- Gitee From a11616611284b313cd73b8d6de05382d520eb38d Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sun, 5 Apr 2020 16:28:25 +0800 Subject: [PATCH 28/49] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/.gitignore | 2 ++ demo/pom.xml | 12 ++++++++++++ demo/src/main/java/Test01.java | 17 +++++++++++++++++ demo/src/main/java/Test02.java | 25 +++++++++++++++++++++++++ demo/src/main/java/TestThread.java | 15 +++++++++++++++ 5 files changed, 71 insertions(+) create mode 100644 demo/.gitignore create mode 100644 demo/pom.xml create mode 100644 demo/src/main/java/Test01.java create mode 100644 demo/src/main/java/Test02.java create mode 100644 demo/src/main/java/TestThread.java diff --git a/demo/.gitignore b/demo/.gitignore new file mode 100644 index 0000000..dc48b22 --- /dev/null +++ b/demo/.gitignore @@ -0,0 +1,2 @@ +*.iml +target \ No newline at end of file diff --git a/demo/pom.xml b/demo/pom.xml new file mode 100644 index 0000000..2c4ddcb --- /dev/null +++ b/demo/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + org.example + demo + 1.0-SNAPSHOT + + + \ No newline at end of file diff --git a/demo/src/main/java/Test01.java b/demo/src/main/java/Test01.java new file mode 100644 index 0000000..54a8529 --- /dev/null +++ b/demo/src/main/java/Test01.java @@ -0,0 +1,17 @@ +import java.util.HashMap; + +public class Test01 { + public static void main(String[] args) { + int a = 1; + int b = 1; + System.out.println(a==b); + + String c = "a"; + String d = "a"; + System.out.println(c==d); + + HashMap hashMap = new HashMap(); + int i = hashMap.hashCode(); + System.out.println(i); + } +} diff --git a/demo/src/main/java/Test02.java b/demo/src/main/java/Test02.java new file mode 100644 index 0000000..03091ae --- /dev/null +++ b/demo/src/main/java/Test02.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.List; + +public class Test02 { + public static void main(String[] args) { + int[] numbers = {3, 32, 321}; + System.out.println(PrintMaxNumber(numbers)); + } + + static String PrintMaxNumber(int[] numbers) { + if (numbers == null || numbers.length == 0) { + return ""; + } + List list = new ArrayList<>(); + for (int a : numbers) { + list.add(a); + } + list.sort((a, b) -> (b + "" + a).compareTo(a + "" + b)); + StringBuffer stringBuffer = new StringBuffer(); + for (int a : list) { + stringBuffer.append(a); + } + return stringBuffer.toString(); + } +} diff --git a/demo/src/main/java/TestThread.java b/demo/src/main/java/TestThread.java new file mode 100644 index 0000000..0237a89 --- /dev/null +++ b/demo/src/main/java/TestThread.java @@ -0,0 +1,15 @@ +public class TestThread { + public static void main(String[] args) throws InterruptedException { + Thread t = new Thread() { + public void run() { + pong(); + } + } ; + t.start(); + Thread.sleep(5); + System.out.print("ping"); + } + static void pong(){ + System.out.print("pong"); + } +} -- Gitee From 38878a803d6e50990224ea5c90cc894a90d225b1 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Sun, 5 Apr 2020 23:02:39 +0800 Subject: [PATCH 29/49] =?UTF-8?q?=E6=B7=BB=E5=8A=A0JUC=E5=B9=B6=E5=8F=91?= =?UTF-8?q?=E7=BA=BF=E7=A8=8Bdemo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/.gitignore | 31 +- demo/mvnw | 322 ++++++++++++++++++ demo/mvnw.cmd | 182 ++++++++++ demo/pom.xml | 56 ++- .../com/example/demo/DemoApplication.java | 13 + .../example/demo/juc/SafeAddWithAtomic.java | 37 ++ .../demo/juc/SafeAddWithStriped64.java | 37 ++ .../com/example/demo/juc/SafeAddWithSyn.java | 36 ++ .../java/com/example/demo/juc/UnSafeAdd.java | 37 ++ .../{ => com/example/demo/test}/Test01.java | 2 + .../{ => com/example/demo/test}/Test02.java | 2 + .../example/demo/test}/TestThread.java | 2 + .../src/main/resources/application.properties | 1 + .../example/demo/DemoApplicationTests.java | 13 + 14 files changed, 763 insertions(+), 8 deletions(-) create mode 100644 demo/mvnw create mode 100644 demo/mvnw.cmd create mode 100644 demo/src/main/java/com/example/demo/DemoApplication.java create mode 100644 demo/src/main/java/com/example/demo/juc/SafeAddWithAtomic.java create mode 100644 demo/src/main/java/com/example/demo/juc/SafeAddWithStriped64.java create mode 100644 demo/src/main/java/com/example/demo/juc/SafeAddWithSyn.java create mode 100644 demo/src/main/java/com/example/demo/juc/UnSafeAdd.java rename demo/src/main/java/{ => com/example/demo/test}/Test01.java (92%) rename demo/src/main/java/{ => com/example/demo/test}/Test02.java (95%) rename demo/src/main/java/{ => com/example/demo/test}/TestThread.java (91%) create mode 100644 demo/src/main/resources/application.properties create mode 100644 demo/src/test/java/com/example/demo/DemoApplicationTests.java diff --git a/demo/.gitignore b/demo/.gitignore index dc48b22..a2a3040 100644 --- a/demo/.gitignore +++ b/demo/.gitignore @@ -1,2 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws *.iml -target \ No newline at end of file +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/demo/mvnw b/demo/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/demo/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/demo/mvnw.cmd b/demo/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/demo/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/demo/pom.xml b/demo/pom.xml index 2c4ddcb..b67d5f1 100644 --- a/demo/pom.xml +++ b/demo/pom.xml @@ -1,12 +1,54 @@ - + 4.0.0 - - org.example + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.example demo - 1.0-SNAPSHOT + 0.0.1-SNAPSHOT + demo + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + - \ No newline at end of file + diff --git a/demo/src/main/java/com/example/demo/DemoApplication.java b/demo/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..094d95b --- /dev/null +++ b/demo/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/demo/src/main/java/com/example/demo/juc/SafeAddWithAtomic.java b/demo/src/main/java/com/example/demo/juc/SafeAddWithAtomic.java new file mode 100644 index 0000000..7a6d941 --- /dev/null +++ b/demo/src/main/java/com/example/demo/juc/SafeAddWithAtomic.java @@ -0,0 +1,37 @@ +package com.example.demo.juc; + +import lombok.extern.slf4j.Slf4j; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +public class SafeAddWithAtomic { + + private static int threadCount = 10; + private static CountDownLatch countDown = new CountDownLatch(threadCount); + private static AtomicInteger count = new AtomicInteger(0); + + private static void add(){ + for (int i = 0; i < 1000; i++) { + count.incrementAndGet(); + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + countDown.countDown(); + } + + public static void main(String[] args) throws InterruptedException { + long start = System.currentTimeMillis(); + for (int i = 0; i < threadCount; i++) { + new Thread(SafeAddWithAtomic::add).start(); + } + countDown.await(); + log.info("count: {}", count.get()); + long end = System.currentTimeMillis(); + System.out.println("使用时间:"+(end-start)+"毫秒"); + } +} \ No newline at end of file diff --git a/demo/src/main/java/com/example/demo/juc/SafeAddWithStriped64.java b/demo/src/main/java/com/example/demo/juc/SafeAddWithStriped64.java new file mode 100644 index 0000000..cf76d3d --- /dev/null +++ b/demo/src/main/java/com/example/demo/juc/SafeAddWithStriped64.java @@ -0,0 +1,37 @@ +package com.example.demo.juc; + +import lombok.extern.slf4j.Slf4j; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.LongAdder; + +@Slf4j +public class SafeAddWithStriped64 { + + private static int threadCount = 10; + private static CountDownLatch countDown = new CountDownLatch(threadCount); + private static LongAdder count = new LongAdder(); + + private static void add(){ + for (int i = 0; i < 1000; i++) { + count.increment(); + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + countDown.countDown(); + } + + public static void main(String[] args) throws InterruptedException { + long start = System.currentTimeMillis(); + for (int i = 0; i < threadCount; i++) { + new Thread(SafeAddWithStriped64::add).start(); + } + countDown.await(); + log.info("count: {}", count); + long end = System.currentTimeMillis(); + System.out.println("使用时间:"+(end-start)+"毫秒"); + } +} \ No newline at end of file diff --git a/demo/src/main/java/com/example/demo/juc/SafeAddWithSyn.java b/demo/src/main/java/com/example/demo/juc/SafeAddWithSyn.java new file mode 100644 index 0000000..b464e5f --- /dev/null +++ b/demo/src/main/java/com/example/demo/juc/SafeAddWithSyn.java @@ -0,0 +1,36 @@ +package com.example.demo.juc; + +import lombok.extern.slf4j.Slf4j; + +import java.util.concurrent.CountDownLatch; + +@Slf4j +public class SafeAddWithSyn { + + private static int threadCount = 10; + private static CountDownLatch countDown = new CountDownLatch(threadCount); + private static int count = 0; + + private synchronized static void add(){ + for (int i = 0; i < 1000; i++) { + count += 1; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + countDown.countDown(); + } + + public static void main(String[] args) throws InterruptedException { + long start = System.currentTimeMillis(); + for (int i = 0; i < threadCount; i++) { + new Thread(SafeAddWithSyn::add).start(); + } + countDown.await(); + log.info("count: {}", count); + long end = System.currentTimeMillis(); + System.out.println("使用时间:"+(end-start)+"毫秒"); + } +} \ No newline at end of file diff --git a/demo/src/main/java/com/example/demo/juc/UnSafeAdd.java b/demo/src/main/java/com/example/demo/juc/UnSafeAdd.java new file mode 100644 index 0000000..d6cbdf5 --- /dev/null +++ b/demo/src/main/java/com/example/demo/juc/UnSafeAdd.java @@ -0,0 +1,37 @@ +package com.example.demo.juc; + + +import lombok.extern.slf4j.Slf4j; + +import java.util.concurrent.CountDownLatch; + +@Slf4j +public class UnSafeAdd { + + private static int threadCount = 10; + private static CountDownLatch countDown = new CountDownLatch(threadCount); + private static int count = 0; + + private static void add(){ + for (int i = 0; i < 1000; i++) { + count += 1; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + countDown.countDown(); + } + + public static void main(String[] args) throws InterruptedException { + long start = System.currentTimeMillis(); + for (int i = 0; i < threadCount; i++) { + new Thread(UnSafeAdd::add).start(); + } + countDown.await(); + log.info("count: {}", count); + long end = System.currentTimeMillis(); + System.out.println("使用时间:"+(end-start)+"毫秒"); + } +} \ No newline at end of file diff --git a/demo/src/main/java/Test01.java b/demo/src/main/java/com/example/demo/test/Test01.java similarity index 92% rename from demo/src/main/java/Test01.java rename to demo/src/main/java/com/example/demo/test/Test01.java index 54a8529..7142997 100644 --- a/demo/src/main/java/Test01.java +++ b/demo/src/main/java/com/example/demo/test/Test01.java @@ -1,3 +1,5 @@ +package com.example.demo.test; + import java.util.HashMap; public class Test01 { diff --git a/demo/src/main/java/Test02.java b/demo/src/main/java/com/example/demo/test/Test02.java similarity index 95% rename from demo/src/main/java/Test02.java rename to demo/src/main/java/com/example/demo/test/Test02.java index 03091ae..9d89a91 100644 --- a/demo/src/main/java/Test02.java +++ b/demo/src/main/java/com/example/demo/test/Test02.java @@ -1,3 +1,5 @@ +package com.example.demo.test; + import java.util.ArrayList; import java.util.List; diff --git a/demo/src/main/java/TestThread.java b/demo/src/main/java/com/example/demo/test/TestThread.java similarity index 91% rename from demo/src/main/java/TestThread.java rename to demo/src/main/java/com/example/demo/test/TestThread.java index 0237a89..07c5290 100644 --- a/demo/src/main/java/TestThread.java +++ b/demo/src/main/java/com/example/demo/test/TestThread.java @@ -1,3 +1,5 @@ +package com.example.demo.test; + public class TestThread { public static void main(String[] args) throws InterruptedException { Thread t = new Thread() { diff --git a/demo/src/main/resources/application.properties b/demo/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/demo/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/demo/src/test/java/com/example/demo/DemoApplicationTests.java b/demo/src/test/java/com/example/demo/DemoApplicationTests.java new file mode 100644 index 0000000..eaa9969 --- /dev/null +++ b/demo/src/test/java/com/example/demo/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 44f9b8392f0fe864a50eece8b7e73e67c067e660 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 7 Apr 2020 20:32:14 +0800 Subject: [PATCH 30/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88logback=E5=92=8Caop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-logback/.gitignore | 32 ++ springboot-225-logback/README.md | 18 + springboot-225-logback/mvnw | 322 ++++++++++++++++++ springboot-225-logback/mvnw.cmd | 182 ++++++++++ springboot-225-logback/pom.xml | 55 +++ .../Springboot225LogbackApplication.java | 13 + .../aop/WebLogAspect.java | 57 ++++ .../controller/TestController.java | 13 + .../src/main/resources/application.properties | 5 + .../src/main/resources/logback-spring.xml | 196 +++++++++++ .../Springboot225LogbackApplicationTests.java | 13 + 11 files changed, 906 insertions(+) create mode 100644 springboot-225-logback/.gitignore create mode 100644 springboot-225-logback/README.md create mode 100644 springboot-225-logback/mvnw create mode 100644 springboot-225-logback/mvnw.cmd create mode 100644 springboot-225-logback/pom.xml create mode 100644 springboot-225-logback/src/main/java/com/example/springboot225logback/Springboot225LogbackApplication.java create mode 100644 springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java create mode 100644 springboot-225-logback/src/main/java/com/example/springboot225logback/controller/TestController.java create mode 100644 springboot-225-logback/src/main/resources/application.properties create mode 100644 springboot-225-logback/src/main/resources/logback-spring.xml create mode 100644 springboot-225-logback/src/test/java/com/example/springboot225logback/Springboot225LogbackApplicationTests.java diff --git a/springboot-225-logback/.gitignore b/springboot-225-logback/.gitignore new file mode 100644 index 0000000..28f9535 --- /dev/null +++ b/springboot-225-logback/.gitignore @@ -0,0 +1,32 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ + +.mvn \ No newline at end of file diff --git a/springboot-225-logback/README.md b/springboot-225-logback/README.md new file mode 100644 index 0000000..fe638f0 --- /dev/null +++ b/springboot-225-logback/README.md @@ -0,0 +1,18 @@ +# Getting Started +SpringBoot2.2.5版本:整合logback和aop + +https://www.wiz.cn/wapp/recent/?docGuid=afb6ed6d-d189-48d8-b91d-125d578f941b&cmd=km%2C +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/maven-plugin/) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) + diff --git a/springboot-225-logback/mvnw b/springboot-225-logback/mvnw new file mode 100644 index 0000000..3c8a553 --- /dev/null +++ b/springboot-225-logback/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-225-logback/mvnw.cmd b/springboot-225-logback/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-225-logback/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-225-logback/pom.xml b/springboot-225-logback/pom.xml new file mode 100644 index 0000000..47ded9e --- /dev/null +++ b/springboot-225-logback/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-logback + 0.0.1-SNAPSHOT + springboot-225-logback + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-aop + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-logback/src/main/java/com/example/springboot225logback/Springboot225LogbackApplication.java b/springboot-225-logback/src/main/java/com/example/springboot225logback/Springboot225LogbackApplication.java new file mode 100644 index 0000000..7e3165e --- /dev/null +++ b/springboot-225-logback/src/main/java/com/example/springboot225logback/Springboot225LogbackApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225logback; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225LogbackApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225LogbackApplication.class, args); + } + +} diff --git a/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java b/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java new file mode 100644 index 0000000..4034940 --- /dev/null +++ b/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java @@ -0,0 +1,57 @@ +package com.example.springboot225logback.aop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; + +/** + * @author JamelHuang + * @date 2018/3/7 + */ + +@Aspect +@Component +public class WebLogAspect { + + private Logger logger = LoggerFactory.getLogger(WebLogAspect.class); + + @Pointcut("execution(public * com.example.springboot225logback.*.*(..))") + public void webLog(){} + + @Before("webLog()") + public void doBefore(JoinPoint joinPoint) throws Throwable { + // 接收到请求,记录请求内容 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = null; + if (attributes != null) { + request = attributes.getRequest(); + } + + // 记录下请求内容 + if (request != null) { + logger.info("REQUEST_URL : " + request.getRequestURL().toString()); + logger.info("REQUEST_PARAMETER : " + Arrays.toString(joinPoint.getArgs())); +// logger.info("HTTP_METHOD : " + request.getMethod()); +// logger.info("IP : " + request.getRemoteAddr()); +// logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); + } + + } + + @AfterReturning(returning = "ret", pointcut = "webLog()") + public void doAfterReturning(Object ret) throws Throwable { + // 处理完请求,返回内容 + logger.info("RESPONSE : " + ret); + } + +} diff --git a/springboot-225-logback/src/main/java/com/example/springboot225logback/controller/TestController.java b/springboot-225-logback/src/main/java/com/example/springboot225logback/controller/TestController.java new file mode 100644 index 0000000..c30cf0b --- /dev/null +++ b/springboot-225-logback/src/main/java/com/example/springboot225logback/controller/TestController.java @@ -0,0 +1,13 @@ +package com.example.springboot225logback.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class TestController { + @GetMapping("hi") + public String hi(@RequestParam(required = false,defaultValue = "yang") String name){ + return "hi:"+name; + } +} diff --git a/springboot-225-logback/src/main/resources/application.properties b/springboot-225-logback/src/main/resources/application.properties new file mode 100644 index 0000000..68f053a --- /dev/null +++ b/springboot-225-logback/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.application.name=logback + +logging.config=classpath:logback-spring.xml +logging.file.path=D:/mylog/ +logging.file.name=${spring.application.name}/${spring.application.name}.log \ No newline at end of file diff --git a/springboot-225-logback/src/main/resources/logback-spring.xml b/springboot-225-logback/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..7528994 --- /dev/null +++ b/springboot-225-logback/src/main/resources/logback-spring.xml @@ -0,0 +1,196 @@ + + + + + + + + + + logback + + + + + + + + + + + + + + + + + info + + + ${CONSOLE_LOG_PATTERN} + + UTF-8 + + + + + + + + + + ${log.path}/log_debug.log + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + ${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log + + 100MB + + + 15 + + + + debug + ACCEPT + DENY + + + + + + + ${log.path}/log_info.log + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + ${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log + + 100MB + + + 15 + + + + info + ACCEPT + DENY + + + + + + + ${log.path}/log_warn.log + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + ${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log + + 100MB + + + 15 + + + + warn + ACCEPT + DENY + + + + + + + + ${log.path}/log_error.log + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + ${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log + + 100MB + + + 15 + + + + ERROR + ACCEPT + DENY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/springboot-225-logback/src/test/java/com/example/springboot225logback/Springboot225LogbackApplicationTests.java b/springboot-225-logback/src/test/java/com/example/springboot225logback/Springboot225LogbackApplicationTests.java new file mode 100644 index 0000000..3abaf00 --- /dev/null +++ b/springboot-225-logback/src/test/java/com/example/springboot225logback/Springboot225LogbackApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225logback; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225LogbackApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 862ff02ff114b8417b1e3d22f960788afc39e868 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 7 Apr 2020 21:16:13 +0800 Subject: [PATCH 31/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88logback=E5=92=8Caop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/example/springboot225logback/aop/WebLogAspect.java | 2 +- .../src/main/resources/application.properties | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java b/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java index 4034940..d634923 100644 --- a/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java +++ b/springboot-225-logback/src/main/java/com/example/springboot225logback/aop/WebLogAspect.java @@ -25,7 +25,7 @@ public class WebLogAspect { private Logger logger = LoggerFactory.getLogger(WebLogAspect.class); - @Pointcut("execution(public * com.example.springboot225logback.*.*(..))") + @Pointcut("execution(public * com.example.springboot225logback.controller.*.*(..))") public void webLog(){} @Before("webLog()") diff --git a/springboot-225-logback/src/main/resources/application.properties b/springboot-225-logback/src/main/resources/application.properties index 68f053a..d61c65f 100644 --- a/springboot-225-logback/src/main/resources/application.properties +++ b/springboot-225-logback/src/main/resources/application.properties @@ -1,5 +1,5 @@ -spring.application.name=logback +spring.application.name=springboot-logback logging.config=classpath:logback-spring.xml -logging.file.path=D:/mylog/ -logging.file.name=${spring.application.name}/${spring.application.name}.log \ No newline at end of file +# 使用logback-spring.xml以后,就不需要下面的配置了 +#logging.file.name=D:/logs/${spring.application.name}.log \ No newline at end of file -- Gitee From 34dcea2ec3df4e689b123804ef052f50dda8ae75 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 8 Apr 2020 04:23:46 +0800 Subject: [PATCH 32/49] =?UTF-8?q?=E4=BC=98=E5=8C=96springboot2.2.5?= =?UTF-8?q?=E6=95=B4=E5=90=88MongoDB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/example/springboot225mongodb/Book.java | 4 ++++ .../example/springboot225mongodb/{entity => }/Customer.java | 2 +- .../springboot225mongodb/{dao => }/CustomerRepository.java | 3 +-- .../Springboot225MongodbApplicationTests.java | 2 -- 4 files changed, 6 insertions(+), 5 deletions(-) rename springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/{entity => }/Customer.java (91%) rename springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/{dao => }/CustomerRepository.java (73%) diff --git a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java index a63560b..3591578 100644 --- a/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java @@ -1,11 +1,15 @@ package com.example.springboot225mongodb; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import java.util.Date; @Data +@NoArgsConstructor +@AllArgsConstructor public class Book { @Id private String id; diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Customer.java similarity index 91% rename from springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java rename to springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Customer.java index a84a1e1..669db24 100644 --- a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/entity/Customer.java +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Customer.java @@ -1,4 +1,4 @@ -package com.example.springboot225mongodb.entity; +package com.example.springboot225mongodb; import org.springframework.data.annotation.Id; diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java similarity index 73% rename from springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java rename to springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java index b93be35..d0977b0 100644 --- a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/dao/CustomerRepository.java +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java @@ -1,6 +1,5 @@ -package com.example.springboot225mongodb.dao; +package com.example.springboot225mongodb; -import com.example.springboot225mongodb.entity.Customer; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java index 151ab58..39647af 100644 --- a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java @@ -1,7 +1,5 @@ package com.example.springboot225mongodb; -import com.example.springboot225mongodb.dao.CustomerRepository; -import com.example.springboot225mongodb.entity.Customer; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -- Gitee From 1a04eaff1a6e76b701088570139ea99d7ae855f5 Mon Sep 17 00:00:00 2001 From: zhuanghanghua <2356530443@qq.com> Date: Tue, 14 Apr 2020 08:33:01 +0800 Subject: [PATCH 33/49] =?UTF-8?q?Spring=20Boot=E9=A1=B9=E7=9B=AEapplicatio?= =?UTF-8?q?n.yml=E6=96=87=E4=BB=B6=E6=95=B0=E6=8D=AE=E5=BA=93=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=AF=86=E7=A0=81=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/pom.xml | 30 ++++++++++++++++ .../com/example/demo/xulian/JasyptTest.java | 36 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 demo/src/main/java/com/example/demo/xulian/JasyptTest.java diff --git a/demo/pom.xml b/demo/pom.xml index b67d5f1..3063075 100644 --- a/demo/pom.xml +++ b/demo/pom.xml @@ -16,6 +16,7 @@ 1.8 + 2.1.1 @@ -40,6 +41,35 @@ + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + ${jasypt.version} + + + + + junit + junit + 4.12 + + + + org.springframework + spring-test + 5.1.9.RELEASE + + + + javax.servlet + javax.servlet-api + 3.1.0 + + test + diff --git a/demo/src/main/java/com/example/demo/xulian/JasyptTest.java b/demo/src/main/java/com/example/demo/xulian/JasyptTest.java new file mode 100644 index 0000000..ae72922 --- /dev/null +++ b/demo/src/main/java/com/example/demo/xulian/JasyptTest.java @@ -0,0 +1,36 @@ +package com.example.demo.xulian; + +import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; +import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig; +import org.junit.Test; + +public class JasyptTest { + + + + @Test + public void testEncrypt() throws Exception { + StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); + EnvironmentPBEConfig config = new EnvironmentPBEConfig(); + + config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,这个算法是默认的 + config.setPassword("xulian"); // 加密的密钥 + standardPBEStringEncryptor.setConfig(config); + String plainText = "root"; + String encryptedText = standardPBEStringEncryptor.encrypt(plainText); + System.out.println(encryptedText); + } + + @Test + public void testDe() throws Exception { + StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); + EnvironmentPBEConfig config = new EnvironmentPBEConfig(); + + config.setAlgorithm("PBEWithMD5AndDES"); + config.setPassword("xulian"); + standardPBEStringEncryptor.setConfig(config); + String encryptedText = "wKfV+APkrQiB4bKwMkn9jLUgsUSlekKHZAwqQRt5w/k="; + String plainText = standardPBEStringEncryptor.decrypt(encryptedText); + System.out.println(plainText); + } +} -- Gitee From 7fecc853a2fb6a67d74b501a9b703bfe22b207a9 Mon Sep 17 00:00:00 2001 From: zhuanghanghua <2356530443@qq.com> Date: Tue, 14 Apr 2020 13:08:37 +0800 Subject: [PATCH 34/49] =?UTF-8?q?Spring=20Boot=E9=A1=B9=E7=9B=AEapplicatio?= =?UTF-8?q?n.yml=E6=96=87=E4=BB=B6=E6=95=B0=E6=8D=AE=E5=BA=93=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=AF=86=E7=A0=81=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/example/demo/{xulian => xuliankeji}/JasyptTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename demo/src/main/java/com/example/demo/{xulian => xuliankeji}/JasyptTest.java (97%) diff --git a/demo/src/main/java/com/example/demo/xulian/JasyptTest.java b/demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java similarity index 97% rename from demo/src/main/java/com/example/demo/xulian/JasyptTest.java rename to demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java index ae72922..0100f1d 100644 --- a/demo/src/main/java/com/example/demo/xulian/JasyptTest.java +++ b/demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java @@ -1,4 +1,4 @@ -package com.example.demo.xulian; +package com.example.demo.xuliankeji; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig; -- Gitee From 20703774c22f143e98c4ed87ebb24c83bdb40d9c Mon Sep 17 00:00:00 2001 From: zhuanghanghua <2356530443@qq.com> Date: Tue, 14 Apr 2020 13:09:16 +0800 Subject: [PATCH 35/49] =?UTF-8?q?Spring=20Boot=E9=A1=B9=E7=9B=AEapplicatio?= =?UTF-8?q?n.yml=E6=96=87=E4=BB=B6=E6=95=B0=E6=8D=AE=E5=BA=93=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=AF=86=E7=A0=81=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-001-demo/.gitignore | 32 ++ springboot-001-demo/mvnw | 310 ++++++++++++++++++ springboot-001-demo/mvnw.cmd | 182 ++++++++++ springboot-001-demo/pom.xml | 69 ++++ .../Springboot001DemoApplication.java | 13 + .../src/main/resources/application.properties | 1 + .../Springboot001DemoApplicationTests.java | 13 + .../xuliankeji/PigxAdminApplicationTest.java | 29 ++ 8 files changed, 649 insertions(+) create mode 100644 springboot-001-demo/.gitignore create mode 100644 springboot-001-demo/mvnw create mode 100644 springboot-001-demo/mvnw.cmd create mode 100644 springboot-001-demo/pom.xml create mode 100644 springboot-001-demo/src/main/java/com/example/springboot001demo/Springboot001DemoApplication.java create mode 100644 springboot-001-demo/src/main/resources/application.properties create mode 100644 springboot-001-demo/src/test/java/com/example/springboot001demo/Springboot001DemoApplicationTests.java create mode 100644 springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java diff --git a/springboot-001-demo/.gitignore b/springboot-001-demo/.gitignore new file mode 100644 index 0000000..7bd258a --- /dev/null +++ b/springboot-001-demo/.gitignore @@ -0,0 +1,32 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ +.mvn \ No newline at end of file diff --git a/springboot-001-demo/mvnw b/springboot-001-demo/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/springboot-001-demo/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-001-demo/mvnw.cmd b/springboot-001-demo/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/springboot-001-demo/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-001-demo/pom.xml b/springboot-001-demo/pom.xml new file mode 100644 index 0000000..0fa099b --- /dev/null +++ b/springboot-001-demo/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.example + springboot-001-demo + 0.0.1-SNAPSHOT + springboot-001-demo + Demo project for Spring Boot + + + 1.8 + 2.1.1 + + + + + org.springframework.boot + spring-boot-starter + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + ${jasypt.version} + + + org.springframework.security + spring-security-core + + + org.springframework.security.oauth + spring-security-oauth2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-001-demo/src/main/java/com/example/springboot001demo/Springboot001DemoApplication.java b/springboot-001-demo/src/main/java/com/example/springboot001demo/Springboot001DemoApplication.java new file mode 100644 index 0000000..e8b4027 --- /dev/null +++ b/springboot-001-demo/src/main/java/com/example/springboot001demo/Springboot001DemoApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot001demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot001DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot001DemoApplication.class, args); + } + +} diff --git a/springboot-001-demo/src/main/resources/application.properties b/springboot-001-demo/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/springboot-001-demo/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/springboot-001-demo/src/test/java/com/example/springboot001demo/Springboot001DemoApplicationTests.java b/springboot-001-demo/src/test/java/com/example/springboot001demo/Springboot001DemoApplicationTests.java new file mode 100644 index 0000000..fe61e8f --- /dev/null +++ b/springboot-001-demo/src/test/java/com/example/springboot001demo/Springboot001DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot001demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot001DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java b/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java new file mode 100644 index 0000000..19df781 --- /dev/null +++ b/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java @@ -0,0 +1,29 @@ +package com.example.springboot001demo.xuliankeji; + +import com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor; +import org.jasypt.encryption.StringEncryptor; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +public class PigxAdminApplicationTest { + @Autowired + private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); + @Test + public void testJasypt() { + // 对应application-dev.yml 中配置的根密码 + System.setProperty("jasypt.encryptor.password", "xulian"); + StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment()); + +// //加密方法 + System.out.println(stringEncryptor.encrypt("root")); + + //解密方法 + System.out.println(stringEncryptor.decrypt("O5EyX3/eaWCUorZ5Y8eSctsHp0A+L9qTYozwzGQWgps=")); + + System.out.println(ENCODER.encode("123")); + + } +} -- Gitee From a599aa27fc95f8382da2b8494068db1fc6fdda1b Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 15 Apr 2020 10:02:08 +0800 Subject: [PATCH 36/49] =?UTF-8?q?Spring=20Boot=E9=A1=B9=E7=9B=AEapplicatio?= =?UTF-8?q?n.yml=E6=96=87=E4=BB=B6=E6=95=B0=E6=8D=AE=E5=BA=93=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=AF=86=E7=A0=81=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../springboot001demo/xuliankeji/PigxAdminApplicationTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java b/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java index 19df781..1494db1 100644 --- a/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java +++ b/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java @@ -8,6 +8,9 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +/** + * application.yml文件中数据库密码,使用jasypt加密 + */ public class PigxAdminApplicationTest { @Autowired private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder(); -- Gitee From 0882792682f2b54e5f6f049fe1c6e67b6d396790 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 14 May 2020 14:58:01 +0800 Subject: [PATCH 37/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=8C=E6=95=B4=E5=90=88=E9=98=BF=E9=87=8C=E4=BA=91=E7=89=A9?= =?UTF-8?q?=E8=81=94=E7=BD=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring-boot-starter-demo | 1 - springboot-001-demo/pom.xml | 1 + springboot-225-aliiot/.gitignore | 31 ++ springboot-225-aliiot/pom.xml | 199 ++++++++ .../AmqpJavaClientDemo.java | 184 +++++++ .../springboot225aliiot/GatewayRunner.java | 51 ++ .../Springboot225AliiotApplication.java | 15 + .../ali/DeviceService.java | 5 + .../ali/MessageCommunicationService.java | 8 + .../ali/OTAFirmwareService.java | 40 ++ .../ali/ProductService.java | 33 ++ .../ali/impl/DeviceServiceImpl.java | 6 + .../impl/MessageCommunicationServiceImpl.java | 51 ++ .../ali/impl/OTAFirmwareServiceImpl.java | 447 ++++++++++++++++++ .../ali/impl/ProductServiceImpl.java | 176 +++++++ .../config/AliIOTConfig.java | 45 ++ .../config/Swagger2Config.java | 35 ++ .../MessageCommunicationController.java | 36 ++ .../controller/OTAFirmwareController.java | 367 ++++++++++++++ .../controller/PopPubController.java | 26 + .../controller/ProductController.java | 49 ++ .../query/ProductQuery.java | 14 + .../service/DevicePubService.java | 11 + .../service/DeviceSubService.java | 11 + .../service/PopPubService.java | 50 ++ .../service/PopSubService.java | 186 ++++++++ .../src/main/resources/application.yml | 8 + .../springboot225aliiot/IOTTest01.java | 42 ++ .../springboot225aliiot/IOTTest02.java | 34 ++ .../Springboot225AliiotApplicationTests.java | 159 +++++++ .../example/springboot225aliiot/Test01.java | 7 + .../ali/impl/ProductServiceImplTest.java | 19 + .../controller/ProductControllerTest.java | 13 + .../CloudSendInstruction.java" | 50 ++ .../AmqpJavaClientDemo.java" | 186 ++++++++ .../AmqpJavaClientDemo.java" | 160 +++++++ .../LinkkitPubClient.java" | 80 ++++ .../LinkkitSubClient.java" | 102 ++++ .../PopPubServer.java" | 39 ++ .../AmqpJavaClientDemo.java" | 165 +++++++ 40 files changed, 3141 insertions(+), 1 deletion(-) delete mode 160000 spring-boot-starter-demo create mode 100644 springboot-225-aliiot/.gitignore create mode 100644 springboot-225-aliiot/pom.xml create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/AmqpJavaClientDemo.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/GatewayRunner.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/Springboot225AliiotApplication.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/DeviceService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/MessageCommunicationService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/OTAFirmwareService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/ProductService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/DeviceServiceImpl.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/MessageCommunicationServiceImpl.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/OTAFirmwareServiceImpl.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/ProductServiceImpl.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/AliIOTConfig.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/Swagger2Config.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/MessageCommunicationController.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/OTAFirmwareController.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/PopPubController.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/ProductController.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/query/ProductQuery.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DevicePubService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DeviceSubService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopPubService.java create mode 100644 springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopSubService.java create mode 100644 springboot-225-aliiot/src/main/resources/application.yml create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest01.java create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest02.java create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Springboot225AliiotApplicationTests.java create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Test01.java create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/ali/impl/ProductServiceImplTest.java create mode 100644 springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/controller/ProductControllerTest.java create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\272\221\347\253\257\344\270\213\345\217\221\346\214\207\344\273\244/CloudSendInstruction.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250AMQP\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205/AmqpJavaClientDemo.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/AmqpJavaClientDemo.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitPubClient.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitSubClient.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/PopPubServer.java" create mode 100644 "springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205\350\256\276\345\244\207\346\266\210\346\201\257/AmqpJavaClientDemo.java" diff --git a/spring-boot-starter-demo b/spring-boot-starter-demo deleted file mode 160000 index 21bc5ce..0000000 --- a/spring-boot-starter-demo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 21bc5ce38b11ed245fd0d262494b853c9b3484a3 diff --git a/springboot-001-demo/pom.xml b/springboot-001-demo/pom.xml index 0fa099b..2e74946 100644 --- a/springboot-001-demo/pom.xml +++ b/springboot-001-demo/pom.xml @@ -54,6 +54,7 @@ org.springframework.security.oauth spring-security-oauth2 + 2.4.0.RELEASE diff --git a/springboot-225-aliiot/.gitignore b/springboot-225-aliiot/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/springboot-225-aliiot/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-aliiot/pom.xml b/springboot-225-aliiot/pom.xml new file mode 100644 index 0000000..fd8eb0a --- /dev/null +++ b/springboot-225-aliiot/pom.xml @@ -0,0 +1,199 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.example + springboot-225-aliiot + 0.0.1-SNAPSHOT + springboot-225-aliiot + Demo project for Spring Boot + + + 1.8 + 2.9.2 + 1.4.0 + + + + + + + pro.nbbt + nbbt-base + 1.0.17 + + + pro.nbbt + nbbt-data + 1.0.7 + + + pro.nbbt + nbbt-web + 1.0.16-beta4 + + + + + + + pro.nbbt + nbbt-base + + + pro.nbbt + nbbt-data + + + pro.nbbt + nbbt-web + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + io.projectreactor + reactor-test + test + + + + + + com.aliyun + aliyun-java-sdk-iot + 7.6.0 + + + + com.aliyun + aliyun-java-sdk-core + 4.5.1 + + + + com.aliyun.alink.linksdk + iot-linkkit-java + 1.2.0.1 + compile + + + + com.aliyun.openservices + iot-client-message + 1.1.2 + + + + + + org.apache.qpid + qpid-jms-client + 0.47.0 + + + + commons-codec + commons-codec + 1.10 + + + + + com.alibaba + fastjson + 1.2.62 + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + + + junit + junit + 4.13 + test + + + + + org.apache.kafka + kafka_2.13 + 2.4.1 + + + + + org.apache.shiro + shiro-spring-boot-starter + ${shiro.version} + + + org.apache.shiro + shiro-ehcache + ${shiro.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/AmqpJavaClientDemo.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/AmqpJavaClientDemo.java new file mode 100644 index 0000000..70c16cd --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/AmqpJavaClientDemo.java @@ -0,0 +1,184 @@ +package com.example.springboot225aliiot; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.InetAddress; +import java.net.URI; +import java.util.Hashtable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * 服务端订阅设备消息 + */ +@Service +public class AmqpJavaClientDemo { + private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class); + + @Resource + private AliIOTConfig aliIOTConfig; + + //业务处理异步线程池,线程池参数可以根据您的业务特点调整;或者您也可以用其他异步方式处理接收到的消息 + private final static ExecutorService executorService = new ThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(50000)); + + public void amqpJavaClientDemo() throws Exception { + //参数说明,请参见上一篇文档:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); +// String iotInstanceId = "${iotInstanceId}"; + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = InetAddress.getLocalHost().getHostAddress(); + + //UserName组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey +// + ",iotInstanceId=" + iotInstanceId //如果是购买的实例,需要传实例ID + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 + String connectionUrl = "failover:(amqps://"+aliIOTConfig.getUid()+".iot-amqp."+"cn-shanghai"+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + // 必须要sleep一下,不然程序执行的太快,来不及消费 设备发送过来的消息;或者实现CommandLineRunner +// Thread.sleep(600000); + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + //1.收到消息之后一定要ACK + // 推荐做法:创建Session选择Session.AUTO_ACKNOWLEDGE,这里会自动ACK。 + // 其他做法:创建Session选择Session.CLIENT_ACKNOWLEDGE,这里一定要调message.acknowledge()来ACK。 + // message.acknowledge(); + //2.建议异步处理收到的消息,确保onMessage函数里没有耗时逻辑。 + // 如果业务处理耗时过程过长阻塞住线程,可能会影响SDK收到消息后的正常回调。 + executorService.submit(() -> processMessage(message)); + } catch (Exception e) { + logger.error("submit task occurs exception ", e); + } + } + }; + + /** + * 在这里处理您收到消息后的具体业务逻辑。 + */ + private static void processMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = body==null?"":new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + } catch (Exception e) { + logger.error("processMessage occurs error ", e); + } + } + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见上一篇文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/GatewayRunner.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/GatewayRunner.java new file mode 100644 index 0000000..649d675 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/GatewayRunner.java @@ -0,0 +1,51 @@ +package com.example.springboot225aliiot; + +import com.example.springboot225aliiot.service.PopSubService; +import lombok.extern.log4j.Log4j2; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + + +/** + * 入口 + * @author linyibeng + * @date 2018-10-12 09:51 + */ +@Component +@Log4j2 +public class GatewayRunner implements CommandLineRunner { + private final static Logger logger = LoggerFactory.getLogger(GatewayRunner.class); + + @Resource + private PopSubService popSubService; + + @Override + public void run(String... args) throws Exception { + System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<"); + // 服务端订阅 + popSubService.popSubService(); + } + + // ====================初始化网关===================== + + + + + + + + // ====================结束初始化网关===================== + // ====================从数据库读取配置===================== + + + + + // ====================结束从数据库读取配置===================== + + + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/Springboot225AliiotApplication.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/Springboot225AliiotApplication.java new file mode 100644 index 0000000..7409862 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/Springboot225AliiotApplication.java @@ -0,0 +1,15 @@ +package com.example.springboot225aliiot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com") +public class Springboot225AliiotApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225AliiotApplication.class, args); + } + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/DeviceService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/DeviceService.java new file mode 100644 index 0000000..d0ee123 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/DeviceService.java @@ -0,0 +1,5 @@ +package com.example.springboot225aliiot.ali; + +public interface DeviceService { + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/MessageCommunicationService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/MessageCommunicationService.java new file mode 100644 index 0000000..9730884 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/MessageCommunicationService.java @@ -0,0 +1,8 @@ +package com.example.springboot225aliiot.ali; + +import com.alibaba.fastjson.JSONObject; + +public interface MessageCommunicationService { + + JSONObject RRpc(String deviceName, String productKey, String requestBase64Byte, Integer timeout, String iotInstanceId, String topic); +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/OTAFirmwareService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/OTAFirmwareService.java new file mode 100644 index 0000000..fd99b2e --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/OTAFirmwareService.java @@ -0,0 +1,40 @@ +package com.example.springboot225aliiot.ali; + +import com.alibaba.fastjson.JSONObject; + +import java.util.List; + +public interface OTAFirmwareService { + JSONObject GenerateOTAUploadURL(String IotInstanceId); + + JSONObject CreateOTAFirmware(String destVersion, String firmwareName, String firmwareUrl, String iotInstanceId, String firmwareSign, String signMethod, + String firmwareSize, String productKey, String firmwareDesc, String type, String srcVersion, String moduleName); + + JSONObject DeleteOTAFirmware(String firmwareId, String iotInstanceId); + + JSONObject ListOTAFirmware(Integer currentPage, Integer pageSize, String iotInstanceId, String productKey, String destVersion); + + JSONObject QueryOTAFirmware(String firmwareId, String iotInstanceId); + + JSONObject CreateOTAVerifyJob(String firmwareId, String productKey, List targetDeviceName, String iotInstanceId, String timeoutInMinutes); + + JSONObject CreateOTAStaticUpgradeJob(String firmwareId, String productKey, String targetSelection, String iotInstanceId, List srcVersion, + Long scheduleTime, Integer retryInterval, Integer retryCount, Integer timeoutInMinutes, Integer maximumPerMinute, + String grayPercent, List targetDeviceName); + + JSONObject CreateOTADynamicUpgradeJob(String firmwareId, String productKey, String iotInstanceId, List srcVersion, Integer retryInterval, Integer retryCount, Integer timeoutInMinutes, Integer maximumPerMinute); + + JSONObject ListOTAJobByFirmware(Integer currentPage, String firmwareId, Integer pageSize, String iotInstanceId); + + JSONObject ListOTAJobByDevice(Integer currentPage, String deviceName, String firmwareId, Integer pageSize, String productKey, String iotInstanceId); + + JSONObject QueryOTAJob(String jobId, String iotInstanceId); + + JSONObject CancelOTAStrategyByJob(String jobId, String iotInstanceId); + + JSONObject CancelOTATaskByDevice(List deviceName, String firmwareId, String productKey, String iotInstanceId, String jobId); + + JSONObject CancelOTATaskByJob(String jobId, String iotInstanceId, Boolean cancelScheduledTask, Boolean cancelQueuedTask, Boolean cancelInProgressTask, Boolean cancelNotifiedTask); + + JSONObject ListOTATaskByJob(Integer currentPage, String jobId, Integer pageSize, String iotInstanceId, String taskStatus); +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/ProductService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/ProductService.java new file mode 100644 index 0000000..cb082d3 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/ProductService.java @@ -0,0 +1,33 @@ +package com.example.springboot225aliiot.ali; + +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225aliiot.query.ProductQuery; + +public interface ProductService { + // 创建产品 + JSONObject createProduct(ProductQuery productQuery); + // 查询产品 + JSONObject queryProduct(String productKey); + // 查询产品列表 + JSONObject queryProductList(String PageSize,String CurrentPage); + // 更新产品 + JSONObject updateProduct(String ProductName,String ProductKey); + // 删除产品 + JSONObject deleteProduct(String ProductKey); + // 创建产品标签 + JSONObject createProductTags(); + // 更新产品标签 + JSONObject updateProductTags(); + // 删除产品标签 + JSONObject deleteProductTags(); + // 查询产品标签列表 + JSONObject listProductTags(); + // 根据产品标签 查询产品列表 + JSONObject listProductByTags(); + // 获取产品的X.509证书信息 + JSONObject queryProductCertInfo(); + // 设置产品的X.509证书信息 + JSONObject setProductCertInfo(); + // 更新产品下设备上报属性消息的去重规则 + JSONObject updateProductFilterConfig(); +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/DeviceServiceImpl.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/DeviceServiceImpl.java new file mode 100644 index 0000000..240e0ff --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/DeviceServiceImpl.java @@ -0,0 +1,6 @@ +package com.example.springboot225aliiot.ali.impl; + +import com.example.springboot225aliiot.ali.DeviceService; + +public class DeviceServiceImpl implements DeviceService { +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/MessageCommunicationServiceImpl.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/MessageCommunicationServiceImpl.java new file mode 100644 index 0000000..55e3526 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/MessageCommunicationServiceImpl.java @@ -0,0 +1,51 @@ +package com.example.springboot225aliiot.ali.impl; + +import com.alibaba.fastjson.JSONObject; +import com.aliyuncs.CommonRequest; +import com.aliyuncs.CommonResponse; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.exceptions.ServerException; +import com.aliyuncs.http.MethodType; +import com.aliyuncs.profile.DefaultProfile; +import com.example.springboot225aliiot.ali.MessageCommunicationService; +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class MessageCommunicationServiceImpl implements MessageCommunicationService { + @Resource + private AliIOTConfig aliIOTConfig; + + @Override + public JSONObject RRpc(String deviceName, String productKey, String requestBase64Byte, Integer timeout, String iotInstanceId, String topic) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("RRpc"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("DeviceName", deviceName); + request.putQueryParameter("Timeout", String.valueOf(timeout)); + request.putQueryParameter("RequestBase64Byte", requestBase64Byte); + request.putQueryParameter("ProductKey", productKey); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("Topic", topic); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/OTAFirmwareServiceImpl.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/OTAFirmwareServiceImpl.java new file mode 100644 index 0000000..2d0e806 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/OTAFirmwareServiceImpl.java @@ -0,0 +1,447 @@ +package com.example.springboot225aliiot.ali.impl; + +import com.alibaba.fastjson.JSONObject; +import com.aliyuncs.CommonRequest; +import com.aliyuncs.CommonResponse; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.exceptions.ServerException; +import com.aliyuncs.http.MethodType; +import com.aliyuncs.profile.DefaultProfile; +import com.example.springboot225aliiot.ali.OTAFirmwareService; +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service +public class OTAFirmwareServiceImpl implements OTAFirmwareService { + @Resource + private AliIOTConfig aliIOTConfig; + + @Override + public JSONObject GenerateOTAUploadURL(String IotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("GenerateOTAUploadURL"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CreateOTAFirmware(String destVersion, String firmwareName, String firmwareUrl, String iotInstanceId, String firmwareSign, String signMethod, String firmwareSize, String productKey, String firmwareDesc, String type, String srcVersion, String moduleName) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CreateOTAFirmware"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("DestVersion", destVersion); + request.putQueryParameter("FirmwareUrl", firmwareUrl); + request.putQueryParameter("FirmwareName", firmwareName); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("FirmwareSign", firmwareSign); + request.putQueryParameter("SignMethod", signMethod); + request.putQueryParameter("FirmwareSize", firmwareSize); + request.putQueryParameter("ProductKey", productKey); + request.putQueryParameter("FirmwareDesc", firmwareDesc); + request.putQueryParameter("Type", type); + request.putQueryParameter("SrcVersion", srcVersion); + request.putQueryParameter("ModuleName", moduleName); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject DeleteOTAFirmware(String firmwareId, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain("iot.cn-shanghai.aliyuncs.com"); + request.setSysVersion("2018-01-20"); + request.setSysAction("DeleteOTAFirmware"); + request.putQueryParameter("RegionId", "cn-hangzhou"); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject ListOTAFirmware(Integer currentPage, Integer pageSize, String iotInstanceId, String productKey, String destVersion) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("ListOTAFirmware"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("CurrentPage", String.valueOf(currentPage)); + request.putQueryParameter("PageSize", String.valueOf(pageSize)); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("ProductKey", productKey); + request.putQueryParameter("DestVersion", destVersion); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject QueryOTAFirmware(String firmwareId, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("QueryOTAFirmware"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CreateOTAVerifyJob(String firmwareId, String productKey, List targetDeviceName, String iotInstanceId, String timeoutInMinutes) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CreateOTAVerifyJob"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("ProductKey", productKey); + for (int i = 0;i < targetDeviceName.size();i++){ + request.putQueryParameter("TargetDeviceName."+(i+1), targetDeviceName.get(i)); + } + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("TimeoutInMinutes", timeoutInMinutes); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CreateOTAStaticUpgradeJob(String firmwareId, String productKey, String targetSelection, String iotInstanceId, List srcVersion, Long scheduleTime, Integer retryInterval, Integer retryCount, Integer timeoutInMinutes, Integer maximumPerMinute, String grayPercent, List targetDeviceName) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CreateOTAStaticUpgradeJob"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("ProductKey", productKey); + request.putQueryParameter("TargetSelection", targetSelection); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + for (int i = 0; i < srcVersion.size(); i++) { + request.putQueryParameter("SrcVersion."+(i+1), srcVersion.get(i)); + } + request.putQueryParameter("ScheduleTime", String.valueOf(scheduleTime)); + request.putQueryParameter("RetryInterval", String.valueOf(retryInterval)); + request.putQueryParameter("RetryCount", String.valueOf(retryCount)); + request.putQueryParameter("TimeoutInMinutes", String.valueOf(timeoutInMinutes)); + request.putQueryParameter("MaximumPerMinute", String.valueOf(maximumPerMinute)); + request.putQueryParameter("GrayPercent", grayPercent); + for (int i = 0; i < targetDeviceName.size(); i++) { + request.putQueryParameter("TargetDeviceName."+(i+1), targetDeviceName.get(i)); + } + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CreateOTADynamicUpgradeJob(String firmwareId, String productKey, String iotInstanceId, List srcVersion, Integer retryInterval, Integer retryCount, Integer timeoutInMinutes, Integer maximumPerMinute) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CreateOTADynamicUpgradeJob"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("ProductKey", productKey); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + for (int i = 0; i < srcVersion.size(); i++) { + request.putQueryParameter("SrcVersion."+(i+1), srcVersion.get(i)); + } + request.putQueryParameter("RetryInterval", String.valueOf(retryInterval)); + request.putQueryParameter("RetryCount", String.valueOf(retryCount)); + request.putQueryParameter("TimeoutInMinutes", String.valueOf(timeoutInMinutes)); + request.putQueryParameter("MaximumPerMinute", String.valueOf(maximumPerMinute)); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject ListOTAJobByFirmware(Integer currentPage, String firmwareId, Integer pageSize, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("listOTAJobByFirmware"); + request.putQueryParameter("PageSize", String.valueOf(pageSize)); + request.putQueryParameter("CurrentPage", String.valueOf(currentPage)); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject ListOTAJobByDevice(Integer currentPage, String deviceName, String firmwareId, Integer pageSize, String productKey, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("ListOTAJobByDevice"); + request.putQueryParameter("PageSize", String.valueOf(pageSize)); + request.putQueryParameter("ProductKey", String.valueOf(productKey)); + request.putQueryParameter("DeviceName", deviceName); + request.putQueryParameter("CurrentPage", String.valueOf(currentPage)); + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject QueryOTAJob(String jobId, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("QueryOTAJob"); + request.putQueryParameter("JobId", jobId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CancelOTAStrategyByJob(String jobId, String iotInstanceId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CancelOTAStrategyByJob"); + request.putQueryParameter("JobId", jobId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CancelOTATaskByDevice(List deviceName, String firmwareId, String productKey, String iotInstanceId, String jobId) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CancelOTATaskByDevice"); + request.putQueryParameter("ProductKey", productKey); + for (int i = 0; i < deviceName.size(); i++) { + request.putQueryParameter("DeviceName."+(i+1), deviceName.get(i)); + } + request.putQueryParameter("FirmwareId", firmwareId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("JobId", jobId); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject CancelOTATaskByJob(String jobId, String iotInstanceId, Boolean cancelScheduledTask, Boolean cancelQueuedTask, Boolean cancelInProgressTask, Boolean cancelNotifiedTask) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CancelOTATaskByJob"); + request.putQueryParameter("JobId", jobId); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("CancelScheduledTask", String.valueOf(cancelScheduledTask)); + request.putQueryParameter("CancelQueuedTask", String.valueOf(cancelQueuedTask)); + request.putQueryParameter("CancelInProgressTask", String.valueOf(cancelInProgressTask)); + request.putQueryParameter("CancelNotifiedTask", String.valueOf(cancelNotifiedTask)); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject ListOTATaskByJob(Integer currentPage, String jobId, Integer pageSize, String iotInstanceId, String taskStatus) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("ListOTATaskByJob"); + request.putQueryParameter("JobId", jobId); + request.putQueryParameter("CurrentPage", String.valueOf(currentPage)); + request.putQueryParameter("PageSize", String.valueOf(pageSize)); + request.putQueryParameter("IotInstanceId", iotInstanceId); + request.putQueryParameter("TaskStatus", taskStatus); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/ProductServiceImpl.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/ProductServiceImpl.java new file mode 100644 index 0000000..04761ef --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/ali/impl/ProductServiceImpl.java @@ -0,0 +1,176 @@ +package com.example.springboot225aliiot.ali.impl; + +import com.alibaba.fastjson.JSONObject; +import com.aliyuncs.CommonRequest; +import com.aliyuncs.CommonResponse; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.http.MethodType; +import com.aliyuncs.profile.DefaultProfile; +import com.example.springboot225aliiot.ali.ProductService; +import com.example.springboot225aliiot.config.AliIOTConfig; +import com.example.springboot225aliiot.query.ProductQuery; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class ProductServiceImpl implements ProductService { + + @Resource + private AliIOTConfig aliIOTConfig; + + @Override + public JSONObject createProduct(ProductQuery productQuery){ + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("CreateProduct"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("NodeType", productQuery.getNodeType()); + request.putQueryParameter("ProductName", productQuery.getProductName()); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject queryProduct(String productKey) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("QueryProduct"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("ProductKey", productKey); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject queryProductList(String PageSize,String CurrentPage) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("QueryProductList"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("PageSize", PageSize); + request.putQueryParameter("CurrentPage", CurrentPage); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject updateProduct(String ProductName,String ProductKey) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("UpdateProduct"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("ProductName", ProductName); + request.putQueryParameter("ProductKey", ProductKey); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject deleteProduct(String ProductKey) { + DefaultProfile profile = DefaultProfile.getProfile(aliIOTConfig.getRegionId(), aliIOTConfig.getAccessKey(), aliIOTConfig.getAccessSecret()); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setSysMethod(MethodType.POST); + request.setSysDomain(aliIOTConfig.getDomain()); + request.setSysVersion("2018-01-20"); + request.setSysAction("DeleteProduct"); + request.putQueryParameter("RegionId", aliIOTConfig.getRegionId()); + request.putQueryParameter("ProductKey", ProductKey); + CommonResponse response = new CommonResponse(); + try { + response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ClientException e) { + e.printStackTrace(); + } + return JSONObject.parseObject(response.getData()); + } + + @Override + public JSONObject createProductTags() { + return null; + } + + @Override + public JSONObject updateProductTags() { + return null; + } + + @Override + public JSONObject deleteProductTags() { + return null; + } + + @Override + public JSONObject listProductTags() { + return null; + } + + @Override + public JSONObject listProductByTags() { + return null; + } + + @Override + public JSONObject queryProductCertInfo() { + return null; + } + + @Override + public JSONObject setProductCertInfo() { + return null; + } + + @Override + public JSONObject updateProductFilterConfig() { + return null; + } + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/AliIOTConfig.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/AliIOTConfig.java new file mode 100644 index 0000000..5240a85 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/AliIOTConfig.java @@ -0,0 +1,45 @@ +package com.example.springboot225aliiot.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "ali.iot") +@Data +public class AliIOTConfig { + /** + * 产品名称 + */ + private String name; + /** + * accessKey + */ + private String accessKey; + /** + * accessSecret + */ + private String accessSecret; + /** + * uid + */ + private String uid; + /** + * regionId + */ + private String regionId; + /** + * product的类型 + */ + private String product; + /** + * domain + */ + private String domain; + + /** + * AMQP 服务端订阅 消费组Id + * consumerGroupId + */ + private String consumerGroupId; +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/Swagger2Config.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/Swagger2Config.java new file mode 100644 index 0000000..13ef9ff --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/config/Swagger2Config.java @@ -0,0 +1,35 @@ +package com.example.springboot225aliiot.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 // 启用Swagger2 +public class Swagger2Config { + @Bean + public Docket createRestApi() {// 创建API基本信息 + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build(); + } + + @SuppressWarnings("deprecation") + private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示 + return new ApiInfoBuilder() + .title("维科新能源-阿里网关接口API")// API 标题 + .description("维科新能源-阿里网关接口API")// API描述 + .contact("nbbt@")// 联系人 + .version("1.0")// 版本号 + .build(); + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/MessageCommunicationController.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/MessageCommunicationController.java new file mode 100644 index 0000000..1cd09ce --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/MessageCommunicationController.java @@ -0,0 +1,36 @@ +package com.example.springboot225aliiot.controller; + +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225aliiot.ali.MessageCommunicationService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping(value = "/MessageCommunication") +@Api(description = "阿里云物联网平台-消息通信相关API") +public class MessageCommunicationController { + @Resource + private MessageCommunicationService messageCommunicationService; + + @PostMapping(value = "/RRpc") + @ApiOperation(value = "发消息给设备,并同步返回响应") + public JSONObject RRpc( + @ApiParam(value = "要接收消息的设备名称。",required = true) @RequestParam(required = true) String DeviceName, + @ApiParam(value = "要发送消息的产品Key。",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "要发送的消息内容经过Base64编码得到的字符串格式数据,例如dGhpcyBpcyBhbiBleGFtcGxl。",required = true) @RequestParam(required = true) String RequestBase64Byte, + @ApiParam(value = "等待设备回复消息的时间,单位是毫秒,取值范围是1,000 ~8,000。",required = true,example = "1000") @RequestParam(required = true) Integer Timeout, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "使用自定义的RRPC相关Topic。需要设备端配合使用,请参见设备端开发自定义Topic。\n" + + "\n" + + "不传入此参数,则使用系统默认的RRPC Topic。",required = false) @RequestParam(required = false) String Topic + ){ + return messageCommunicationService.RRpc(DeviceName,ProductKey,RequestBase64Byte,Timeout,IotInstanceId,Topic); + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/OTAFirmwareController.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/OTAFirmwareController.java new file mode 100644 index 0000000..1129299 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/OTAFirmwareController.java @@ -0,0 +1,367 @@ +package com.example.springboot225aliiot.controller; + +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225aliiot.ali.OTAFirmwareService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import java.util.List; + +@RestController +@RequestMapping(value = "/OTAFirmware") +@Api(description = "阿里云物联网平台-固件升级相关API") +public class OTAFirmwareController { + @Resource + private OTAFirmwareService otaFirmwareService; + + @PostMapping(value = "/GenerateOTAUploadURL") + @ApiOperation(value = "生成固件文件的上传对象存储的信息") + public JSONObject GenerateOTAUploadURL( + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.GenerateOTAUploadURL(IotInstanceId); + } + + @PostMapping(value = "/CreateOTAFirmware") + @ApiOperation(value = "创建固件") + public JSONObject CreateOTAFirmware( + @ApiParam(value = "当前固件的版本号,仅支持英文字母、数字、点号(.)、连字符(-)和下划线(_)。长度限制为1~64字符。",required = true)@RequestParam String DestVersion, + @ApiParam(value = "固件名称,仅支持中文汉字、英文字母、数字和下划线(_),且不能以下划线(_)开头。长度限制为4~32字符。",required = true)@RequestParam String FirmwareName, + @ApiParam(value = "固件的URL,即固件文件在对象存储(OSS)上的存储地址。调用GenerateOTAUploadURL生成固件上传信息,返回的参数。",required = true)@RequestParam String FirmwareUrl, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。")@RequestParam(required = false)String IotInstanceId, + @ApiParam(value = "固件签名值。使用SignMethod对固件文件内容加签计算得出的值。不传入此参数,则采用对象存储(OSS)中固件文件的MD5值作为固件签名值。")@RequestParam(required = false)String FirmwareSign, + @ApiParam(value = "固件签名方法。目前仅支持取值为MD5:MD5签名。不传入此参数,默认为MD5。")@RequestParam(required = false)String SignMethod, + @ApiParam(value = "固件大小,单位:字节。不传入此参数,则采用对象存储(OSS)中固件文件的大小作为固件大小。")@RequestParam(required = false)String FirmwareSize, + @ApiParam(value = "固件所属产品的ProductKey。",required = true)@RequestParam String ProductKey, + @ApiParam(value = "固件描述。长度不可超过100字符。一个中文汉字算一个字符。")@RequestParam(required = false)String FirmwareDesc, + @ApiParam(value = "固件类型。可选:0:整包固件,您上传的固件文件包含完整的固件,将推送整包固件给设备进行升级。" + + "1:差分固件,您上传的固件文件仅包含新版本固件与之前版本的差异部分,仅推送差异部分给设备进行升级。" + + "不传入此参数,则默认值为0:整包固件。")@RequestParam(required = false)String Type, + @ApiParam(value = "待升级的固件版本号,即待升级设备的现有固件版本号。可以调用QueryDeviceDetail,查看设备固件版本号(FirmwareVersion)。")@RequestParam(required = false)String SrcVersion, + @ApiParam(name = "ModuleName",value = "固件模块名称。仅支持英文字母、数字、点号、连字符(-)和下划线(_)。长度限制为1~64字符。" + + "固件模块用于区分同产品下设备的不同模块的升级。")@RequestParam(required = false)String ModuleName + ){ + return otaFirmwareService.CreateOTAFirmware(DestVersion,FirmwareName,FirmwareUrl,IotInstanceId,FirmwareSign,SignMethod,FirmwareSize, + ProductKey,FirmwareDesc,Type,SrcVersion,ModuleName); + } + + @PostMapping(value = "/DeleteOTAFirmware") + @ApiOperation(value = "删除指定固件") + public JSONObject DeleteOTAFirmware( + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.DeleteOTAFirmware(FirmwareId,IotInstanceId); + } + + @PostMapping(value = "/ListOTAFirmware") + @ApiOperation(value = "查询固件列表") + public JSONObject ListOTAFirmware( + @ApiParam(value = "指定从返回结果中的第几页开始显示。页数从1开始排序。",required = true,example = "1") @RequestParam(required = true,defaultValue = "1") Integer CurrentPage, + @ApiParam(value = "指定返回结果中每页显示的固件数量。最大限制为100。",required = true,example = "100") @RequestParam(required = true,defaultValue = "10") Integer PageSize, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "固件所属产品的ProductKey。传入该参数,则查询指定产品下的固件列表;不传入此参数,则返回当前阿里云账号下的所有固件列表。",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "固件版本号。传入该参数,则查询版本号为指定版本号的固件。",required = false) @RequestParam(required = false) String DestVersion + ){ + return otaFirmwareService.ListOTAFirmware(CurrentPage,PageSize,IotInstanceId,ProductKey,DestVersion); + } + + @PostMapping(value = "/QueryOTAFirmware") + @ApiOperation(value = "查询指定固件的详细信息") + public JSONObject QueryOTAFirmware( + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.QueryOTAFirmware(FirmwareId,IotInstanceId); + } + + @PostMapping(value = "/CreateOTAVerifyJob") + @ApiOperation(value = "创建固件验证批次") + public JSONObject CreateOTAVerifyJob( + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "固件所属产品的ProductKey",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "待验证的设备。\n" + + "\n" + + "说明\n" + + "设备所属产品必须与固件所属产品一致。\n" + + "设备名称不能重复。\n" + + "最多可传入10个设备名称。",required = true) @RequestParam(required = true) List TargetDeviceName, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "设置设备升级超时时间,单位分钟。范围1~1,440。",required = false) @RequestParam(required = false) String TimeoutInMinutes + ){ + return otaFirmwareService.CreateOTAVerifyJob(FirmwareId,ProductKey,TargetDeviceName,IotInstanceId,TimeoutInMinutes); + } + + @PostMapping(value = "/CreateOTAStaticUpgradeJob") + @ApiOperation(value = "创建静态批量升级批次") + public JSONObject CreateOTAStaticUpgradeJob( + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "固件所属产品的ProductKey",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "升级范围。\n" + + "\n" + + "ALL:全量升级。\n" + + "SPECIFIC:定向升级。\n" + + "GRAY:灰度升级。",required = true) @RequestParam(required = true) String TargetSelection, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "待升级的固件版本号列表。\n" + + "\n" + + "可以调用QueryDeviceDetail,查看设备固件版本号FirmwareVersion。\n" + + "\n" + + "说明\n" + + "发起全量升级(TargetSelection=ALL)和灰度升级(TargetSelection=GRAY)任务时,需传入该参数,且不能传入TargetDeviceNames参数。\n" + + "发起定向升级(TargetSelection=SPECIFIC)任务时,不能传入该参数。\n" + + "使用差分固件发起全量升级和灰度升级任务时,该参数值需指定为差分固件的待升级版本号(SrcVersion)。\n" + + "列表中不能有重复的版本号。\n" + + "最多可传入10个版本号。",required = false,example = "1.0.0,1.0.1") @RequestParam(required = false) List SrcVersion, + @ApiParam(value = "指定发起固件升级的时间。\n" + + "\n" + + "定时时间范围需为当前时间的5分钟后~7天内。取值为13位毫秒值时间戳,例如,1577808000000。\n" + + "\n" + + "不传入该参数,则表示立即升级。",required = false,example = "1577808000000") @RequestParam(required = false) Long ScheduleTime, + @ApiParam(value = "设备升级失败后,自动重试的时间间隔,单位:分钟。可选值:\n" + + "\n" + + "0:立即重试。\n" + + "10:10分钟后重试。\n" + + "30:30分钟后重试。\n" + + "60:60分钟(即1小时)后重试。\n" + + "1440:1,440分钟(即24小时)后重试。\n" + + "不传入此参数,则表示不重试。",required = false,example = "1440") @RequestParam(required = false) Integer RetryInterval, + @ApiParam(value = "自动重试次数。\n" + + "\n" + + "如果传入RetryInterval参数,则需传入该参数。\n" + + "\n" + + "可选值:\n" + + "\n" + + "1:1次。\n" + + "2:2次。\n" + + "5:5次。",required = false,example = "5") @RequestParam(required = false) Integer RetryCount, + @ApiParam(value = "设备升级超时时间。单位:分钟,取值范围:1~1,440。\n" + + "\n" + + "超过指定时间后,设备未完成升级,则升级失败。\n" + + "\n" + + "说明\n" + + "从设备首次上报进度开始计算时间。\n" + + "因超时而导致的升级失败,云端不会触发自动重试逻辑。",required = false,example = "1440") @RequestParam(required = false) Integer TimeoutInMinutes, + @ApiParam(value = "每分钟最多向多少个设备推送固件下载URL。取值范围:0~1,000。\n" + + "\n" + + "不传入该参数,则取默认值1,000。",required = false,example = "1000") @RequestParam(required = false) Integer MaximumPerMinute, + @ApiParam(value = "设置灰度比例。取值为字符串格式的百分比,小数点后最多3位小数,系统计算结果向下取整。灰度升级的设备至少为1个。\n" + + "\n" + + "例如有100个待升级设备,设置灰度升级的灰度比例为33.33,则系统计算结果为33。\n" + + "\n" + + "升级范围指定为灰度升级(TargetSelection=GRAY)时,需传入此参数。",required = false) @RequestParam(required = false) String GrayPercent, + @ApiParam(value = "定向升级(即TargetSelection=SPECIFIC)的设备名称列表。\n" + + "\n" + + "说明\n" + + "发起定向升级(TargetSelection=SPECIFIC)任务时,需传入该参数,且不能传入SrcVersions指定待升级版本号。\n" + + "使用差分固件进行定向升级时,要升级的设备的当前固件版本号需与差分固件的待升级版本号(SrcVersion)相同。\n" + + "可以调用QueryDeviceDetail,查看设备固件版本号(FirmwareVersion)。\n" + + "列表中的设备所属的产品必须与固件所属产品一致。\n" + + "列表中不能有重复的设备名称。\n" + + "最多可传入200个设备名称。",required = false,example = "device06,device07") @RequestParam(required = false) List TargetDeviceName + ){ + return otaFirmwareService.CreateOTAStaticUpgradeJob(FirmwareId,ProductKey,TargetSelection,IotInstanceId,SrcVersion,ScheduleTime,RetryInterval,RetryCount, + TimeoutInMinutes,MaximumPerMinute,GrayPercent,TargetDeviceName); + } + + @PostMapping(value = "/CreateOTADynamicUpgradeJob") + @ApiOperation(value = "创建动态升级批次") + public JSONObject CreateOTADynamicUpgradeJob( + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "固件所属产品的ProductKey",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "待升级的固件版本号列表。\n" + + "\n" + + "可以调用QueryDeviceDetail,查看设备固件版本号FirmwareVersion。\n" + + "\n" + + "说明\n" + + "对差分固件发起动态升级任务时,该参数值必须与差分固件的待升级版本(SrcVersion)相同。\n" + + "列表中不能有重复的版本号。\n" + + "最多可传入10个版本号。",required = false,example = "1.0.0,1.0.1") @RequestParam(required = false) List SrcVersion, + @ApiParam(value = "设备升级失败后,自动重试的时间间隔,单位:分钟。可选值:\n" + + "\n" + + "0:立即重试。\n" + + "10:10分钟后重试。\n" + + "30:30分钟后重试。\n" + + "60:60分钟(即1小时)后重试。\n" + + "1440:1,440分钟(即24小时)后重试。\n" + + "不传入此参数,则表示不重试。",required = false,example = "1440") @RequestParam(required = false) Integer RetryInterval, + @ApiParam(value = "自动重试次数。\n" + + "\n" + + "如果传入RetryInterval参数,则需传入该参数。\n" + + "\n" + + "可选值:\n" + + "\n" + + "1:1次。\n" + + "2:2次。\n" + + "5:5次。",required = false,example = "5") @RequestParam(required = false) Integer RetryCount, + @ApiParam(value = "设备升级超时时间。单位:分钟,取值范围:1~1,440。\n" + + "\n" + + "超过指定时间后,设备未完成升级,则升级失败。\n" + + "\n" + + "说明\n" + + "从设备首次上报进度开始计算时间。\n" + + "因超时而导致的升级失败,不会触发自动重试逻辑。",required = false,example = "1440") @RequestParam(required = false) Integer TimeoutInMinutes, + @ApiParam(value = "每分钟最多向多少个设备推送固件下载URL。取值范围:0~1,000。\n" + + "\n" + + "不传入该参数,则取默认值1,000。",required = false,example = "1000") @RequestParam(required = false) Integer MaximumPerMinute + ){ + return otaFirmwareService.CreateOTADynamicUpgradeJob(FirmwareId,ProductKey,IotInstanceId,SrcVersion,RetryInterval,RetryCount,TimeoutInMinutes,MaximumPerMinute); + } + + @PostMapping(value = "/ListOTAJobByFirmware") + @ApiOperation(value = "获取固件下的升级批次列表") + public JSONObject ListOTAJobByFirmware( + @ApiParam(value = "指定从返回结果中的第几页开始显示。页数从1开始排序。",required = true,example = "1") @RequestParam(required = true) Integer CurrentPage, + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "指定返回结果中,每页显示的升级批次数量。最大值100。",required = true,example = "10") @RequestParam(required = true) Integer PageSize, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.ListOTAJobByFirmware(CurrentPage,FirmwareId,PageSize,IotInstanceId); + } + + @PostMapping(value = "/ListOTAJobByDevice") + @ApiOperation(value = "获取设备所在的固件升级批次列表") + public JSONObject ListOTAJobByDevice( + @ApiParam(value = "显示返回结果的第几页。返回结果页数从1开始排序。",required = true,example = "1") @RequestParam(required = true,defaultValue = "1") Integer CurrentPage, + @ApiParam(value = "设备名称。",required = true) @RequestParam(required = true) String DeviceName, + @ApiParam(value = "固件ID。固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "指定返回结果中每页显示的固件数量。最大限制为100。",required = true,example = "10") @RequestParam(required = true,defaultValue = "10") Integer PageSize, + @ApiParam(value = "设备所属产品的ProductKey。",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.ListOTAJobByDevice(CurrentPage,DeviceName,FirmwareId,PageSize,ProductKey,IotInstanceId); + } + + @PostMapping(value = "/QueryOTAJob") + @ApiOperation(value = "查询指定升级批次的详情") + public JSONObject QueryOTAJob( + @ApiParam(value = "升级批次ID。\n" + + "\n" + + "您调用CreateOTAVerifyJob、CreateOTAStaticUpgradeJob或CreateOTADynamicUpgradeJob创建升级任务批次后,返回的JobId。" + + "您也可以在物联网平台控制台固件的固件详情页查看。",required = true) @RequestParam(required = true) String JobId, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.QueryOTAJob(JobId,IotInstanceId); + } + + @PostMapping(value = "/CancelOTAStrategyByJob") + @ApiOperation(value = "取消动态升级批次所关联的动态升级策略") + public JSONObject CancelOTAStrategyByJob( + @ApiParam(value = "升级批次ID。\n" + + "\n" + + "您调用CreateOTADynamicUpgradeJob创建批次返回的JobId。" + + "您也可以在物联网平台控制台固件的固件详情页查看。",required = true) @RequestParam(required = true) String JobId, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId + ){ + return otaFirmwareService.CancelOTAStrategyByJob(JobId,IotInstanceId); + } + + @PostMapping(value = "/CancelOTATaskByDevice") + @ApiOperation(value = "取消指定固件下状态为待升级的设备升级作业") + public JSONObject CancelOTATaskByDevice( + @ApiParam(value = "要取消升级的设备名称。\n" + + "\n" + + "设备名称不能重复。\n" + + "\n" + + "最多可传入200个设备名称。",required = true) @RequestParam(required = true) List DeviceName, + @ApiParam(value = "固件ID,固件的唯一标识符。\n" + + "\n" + + "固件ID是调用CreateOTAFirmware创建固件时,返回的参数之一。\n" + + "\n" + + "可以调用ListOTAFirmware,从返回参数中查看。",required = true) @RequestParam(required = true) String FirmwareId, + @ApiParam(value = "要取消升级的设备所属产品的ProductKey。",required = true) @RequestParam(required = true) String ProductKey, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "升级批次ID。传入此参数则只删除指定批次下的设备升级任务。\n" + + "\n" + + "批次ID是您调用CreateOTAVerifyJob、CreateOTAStaticUpgradeJob或CreateOTADynamicUpgradeJob创建升级任务后返回的JobId。" + + "您也可以在物联网平台控制台上固件的固件详情页查看。",required = false) @RequestParam(required = false) String JobId + ){ + return otaFirmwareService.CancelOTATaskByDevice(DeviceName,FirmwareId,ProductKey,IotInstanceId,JobId); + } + + @PostMapping(value = "/CancelOTATaskByJob") + @ApiOperation(value = "取消指定批次下的设备升级作业") + public JSONObject CancelOTATaskByJob( + @ApiParam(value = "升级批次ID。\n" + + "\n" + + "您调用CreateOTAStaticUpgradeJob或CreateOTADynamicUpgradeJob创建批次返回的JobId。" + + "您也可以在物联网平台控制台固件的固件详情页查看。",required = true) @RequestParam(required = true) String JobId, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "取消定时升级批次下的设备升级作业,即调用CreateOTAStaticUpgradeJob时,传入了ScheduleTime参数创建的升级批次。取值:\n" + + "\n" + + "true:取消。\n" + + "false:不取消。\n" + + "不传入此参数,则取默认值false。",required = false) @RequestParam(required = false) Boolean CancelScheduledTask, + @ApiParam(value = "取消批次下所有状态为待推送(QUEUED)的设备升级作业。取值:\n" + + "\n" + + "true:取消。\n" + + "false:不取消。\n" + + "不传入此参数,则取默认值false。",required = false) @RequestParam(required = false) Boolean CancelQueuedTask, + @ApiParam(value = "取消批次下所有状态为升级中(IN_PROGRESS)的设备升级作业。取值:\n" + + "\n" + + "true:取消。\n" + + "false:不取消。\n" + + "不传入此参数,则取默认值false。",required = false) @RequestParam(required = false) Boolean CancelInProgressTask, + @ApiParam(value = "取消批次下所有状态为已推送(NOTIFIED)的设备升级作业。取值:\n" + + "\n" + + "true:取消。\n" + + "false:不取消。\n" + + "不传入此参数,则取默认值false。",required = false) @RequestParam(required = false) Boolean CancelNotifiedTask + ){ + return otaFirmwareService.CancelOTATaskByJob(JobId,IotInstanceId,CancelScheduledTask,CancelQueuedTask,CancelInProgressTask,CancelNotifiedTask); + } + + @PostMapping(value = "/ListOTATaskByJob") + @ApiOperation(value = "查询指定升级批次下的设备升级作业列表") + public JSONObject ListOTATaskByJob( + @ApiParam(value = "指定从返回结果中的第几页开始显示。页数从1开始排序。",required = true,example = "1") @RequestParam(required = true,defaultValue = "1") Integer CurrentPage, + @ApiParam(value = "升级批次ID,升级批次的唯一标识符。" + + "您调用CreateOTAVerifyJob、CreateOTAStaticUpgradeJob或CreateOTADynamicUpgradeJob返回的JobId。" + + "您也可以在物联网平台控制台上固件的固件详情页查看。",required = true) @RequestParam(required = true) String JobId, + @ApiParam(value = "指定返回结果中,每页显示的设备升级作业数量。最大限制:100。",required = true,example = "10") @RequestParam(required = true,defaultValue = "10") Integer PageSize, + @ApiParam(value = "公共实例不传此参数;您购买的实例需传入实例ID。",required = false) @RequestParam(required = false) String IotInstanceId, + @ApiParam(value = "传入此参数,则查询指定升级状态下的设备升级作业。\n" + + "\n" + + "QUEUED:待推送。\n" + + "NOTIFIED:已推送。\n" + + "IN_PROGRESS:升级中。\n" + + "SUCCEEDED:升级成功。\n" + + "FAILED:升级失败。\n" + + "不传入此参数,则查询指定升级批次下的全部设备升级作业。",required = false) @RequestParam(required = false) String TaskStatus + ){ + return otaFirmwareService.ListOTATaskByJob(CurrentPage,JobId,PageSize,IotInstanceId,TaskStatus); + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/PopPubController.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/PopPubController.java new file mode 100644 index 0000000..160cfe9 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/PopPubController.java @@ -0,0 +1,26 @@ +package com.example.springboot225aliiot.controller; + +import com.aliyuncs.iot.model.v20180120.PubResponse; +import com.example.springboot225aliiot.service.PopPubService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping(value = "/popPub") +@Api(description = "云发布到设备") +public class PopPubController { + @Resource + private PopPubService popPubService; + + @PostMapping(value = "/publish") + @ApiOperation(value = "服务端发布消息") + public PubResponse publish(String productKey, String deviceName, String messageContent){ + return popPubService.popPub(productKey, deviceName, messageContent); + } + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/ProductController.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/ProductController.java new file mode 100644 index 0000000..fc01d22 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/controller/ProductController.java @@ -0,0 +1,49 @@ +package com.example.springboot225aliiot.controller; + +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225aliiot.ali.ProductService; +import com.example.springboot225aliiot.query.ProductQuery; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +@RestController +@RequestMapping(value = "/product") +@Api(description = "阿里IOT产品管理") +public class ProductController { + @Resource + private ProductService productService; + + @PostMapping(value = "/createProduct") + @ApiOperation(value = "创建产品") + public JSONObject createProduct(ProductQuery productQuery){ + return productService.createProduct(productQuery); + } + + @GetMapping(value = "/queryProduct") + @ApiOperation(value = "查询产品详情") + public JSONObject queryProduct(@RequestParam String productKey){ + return productService.queryProduct(productKey); + } + + @GetMapping(value = "/queryProductList") + @ApiOperation(value = "查询产品列表") + public JSONObject queryProductList(@RequestParam String PageSize,@RequestParam String CurrentPage){ + return productService.queryProductList(PageSize,CurrentPage); + } + + @PutMapping(value = "/updateProduct") + @ApiOperation(value = "更新产品") + public JSONObject updateProduct(@RequestParam String ProductName, + @RequestParam String ProductKey){ + return productService.updateProduct(ProductName,ProductKey); + } + + @DeleteMapping(value = "/deleteProduct") + @ApiOperation(value = "删除产品") + public JSONObject updateProduct(@RequestParam String ProductKey){ + return productService.deleteProduct(ProductKey); + } +} \ No newline at end of file diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/query/ProductQuery.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/query/ProductQuery.java new file mode 100644 index 0000000..8c21f75 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/query/ProductQuery.java @@ -0,0 +1,14 @@ +package com.example.springboot225aliiot.query; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@Data +@ApiModel(value = "阿里IOT产品请求") +public class ProductQuery { + @ApiModelProperty(value = "0:设备 1:网关",required = true) + private String nodeType; + @ApiModelProperty(value = "产品名称",required = true) + private String productName; +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DevicePubService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DevicePubService.java new file mode 100644 index 0000000..b03a209 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DevicePubService.java @@ -0,0 +1,11 @@ +package com.example.springboot225aliiot.service; + +import org.springframework.stereotype.Service; + +/** + * 设备发布 + */ +@Service +public class DevicePubService { + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DeviceSubService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DeviceSubService.java new file mode 100644 index 0000000..91250e9 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/DeviceSubService.java @@ -0,0 +1,11 @@ +package com.example.springboot225aliiot.service; + +import org.springframework.stereotype.Service; + +/** + * 设备订阅 + */ +@Service +public class DeviceSubService { + +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopPubService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopPubService.java new file mode 100644 index 0000000..017ebb9 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopPubService.java @@ -0,0 +1,50 @@ +package com.example.springboot225aliiot.service; + +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.iot.model.v20180120.PubRequest; +import com.aliyuncs.iot.model.v20180120.PubResponse; +import com.aliyuncs.profile.DefaultProfile; +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.eclipse.paho.client.mqttv3.internal.websocket.Base64; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +/** + * 服务端发布 + */ +@Service +public class PopPubService { + + @Resource + private AliIOTConfig aliIOTConfig; + + public PubResponse popPub(String productKey, String deviceName, String messageContent) { + String regionId = "cn-shanghai"; + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); +// final String productKey = "a12xkkUoV0i"; +// final String deviceName = "device06"; + //设置client的参数 + DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret); + IAcsClient client = new DefaultAcsClient(profile); + + PubRequest request = new PubRequest(); + request.setQos(0); + //设置发布消息的topic + request.setTopicFullName("/" + productKey + "/" + deviceName + "/user/cloudmsg"); + request.setProductKey(productKey); + //设置消息的内容,一定要用base64编码,否则乱码 +// request.setMessageContent(Base64.encode("{\"accuracy\":0.001,\"time\":now}")); + request.setMessageContent(Base64.encode(messageContent)); + PubResponse response = new PubResponse(); + try { + response = client.getAcsResponse(request); + System.out.println("pub success?:" + response.getSuccess()); + } catch (Exception e) { + System.out.println(e); + } + return response; + } +} diff --git a/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopSubService.java b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopSubService.java new file mode 100644 index 0000000..3251101 --- /dev/null +++ b/springboot-225-aliiot/src/main/java/com/example/springboot225aliiot/service/PopSubService.java @@ -0,0 +1,186 @@ +package com.example.springboot225aliiot.service; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.InetAddress; +import java.net.URI; +import java.util.Hashtable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * 服务端订阅 + */ +@Service +public class PopSubService { + private final static Logger logger = LoggerFactory.getLogger(PopSubService.class); + + @Resource + private AliIOTConfig aliIOTConfig; + + //业务处理异步线程池,线程池参数可以根据您的业务特点调整;或者您也可以用其他异步方式处理接收到的消息 + private final static ExecutorService executorService = new ThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(50000)); + + public void popSubService() throws Exception { + //参数说明,请参见上一篇文档:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); +// String iotInstanceId = "${iotInstanceId}"; + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = InetAddress.getLocalHost().getHostAddress(); + + //UserName组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey +// + ",iotInstanceId=" + iotInstanceId //如果是购买的实例,需要传实例ID + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 + String connectionUrl = "failover:(amqps://"+aliIOTConfig.getUid()+".iot-amqp."+"cn-shanghai"+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + // 必须要sleep一下,不然程序执行的太快,来不及消费 设备发送过来的消息;或者实现CommandLineRunner +// Thread.sleep(600000); + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + //1.收到消息之后一定要ACK + // 推荐做法:创建Session选择Session.AUTO_ACKNOWLEDGE,这里会自动ACK。 + // 其他做法:创建Session选择Session.CLIENT_ACKNOWLEDGE,这里一定要调message.acknowledge()来ACK。 + message.acknowledge(); + //2.建议异步处理收到的消息,确保onMessage函数里没有耗时逻辑。 + // 如果业务处理耗时过程过长阻塞住线程,可能会影响SDK收到消息后的正常回调。 + executorService.submit(() -> processMessage(message)); + } catch (Exception e) { + logger.error("submit task occurs exception ", e); + } + } + }; + + /** + * 在这里处理您收到消息后的具体业务逻辑。 + */ + private static void processMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = body==null?"":new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + // 1向数据库中插入message,2把设备发过来的实时数据下发到kafka,kafka再把消息发送到我们的平台,把相关数据存到我们平台的数据库中 + + } catch (Exception e) { + logger.error("processMessage occurs error ", e); + } + } + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见上一篇文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } +} diff --git a/springboot-225-aliiot/src/main/resources/application.yml b/springboot-225-aliiot/src/main/resources/application.yml new file mode 100644 index 0000000..c208153 --- /dev/null +++ b/springboot-225-aliiot/src/main/resources/application.yml @@ -0,0 +1,8 @@ +ali: + iot: + access-key: LTAI4GHKW5pnqksbrQ6cxsq4 + access-secret: wrScruBU4XuR7uPQmgdCSA7yeKkcy0 + consumerGroupId: DEFAULT_GROUP + domain: iot.cn-shanghai.aliyuncs.com + region-id: cn-shanghai + uid: 1267627266980013 \ No newline at end of file diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest01.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest01.java new file mode 100644 index 0000000..1624c78 --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest01.java @@ -0,0 +1,42 @@ +package com.example.springboot225aliiot; + +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.exceptions.ServerException; +import com.aliyuncs.iot.model.v20180120.PubRequest; +import com.aliyuncs.iot.model.v20180120.PubResponse; +import com.aliyuncs.profile.DefaultProfile; +import com.aliyuncs.profile.IClientProfile; +import org.apache.tomcat.util.codec.binary.Base64; + +public class IOTTest01 { + public static void main(String[] args) throws ClientException { + //初始化SDK客户端 + String accessKey = "LTAI4GHKW5pnqksbrQ6cxsq4"; + String accessSecret = "wrScruBU4XuR7uPQmgdCSA7yeKkcy0"; + DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Iot", "iot.cn-shanghai.aliyuncs.com"); + IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret); + DefaultAcsClient client = new DefaultAcsClient(profile); //初始化SDK客户端 + + //以调用Pub接口发布消息到Topic为例 + PubRequest request = new PubRequest(); + request.setProductKey("a1H0HG5T53N"); + request.setMessageContent(Base64.encodeBase64String("hello world".getBytes())); + request.setTopicFullName("/a1H0HG5T53N/test01/get"); + request.setQos(0); //目前支持QoS0和QoS1 + try + { + PubResponse response = client.getAcsResponse(request); + System.out.println(response.getSuccess()); + System.out.println(response.getErrorMessage()); + } + catch (ServerException e) + { + e.printStackTrace(); + } + catch (ClientException e) + { + e.printStackTrace(); + } + } +} diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest02.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest02.java new file mode 100644 index 0000000..a04c28f --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/IOTTest02.java @@ -0,0 +1,34 @@ +package com.example.springboot225aliiot; + +import com.aliyuncs.CommonRequest; +import com.aliyuncs.CommonResponse; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.exceptions.ServerException; +import com.aliyuncs.http.MethodType; +import com.aliyuncs.profile.DefaultProfile; + +public class IOTTest02 { + public static void main(String[] args) throws ClientException { + DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI4GHKW5pnqksbrQ6cxsq4", "wrScruBU4XuR7uPQmgdCSA7yeKkcy0"); + IAcsClient client = new DefaultAcsClient(profile); + + CommonRequest request = new CommonRequest(); + request.setMethod(MethodType.POST); + request.setDomain("iot.cn-shanghai.aliyuncs.com"); + request.setVersion("2018-01-20"); + request.setAction( "QueryProductList"); + request.putQueryParameter("RegionId", "cn-shanghai"); + request.putQueryParameter("PageSize", "10"); + request.putQueryParameter("CurrentPage", "1"); + try { + CommonResponse response = client.getCommonResponse(request); + System.out.println(response.getData()); + } catch (ServerException e) { + e.printStackTrace(); + } catch (ClientException e) { + e.printStackTrace(); + } + } +} diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Springboot225AliiotApplicationTests.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Springboot225AliiotApplicationTests.java new file mode 100644 index 0000000..188ddca --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Springboot225AliiotApplicationTests.java @@ -0,0 +1,159 @@ +package com.example.springboot225aliiot; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.URI; +import java.util.Hashtable; + +@SpringBootTest +class Springboot225AliiotApplicationTests { + + private final static Logger logger = LoggerFactory.getLogger(Springboot225AliiotApplicationTests.class); + + @Resource + private static AliIOTConfig aliIOTConfig; + + @Test + public void test() throws Exception { + //参数说明,请参见:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + System.out.println(accessKey); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = "ClientId01"; + + //UserName组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 +// String connectionUrl = "failover:(amqps://${uid}.iot-amqp.${regionId}.aliyuncs.com:5671?amqp.idleTimeout=80000)" +// + "?failover.reconnectDelay=30"; + String connectionUrl = "failover:(amqps://123456.iot-amqp."+aliIOTConfig.getRegionId()+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + //如果创建Session选择的是Session.CLIENT_ACKNOWLEDGE,这里需要手动ACK。 + //message.acknowledge(); + //如果要对收到的消息做耗时的处理,请异步处理,确保这里不要有耗时逻辑。 + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立。 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见上一篇文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } + +} diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Test01.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Test01.java new file mode 100644 index 0000000..33eb1d9 --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/Test01.java @@ -0,0 +1,7 @@ +package com.example.springboot225aliiot; + +public class Test01 { + public static void main(String[] args) { + System.out.println(String.valueOf(false)); + } +} diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/ali/impl/ProductServiceImplTest.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/ali/impl/ProductServiceImplTest.java new file mode 100644 index 0000000..2c2c8dd --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/ali/impl/ProductServiceImplTest.java @@ -0,0 +1,19 @@ +package com.example.springboot225aliiot.ali.impl; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; + +@SpringBootTest +class ProductServiceImplTest { + + @Resource + private static AliIOTConfig aliIOTConfig; + + @Test + void createProduct() { + + } +} \ No newline at end of file diff --git a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/controller/ProductControllerTest.java b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/controller/ProductControllerTest.java new file mode 100644 index 0000000..db17324 --- /dev/null +++ b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/controller/ProductControllerTest.java @@ -0,0 +1,13 @@ +package com.example.springboot225aliiot.controller; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ProductControllerTest { + + @Test + void createProduct() { + + } +} \ No newline at end of file diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\272\221\347\253\257\344\270\213\345\217\221\346\214\207\344\273\244/CloudSendInstruction.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\272\221\347\253\257\344\270\213\345\217\221\346\214\207\344\273\244/CloudSendInstruction.java" new file mode 100644 index 0000000..2f62d04 --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\272\221\347\253\257\344\270\213\345\217\221\346\214\207\344\273\244/CloudSendInstruction.java" @@ -0,0 +1,50 @@ +package com.example.springboot225aliiot.云端下发指令; + +import com.alibaba.fastjson.JSONObject; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.exceptions.ClientException; +import com.aliyuncs.iot.model.v20180120.SetDevicePropertyRequest; +import com.aliyuncs.iot.model.v20180120.SetDevicePropertyResponse; +import com.aliyuncs.profile.DefaultProfile; +import com.aliyuncs.profile.IClientProfile; +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; + +/** + * 云端下发指令 + */ +@SpringBootTest +@RunWith(SpringJUnit4ClassRunner.class) +public class CloudSendInstruction { + + @Resource + private AliIOTConfig aliIOTConfig; + + @Test + public void test01() throws ClientException { + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Iot", "iot.cn-shanghai.aliyuncs.com"); + IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret); + DefaultAcsClient client = new DefaultAcsClient(profile); + + SetDevicePropertyRequest request = new SetDevicePropertyRequest(); + request.setProductKey("a12xkkUoV0i"); + request.setDeviceName("device06"); + JSONObject itemJson = new JSONObject(); + itemJson.put("Status", 0); + request.setItems(itemJson.toString()); + + try { + SetDevicePropertyResponse response = client.getAcsResponse(request); + System.out.println(response.getRequestId() + ", success: " + response.getSuccess()); + } catch (ClientException e) { + e.printStackTrace(); + } + } +} diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250AMQP\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205/AmqpJavaClientDemo.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250AMQP\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205/AmqpJavaClientDemo.java" new file mode 100644 index 0000000..35fa71e --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250AMQP\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205/AmqpJavaClientDemo.java" @@ -0,0 +1,186 @@ +package com.example.springboot225aliiot.使用AMQP服务端订阅; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.InetAddress; +import java.net.URI; +import java.util.Hashtable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@SpringBootTest +@RunWith(SpringJUnit4ClassRunner.class) +public class AmqpJavaClientDemo { + private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class); + + @Resource + private AliIOTConfig aliIOTConfig; + + //业务处理异步线程池,线程池参数可以根据您的业务特点调整;或者您也可以用其他异步方式处理接收到的消息 + private final static ExecutorService executorService = new ThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(50000)); + + @Test + public void amqpJavaClientDemo() throws Exception { + //参数说明,请参见上一篇文档:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); +// String iotInstanceId = "${iotInstanceId}"; + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = InetAddress.getLocalHost().getHostAddress(); + + //UserName组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey +// + ",iotInstanceId=" + iotInstanceId //如果是购买的实例,需要传实例ID + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 + String connectionUrl = "failover:(amqps://"+aliIOTConfig.getUid()+".iot-amqp."+"cn-shanghai"+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + // 必须要sleep一下,不然程序执行的太快,来不及消费 设备发送过来的消息 + Thread.sleep(600000); + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + //1.收到消息之后一定要ACK + // 推荐做法:创建Session选择Session.AUTO_ACKNOWLEDGE,这里会自动ACK。 + // 其他做法:创建Session选择Session.CLIENT_ACKNOWLEDGE,这里一定要调message.acknowledge()来ACK。 + // message.acknowledge(); + //2.建议异步处理收到的消息,确保onMessage函数里没有耗时逻辑。 + // 如果业务处理耗时过程过长阻塞住线程,可能会影响SDK收到消息后的正常回调。 + executorService.submit(() -> processMessage(message)); + } catch (Exception e) { + logger.error("submit task occurs exception ", e); + } + } + }; + + /** + * 在这里处理您收到消息后的具体业务逻辑。 + */ + private static void processMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + } catch (Exception e) { + logger.error("processMessage occurs error ", e); + } + } + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见上一篇文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } +} diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/AmqpJavaClientDemo.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/AmqpJavaClientDemo.java" new file mode 100644 index 0000000..5787d43 --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/AmqpJavaClientDemo.java" @@ -0,0 +1,160 @@ +package com.example.springboot225aliiot.使用自定义Topic进行通信.设备发送消息给服务器; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.InetAddress; +import java.net.URI; +import java.util.Hashtable; + +@SpringBootTest +@RunWith(SpringJUnit4ClassRunner.class) +public class AmqpJavaClientDemo { + private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class); + + @Resource + private AliIOTConfig aliIOTConfig; + + @Test + public void amqpJavaClientDemoTest() throws Exception { + //参数说明,请参见文档:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = InetAddress.getLocalHost().getHostAddress(); + + //UserName组装方法,请参见文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 + String connectionUrl = "failover:(amqps://"+aliIOTConfig.getUid()+".iot-amqp."+"cn-shanghai"+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + + + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + //如果创建Session选择的是Session.CLIENT_ACKNOWLEDGE,这里需要手动ACK。 + //message.acknowledge(); + //如果要对收到的消息做耗时的处理,请异步处理,确保这里不要有耗时逻辑。 + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立。 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } +} diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitPubClient.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitPubClient.java" new file mode 100644 index 0000000..8a3883c --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitPubClient.java" @@ -0,0 +1,80 @@ +package com.example.springboot225aliiot.使用自定义Topic进行通信.设备发送消息给服务器; + +import com.aliyun.alink.dm.api.DeviceInfo; +import com.aliyun.alink.dm.api.InitResult; +import com.aliyun.alink.linkkit.api.ILinkKitConnectListener; +import com.aliyun.alink.linkkit.api.IoTMqttClientConfig; +import com.aliyun.alink.linkkit.api.LinkKit; +import com.aliyun.alink.linkkit.api.LinkKitInitParams; +import com.aliyun.alink.linksdk.cmp.connect.channel.MqttPublishRequest; +import com.aliyun.alink.linksdk.cmp.core.base.ARequest; +import com.aliyun.alink.linksdk.cmp.core.base.AResponse; +import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSendListener; +import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper; +import com.aliyun.alink.linksdk.tools.AError; + +import java.util.HashMap; +import java.util.Map; + +/** + * 设备发布 + */ +public class LinkkitPubClient { + + public static void main(String[] args) { + final String productKey = "您的产品productKey"; + final String deviceName = "您设备的名字deviceName"; + final String deviceSecret = "您的设备秘钥deviceSecret"; + final String region = "您设备所处区域regionId"; + + LinkKitInitParams params = new LinkKitInitParams(); + //LinkKit底层是mqtt协议,设置mqtt的配置 + IoTMqttClientConfig config = new IoTMqttClientConfig(); + config.productKey = productKey; + config.deviceName = deviceName; + config.deviceSecret = deviceSecret; + config.channelHost = productKey + ".iot-as-mqtt." + region + ".aliyuncs.com:1883"; + //设备的信息 + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.productKey = productKey; + deviceInfo.deviceName = deviceName; + deviceInfo.deviceSecret = deviceSecret; + //报备的设备初始状态,此处没有物模型初始状态 + Map propertyValues = new HashMap(); + + params.mqttClientConfig = config; + params.deviceInfo = deviceInfo; + params.propertyValues = propertyValues; + + //连接并设置连接成功以后的回调函数 + LinkKit.getInstance().init(params, new ILinkKitConnectListener() { + @Override + public void onError(AError aError) { + System.out.println("Init error:" + aError); + } + + //初始化成功以后的回调 + @Override + public void onInitDone(InitResult initResult) { + //设置pub消息的topic和内容 + MqttPublishRequest request = new MqttPublishRequest(); + request.topic = "/" + productKey + "/" + deviceName + "/user/devmsg"; + request.qos = 0; + request.payloadObj = "{\"temperature\":35.0, \"time\":\"sometime\"}"; + //发送消息并设置成功以后的回调 + LinkKit.getInstance().publish(request, new IConnectSendListener() { + @Override + public void onResponse(ARequest aRequest, AResponse aResponse) { + System.out.println("onResponse:" + aResponse.getData()); + } + + @Override + public void onFailure(ARequest aRequest, AError aError) { + System.out.println("onFailure:" + aError.getCode() + aError.getMsg()); + } + }); + } + }); + } +} + diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitSubClient.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitSubClient.java" new file mode 100644 index 0000000..bc87734 --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/LinkkitSubClient.java" @@ -0,0 +1,102 @@ +package com.example.springboot225aliiot.使用自定义Topic进行通信.设备发送消息给服务器; + +import com.aliyun.alink.dm.api.DeviceInfo; +import com.aliyun.alink.dm.api.InitResult; +import com.aliyun.alink.linkkit.api.ILinkKitConnectListener; +import com.aliyun.alink.linkkit.api.IoTMqttClientConfig; +import com.aliyun.alink.linkkit.api.LinkKit; +import com.aliyun.alink.linkkit.api.LinkKitInitParams; +import com.aliyun.alink.linksdk.cmp.connect.channel.MqttSubscribeRequest; +import com.aliyun.alink.linksdk.cmp.core.base.AMessage; +import com.aliyun.alink.linksdk.cmp.core.base.ConnectState; +import com.aliyun.alink.linksdk.cmp.core.listener.IConnectNotifyListener; +import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSubscribeListener; +import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper; +import com.aliyun.alink.linksdk.tools.AError; + +import java.util.HashMap; +import java.util.Map; + +/** + * 设备订阅 + */ +public class LinkkitSubClient { + + public static void main(String[] args) throws InterruptedException { + final String productKey = "a12xkkUoV0i"; + final String deviceName = "device06"; + final String deviceSecret = "mh4MNqb8yEpNzhALP9xHwYN5HniM5UR9"; + final String region = "cn-shanghai"; + + LinkKitInitParams params = new LinkKitInitParams(); + //LinkKit底层是mqtt协议,设置mqtt的配置 + IoTMqttClientConfig config = new IoTMqttClientConfig(); + config.productKey = productKey; + config.deviceName = deviceName; + config.deviceSecret = deviceSecret; + config.channelHost = productKey + ".iot-as-mqtt." + region + ".aliyuncs.com:1883"; + //设备的信息 + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.productKey = productKey; + deviceInfo.deviceName = deviceName; + deviceInfo.deviceSecret = deviceSecret; + //报备的设备初始状态,此处没有物模型初始状态 + Map propertyValues = new HashMap(); + + params.mqttClientConfig = config; + params.deviceInfo = deviceInfo; + params.propertyValues = propertyValues; + + //连接并设置连接成功以后的回调函数 + LinkKit.getInstance().init(params, new ILinkKitConnectListener() { + @Override + public void onError(AError aError) { + System.out.println("Init error:" + aError); + } + + //初始化成功以后的回调 + @Override + public void onInitDone(InitResult initResult) { + //设置订阅的topic + MqttSubscribeRequest request = new MqttSubscribeRequest(); + request.topic = "/" + productKey + "/" + deviceName + "/user/cloudmsg"; + request.isSubscribe = true; + //发出订阅请求并设置订阅成功或者失败的回调函数 + LinkKit.getInstance().subscribe(request, new IConnectSubscribeListener() { + @Override + public void onSuccess() { + System.out.println(""); + } + + @Override + public void onFailure(AError aError) { + + } + }); + + //设置订阅的下行消息到来时的回调函数 + IConnectNotifyListener notifyListener = new IConnectNotifyListener() { + //此处定义收到下行消息以后的回调函数。 + @Override + public void onNotify(String connectId, String topic, AMessage aMessage) { + System.out.println( + "received message from " + topic + ":" + new String((byte[])aMessage.getData())); + } + + @Override + public boolean shouldHandle(String s, String s1) { + return false; + } + + @Override + public void onConnectStateChange(String s, ConnectState connectState) { + + } + }; + LinkKit.getInstance().registerOnNotifyListener(notifyListener); + } + }); + + Thread.sleep(6000000); + } +} \ No newline at end of file diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/PopPubServer.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/PopPubServer.java" new file mode 100644 index 0000000..30c6fe5 --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\344\275\277\347\224\250\350\207\252\345\256\232\344\271\211Topic\350\277\233\350\241\214\351\200\232\344\277\241/\350\256\276\345\244\207\345\217\221\351\200\201\346\266\210\346\201\257\347\273\231\346\234\215\345\212\241\345\231\250/PopPubServer.java" @@ -0,0 +1,39 @@ +package com.example.springboot225aliiot.使用自定义Topic进行通信.设备发送消息给服务器; + +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.iot.model.v20180120.PubRequest; +import com.aliyuncs.iot.model.v20180120.PubResponse; +import com.aliyuncs.profile.DefaultProfile; +import org.eclipse.paho.client.mqttv3.internal.websocket.Base64; + +/** + * 云发布消息 + */ +public class PopPubServer { + + public static void main(String[] args) { + String regionId = "cn-shanghai"; + String accessKey = "LTAI4GHKW5pnqksbrQ6cxsq4"; + String accessSecret = "wrScruBU4XuR7uPQmgdCSA7yeKkcy0"; + final String productKey = "a12xkkUoV0i"; + final String deviceName = "device06"; + //设置client的参数 + DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret); + IAcsClient client = new DefaultAcsClient(profile); + + PubRequest request = new PubRequest(); + request.setQos(0); + //设置发布消息的topic + request.setTopicFullName("/" + productKey + "/" + deviceName + "/user/cloudmsg"); + request.setProductKey(productKey); + //设置消息的内容,一定要用base64编码,否则乱码 + request.setMessageContent(Base64.encode("{\"accuracy\":0.001,\"time\":now}")); + try { + PubResponse response = client.getAcsResponse(request); + System.out.println("pub success?:" + response.getSuccess()); + } catch (Exception e) { + System.out.println(e); + } + } +} diff --git "a/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205\350\256\276\345\244\207\346\266\210\346\201\257/AmqpJavaClientDemo.java" "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205\350\256\276\345\244\207\346\266\210\346\201\257/AmqpJavaClientDemo.java" new file mode 100644 index 0000000..bc672c0 --- /dev/null +++ "b/springboot-225-aliiot/src/test/java/com/example/springboot225aliiot/\346\234\215\345\212\241\347\253\257\350\256\242\351\230\205\350\256\276\345\244\207\346\266\210\346\201\257/AmqpJavaClientDemo.java" @@ -0,0 +1,165 @@ +package com.example.springboot225aliiot.服务端订阅设备消息; + +import com.example.springboot225aliiot.config.AliIOTConfig; +import org.apache.commons.codec.binary.Base64; +import org.apache.qpid.jms.JmsConnection; +import org.apache.qpid.jms.JmsConnectionListener; +import org.apache.qpid.jms.message.JmsInboundMessageDispatch; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.annotation.Resource; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.jms.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import java.net.InetAddress; +import java.net.URI; +import java.util.Hashtable; + +/** + * 入门教程-快速玩转物联网平台-服务端订阅设备消息 + * AMQP + */ +@SpringBootTest +@RunWith(SpringJUnit4ClassRunner.class) +public class AmqpJavaClientDemo { + + private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class); + + @Resource + private AliIOTConfig aliIOTConfig; + + @Test + public void amqpJavaClientDemoTest() throws Exception { + //参数说明,请参见:AMQP客户端接入说明。 + String accessKey = aliIOTConfig.getAccessKey(); + String accessSecret = aliIOTConfig.getAccessSecret(); + String consumerGroupId = aliIOTConfig.getConsumerGroupId(); + long timeStamp = System.currentTimeMillis(); + //签名方法:支持hmacmd5,hmacsha1和hmacsha256 + String signMethod = "hmacsha1"; + //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。 + //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。 +// String clientId = "${YourClientId}"; + String clientId = InetAddress.getLocalHost().getHostAddress(); + + //UserName组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String userName = clientId + "|authMode=aksign" + + ",signMethod=" + signMethod + + ",timestamp=" + timeStamp + + ",authId=" + accessKey + + ",consumerGroupId=" + consumerGroupId + + "|"; + //password组装方法,请参见上一篇文档:AMQP客户端接入说明。 + String signContent = "authId=" + accessKey + "×tamp=" + timeStamp; + String password = doSign(signContent,accessSecret, signMethod); + //按照qpid-jms的规范,组装连接URL。 +// String connectionUrl = "failover:(amqps://${uid}.iot-amqp.${regionId}.aliyuncs.com:5671?amqp.idleTimeout=80000)" +// + "?failover.reconnectDelay=30"; + String connectionUrl = "failover:(amqps://"+aliIOTConfig.getUid()+".iot-amqp."+"cn-shanghai"+".aliyuncs.com:5671?amqp.idleTimeout=80000)" + + "?failover.reconnectDelay=30"; + + Hashtable hashtable = new Hashtable<>(); + hashtable.put("connectionfactory.SBCF",connectionUrl); + hashtable.put("queue.QUEUE", "default"); + hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); + Context context = new InitialContext(hashtable); + ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF"); + Destination queue = (Destination)context.lookup("QUEUE"); + // Create Connection + Connection connection = cf.createConnection(userName, password); + ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener); + // Create Session + // Session.CLIENT_ACKNOWLEDGE: 收到消息后,需要手动调用message.acknowledge() + // Session.AUTO_ACKNOWLEDGE: SDK自动ACK(推荐) + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + // Create Receiver Link + MessageConsumer consumer = session.createConsumer(queue); + consumer.setMessageListener(messageListener); + } + + private static MessageListener messageListener = new MessageListener() { + @Override + public void onMessage(Message message) { + try { + byte[] body = message.getBody(byte[].class); + String content = new String(body); + String topic = message.getStringProperty("topic"); + String messageId = message.getStringProperty("messageId"); + logger.info("receive message" + + ", topic = " + topic + + ", messageId = " + messageId + + ", content = " + content); + //如果创建Session选择的是Session.CLIENT_ACKNOWLEDGE,这里需要手动ACK。 + //message.acknowledge(); + //如果要对收到的消息做耗时的处理,请异步处理,确保这里不要有耗时逻辑。 + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + + private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() { + /** + * 连接成功建立。 + */ + @Override + public void onConnectionEstablished(URI remoteURI) { + logger.info("onConnectionEstablished, remoteUri:{}", remoteURI); + } + + /** + * 尝试过最大重试次数之后,最终连接失败。 + */ + @Override + public void onConnectionFailure(Throwable error) { + logger.error("onConnectionFailure, {}", error.getMessage()); + } + + /** + * 连接中断。 + */ + @Override + public void onConnectionInterrupted(URI remoteURI) { + logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI); + } + + /** + * 连接中断后又自动重连上。 + */ + @Override + public void onConnectionRestored(URI remoteURI) { + logger.info("onConnectionRestored, remoteUri:{}", remoteURI); + } + + @Override + public void onInboundMessage(JmsInboundMessageDispatch envelope) {} + + @Override + public void onSessionClosed(Session session, Throwable cause) {} + + @Override + public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {} + + @Override + public void onProducerClosed(MessageProducer producer, Throwable cause) {} + }; + + /** + * password签名计算方法,请参见上一篇文档:AMQP客户端接入说明。 + */ + private static String doSign(String toSignString, String secret, String signMethod) throws Exception { + SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(signingKey); + byte[] rawHmac = mac.doFinal(toSignString.getBytes()); + return Base64.encodeBase64String(rawHmac); + } +} \ No newline at end of file -- Gitee From e158d12001b6d4657feab6a655534c2fc85f0bfa Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 27 May 2020 15:11:50 +0800 Subject: [PATCH 38/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=8C=E6=95=B4=E5=90=88kafka?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-kafka/.gitignore | 31 +++++++ springboot-225-kafka/pom.xml | 87 +++++++++++++++++++ .../Springboot225KafkaApplication.java | 13 +++ .../consumer/ConsumerDemo.java | 18 ++++ .../controller/ProducerController.java | 18 ++++ .../src/main/resources/application.yml | 14 +++ .../Springboot225KafkaApplicationTests.java | 13 +++ 7 files changed, 194 insertions(+) create mode 100644 springboot-225-kafka/.gitignore create mode 100644 springboot-225-kafka/pom.xml create mode 100644 springboot-225-kafka/src/main/java/com/example/springboot225kafka/Springboot225KafkaApplication.java create mode 100644 springboot-225-kafka/src/main/java/com/example/springboot225kafka/consumer/ConsumerDemo.java create mode 100644 springboot-225-kafka/src/main/java/com/example/springboot225kafka/controller/ProducerController.java create mode 100644 springboot-225-kafka/src/main/resources/application.yml create mode 100644 springboot-225-kafka/src/test/java/com/example/springboot225kafka/Springboot225KafkaApplicationTests.java diff --git a/springboot-225-kafka/.gitignore b/springboot-225-kafka/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/springboot-225-kafka/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-kafka/pom.xml b/springboot-225-kafka/pom.xml new file mode 100644 index 0000000..1dc2ebe --- /dev/null +++ b/springboot-225-kafka/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.7.RELEASE + + + com.example + springboot-225-kafka + 0.0.1-SNAPSHOT + springboot-225-kafka + SpringBoot整合Kafka + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + org.apache.kafka + kafka-streams + + + org.springframework.kafka + spring-kafka + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + io.projectreactor + reactor-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-kafka/src/main/java/com/example/springboot225kafka/Springboot225KafkaApplication.java b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/Springboot225KafkaApplication.java new file mode 100644 index 0000000..979768e --- /dev/null +++ b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/Springboot225KafkaApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225kafka; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225KafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225KafkaApplication.class, args); + } + +} diff --git a/springboot-225-kafka/src/main/java/com/example/springboot225kafka/consumer/ConsumerDemo.java b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/consumer/ConsumerDemo.java new file mode 100644 index 0000000..a2a9b4d --- /dev/null +++ b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/consumer/ConsumerDemo.java @@ -0,0 +1,18 @@ +package com.example.springboot225kafka.consumer; + + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +public class ConsumerDemo { + /** + * 定义此消费者接收topics = "demo"的消息,与controller中的topic对应上即可 + * @param record 变量代表消息本身,可以通过ConsumerRecord类型的record变量来打印接收的消息的各种信息 + */ + @KafkaListener(topics = "demo") + public void listen (ConsumerRecord record){ + System.out.printf("topic is %s, offset is %d, value is %s \n", record.topic(), record.offset(), record.value()); + } +} diff --git a/springboot-225-kafka/src/main/java/com/example/springboot225kafka/controller/ProducerController.java b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/controller/ProducerController.java new file mode 100644 index 0000000..71b085d --- /dev/null +++ b/springboot-225-kafka/src/main/java/com/example/springboot225kafka/controller/ProducerController.java @@ -0,0 +1,18 @@ +package com.example.springboot225kafka.controller; + +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +public class ProducerController { + @Resource + private KafkaTemplate kafkaTemplate; + @RequestMapping("/message/send") + public String send(String msg){ + kafkaTemplate.send("demo", msg); //使用kafka模板发送信息 + return "success"; + } +} diff --git a/springboot-225-kafka/src/main/resources/application.yml b/springboot-225-kafka/src/main/resources/application.yml new file mode 100644 index 0000000..475fa58 --- /dev/null +++ b/springboot-225-kafka/src/main/resources/application.yml @@ -0,0 +1,14 @@ +spring: + kafka: + bootstrap-servers: 192.168.0.120:9092 #ָkafka serverĵַȺм䣬Ÿ + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + consumer: + group-id: default_consumer_group #ȺID + enable-auto-commit: true + auto-commit-interval: 1000 + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer +server: + port: 8500 \ No newline at end of file diff --git a/springboot-225-kafka/src/test/java/com/example/springboot225kafka/Springboot225KafkaApplicationTests.java b/springboot-225-kafka/src/test/java/com/example/springboot225kafka/Springboot225KafkaApplicationTests.java new file mode 100644 index 0000000..4e3efb8 --- /dev/null +++ b/springboot-225-kafka/src/test/java/com/example/springboot225kafka/Springboot225KafkaApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225kafka; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225KafkaApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 8f4037de11396f5f68f9de7ce4af18da821630e5 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 27 May 2020 16:01:21 +0800 Subject: [PATCH 39/49] =?UTF-8?q?SpringBoot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=8C=E6=95=B4=E5=90=88velocity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-velocity/.gitignore | 31 ++ springboot-225-velocity/pom.xml | 102 ++++ .../src/main/java/HelloVelocity.java | 39 ++ .../src/main/java/VelocityGenerator.java | 67 +++ .../Springboot225VelocityApplication.java | 13 + .../config/Swagger2Config.java | 35 ++ .../controller/HelloController.java | 23 + .../VelocityGeneratorController.java | 77 +++ .../src/main/resources/HelloVelocity.vm | 7 + .../src/main/resources/application.properties | 1 + .../src/main/resources/controller.java.vm | 113 +++++ .../springboot225velocity/CodeGenerator.java | 450 ++++++++++++++++++ .../SpringBootPlusGenerator.java | 104 ++++ ...Springboot225VelocityApplicationTests.java | 13 + .../config/GeneratorConfig.java | 93 ++++ .../config/GeneratorStrategy.java | 30 ++ .../config/MybatisPlusGeneratorConfig.java | 51 ++ .../config/ProjectConfig.java | 64 +++ .../config/TableConfig.java | 41 ++ .../query/SpringBootPlusMySqlQuery.java | 34 ++ .../query/SpringBootPlusSqlServerQuery.java | 44 ++ .../constant/GeneratorConstant.java | 141 ++++++ .../exception/ApiCode.java | 132 +++++ .../exception/GeneratorException.java | 40 ++ .../exception/SpringBootPlusException.java | 65 +++ .../properties/GeneratorProperties.java | 135 ++++++ .../resources/templates/controller.java.vm | 162 +++++++ .../test/resources/templates/entity.java.vm | 104 ++++ .../test/resources/templates/hello.java.vm | 0 .../test/resources/templates/mapper.java.vm | 53 +++ .../test/resources/templates/mapper.xml.vm | 51 ++ .../resources/templates/pageParam.java.vm | 31 ++ .../test/resources/templates/queryVo.java.vm | 46 ++ .../test/resources/templates/service.java.vm | 72 +++ .../resources/templates/serviceImpl.java.vm | 80 ++++ 35 files changed, 2544 insertions(+) create mode 100644 springboot-225-velocity/.gitignore create mode 100644 springboot-225-velocity/pom.xml create mode 100644 springboot-225-velocity/src/main/java/HelloVelocity.java create mode 100644 springboot-225-velocity/src/main/java/VelocityGenerator.java create mode 100644 springboot-225-velocity/src/main/java/com/example/springboot225velocity/Springboot225VelocityApplication.java create mode 100644 springboot-225-velocity/src/main/java/com/example/springboot225velocity/config/Swagger2Config.java create mode 100644 springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/HelloController.java create mode 100644 springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java create mode 100644 springboot-225-velocity/src/main/resources/HelloVelocity.vm create mode 100644 springboot-225-velocity/src/main/resources/application.properties create mode 100644 springboot-225-velocity/src/main/resources/controller.java.vm create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/CodeGenerator.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/SpringBootPlusGenerator.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/Springboot225VelocityApplicationTests.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorConfig.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorStrategy.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/MybatisPlusGeneratorConfig.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/ProjectConfig.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/TableConfig.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusMySqlQuery.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusSqlServerQuery.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/constant/GeneratorConstant.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/ApiCode.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/GeneratorException.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/SpringBootPlusException.java create mode 100644 springboot-225-velocity/src/test/java/com/example/springboot225velocity/properties/GeneratorProperties.java create mode 100644 springboot-225-velocity/src/test/resources/templates/controller.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/entity.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/hello.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/mapper.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/mapper.xml.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/pageParam.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/queryVo.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/service.java.vm create mode 100644 springboot-225-velocity/src/test/resources/templates/serviceImpl.java.vm diff --git a/springboot-225-velocity/.gitignore b/springboot-225-velocity/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/springboot-225-velocity/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-velocity/pom.xml b/springboot-225-velocity/pom.xml new file mode 100644 index 0000000..ca52363 --- /dev/null +++ b/springboot-225-velocity/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-velocity + 0.0.1-SNAPSHOT + springboot-225-velocity + Demo project for Spring Boot + + + 1.8 + 3.3.1 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + io.projectreactor + reactor-test + test + + + + + org.apache.velocity + velocity + 1.7 + + + + com.baomidou + mybatis-plus-generator + ${mybatis-plus-boot-starter.version} + + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-velocity/src/main/java/HelloVelocity.java b/springboot-225-velocity/src/main/java/HelloVelocity.java new file mode 100644 index 0000000..68a0a76 --- /dev/null +++ b/springboot-225-velocity/src/main/java/HelloVelocity.java @@ -0,0 +1,39 @@ +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +public class HelloVelocity { + public static void main(String[] args) { + VelocityEngine ve = new VelocityEngine(); +// ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); +// ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); +// ve.init(); + // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 + Properties p = new Properties(); + p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); + ve.init(p); + + Template t = ve.getTemplate("HelloVelocity.vm"); + VelocityContext ctx = new VelocityContext(); + + ctx.put("name", "velocity"); + ctx.put("date", (new Date()).toString()); + + List temp = new ArrayList(); + temp.add("1"); + temp.add("2"); + ctx.put("list", temp); + + StringWriter sw = new StringWriter(); + + t.merge(ctx, sw); + + System.out.println(sw.toString()); + } +} diff --git a/springboot-225-velocity/src/main/java/VelocityGenerator.java b/springboot-225-velocity/src/main/java/VelocityGenerator.java new file mode 100644 index 0000000..6230ca4 --- /dev/null +++ b/springboot-225-velocity/src/main/java/VelocityGenerator.java @@ -0,0 +1,67 @@ +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; + +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +public class VelocityGenerator { + public static void main(String[] args) { + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); + ve.init(); + // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 + Properties p = new Properties(); +// p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); +// ve.init(p); + + // 文件输出路径 + //使用这个目录生成的代码,是在target目录下的 +// String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; + p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\"); + String rootPath = p.getProperty("parent_path"); + + Template helloTpt = ve.getTemplate("HelloVelocity.vm"); + VelocityContext ctx = new VelocityContext(); + ctx.put("name", "velocity"); + ctx.put("date", (new Date()).toString()); + List temp = new ArrayList(); + temp.add("1"); + temp.add("2"); + ctx.put("list", temp); + merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); + + + Template controllerTemplate = ve.getTemplate("controller.java.vm"); + VelocityContext controllerContext = new VelocityContext(); + controllerContext.put("package","controller"); + controllerContext.put("restControllerStyle",true); + controllerContext.put("entityObjectName","test"); + controllerContext.put("controllerName","TestController"); + controllerContext.put("serviceName","TestService"); + controllerContext.put("serviceObjectName","testServiceImpl"); + merge(controllerTemplate,controllerContext,rootPath+"/controller/TestController.java"); + + System.out.println("success..."); + } + + private static void merge(Template template, VelocityContext ctx, String path) { + PrintWriter writer = null; + try { + writer = new PrintWriter(path); + template.merge(ctx, writer); + writer.flush(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } finally { + writer.close(); + } + } +} diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/Springboot225VelocityApplication.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/Springboot225VelocityApplication.java new file mode 100644 index 0000000..c371072 --- /dev/null +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/Springboot225VelocityApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225velocity; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225VelocityApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225VelocityApplication.class, args); + } + +} diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/config/Swagger2Config.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/config/Swagger2Config.java new file mode 100644 index 0000000..5b60ae4 --- /dev/null +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/config/Swagger2Config.java @@ -0,0 +1,35 @@ +package com.example.springboot225velocity.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 // 启用Swagger2 +public class Swagger2Config { + @Bean + public Docket createRestApi() {// 创建API基本信息 + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 + .paths(PathSelectors.any()) + .build(); + } + + @SuppressWarnings("deprecation") + private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示 + return new ApiInfoBuilder() + .title("自动生成代码系统-接口API")// API 标题 + .description("自动生成代码系统-接口API")// API描述 + .contact("nbbt@")// 联系人 + .version("1.0")// 版本号 + .build(); + } +} diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/HelloController.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/HelloController.java new file mode 100644 index 0000000..99083dd --- /dev/null +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/HelloController.java @@ -0,0 +1,23 @@ +package com.example.springboot225velocity.controller; + +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value = "/hello") +@Slf4j +@Data +public class HelloController { + @GetMapping("/test") + public String test( +// HttpServletRequest request +// @RequestBody Object ${param1} + ){ +// request.getParameter(${}); +// request.getParameterMap(); + return "hello test"; + } +} diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java new file mode 100644 index 0000000..ff42816 --- /dev/null +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java @@ -0,0 +1,77 @@ +package com.example.springboot225velocity.controller; + +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +@RestController +@RequestMapping("/velocityGenerator") +public class VelocityGeneratorController { + + @RequestMapping("/generate") + public void generate() { + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); + ve.init(); + // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 + Properties p = new Properties(); +// p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); +// ve.init(p); + + // 文件输出路径 + //使用这个目录生成的代码,是在target目录下的 +// String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; + p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\"); + String rootPath = p.getProperty("parent_path"); + + Template helloTpt = ve.getTemplate("HelloVelocity.vm"); + VelocityContext ctx = new VelocityContext(); + ctx.put("name", "velocity"); + ctx.put("date", (new Date()).toString()); + List temp = new ArrayList(); + temp.add("1"); + temp.add("2"); + ctx.put("list", temp); + merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); + + + Template controllerTemplate = ve.getTemplate("controller.java.vm"); + VelocityContext controllerContext = new VelocityContext(); + controllerContext.put("package","controller"); + controllerContext.put("restControllerStyle",true); + controllerContext.put("entityObjectName","test"); + controllerContext.put("controllerName","TestController"); + controllerContext.put("serviceName","TestService"); + controllerContext.put("serviceObjectName","testServiceImpl"); + merge(controllerTemplate,controllerContext,rootPath+"/controller/TestController.java"); + + + + System.out.println("success..."); + } + + private static void merge(Template template, VelocityContext ctx, String path) { + PrintWriter writer = null; + try { + writer = new PrintWriter(path); + template.merge(ctx, writer); + writer.flush(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } finally { + writer.close(); + } + } +} diff --git a/springboot-225-velocity/src/main/resources/HelloVelocity.vm b/springboot-225-velocity/src/main/resources/HelloVelocity.vm new file mode 100644 index 0000000..ea8cd68 --- /dev/null +++ b/springboot-225-velocity/src/main/resources/HelloVelocity.vm @@ -0,0 +1,7 @@ +#set( $iAmVariable = "good!" ) +Welcome $name to velocity.com +today is $date. +#foreach ($i in $list) + $i +#end +$iAmVariable \ No newline at end of file diff --git a/springboot-225-velocity/src/main/resources/application.properties b/springboot-225-velocity/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/springboot-225-velocity/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/springboot-225-velocity/src/main/resources/controller.java.vm b/springboot-225-velocity/src/main/resources/controller.java.vm new file mode 100644 index 0000000..c0a16ac --- /dev/null +++ b/springboot-225-velocity/src/main/resources/controller.java.vm @@ -0,0 +1,113 @@ +package ${package}; + +import lombok.*; +import org.springframework.web.bind.annotation.*; + +##/** +## * $!{table.comment} 控制器 +## * +## * @author ${author} +## * @since ${date} +## */ +@Slf4j +#if(${restControllerStyle}) +@RestController +#else +@Controller +#end +@RequestMapping("/${entityObjectName}") +#if(${swaggerTags}) +@Api(value = "$!{tableComment}API", tags = {"$!{tableComment}"}) +#else +@Api("$!{tableComment}API") +#end +public class ${controllerName} { + +## @Autowired +## private ${serviceName} ${serviceObjectName}; + +## /** +## * 添加$!{table.comment} +## */ +## @PostMapping("/add") +###if(${cfg.requiresPermissions}) +## @RequiresPermissions("$!{cfg.colonTableName}:add") +###end +###if(${cfg.operationLog}) +## @OperationLog(name = "添加$!{tableComment}", type = OperationLogType.ADD) +###end +## @ApiOperation(value = "添加$!{tableComment}", response = ApiResult.class) +## public ApiResult add${entity}(#if(${cfg.paramValidation})@Validated(Add.class) #end@RequestBody ${entity} ${cfg.entityObjectName}) throws Exception { +## boolean flag = ${cfg.serviceObjectName}.save${entity}(${cfg.entityObjectName}); +## return ApiResult.result(flag); +## } +## +## /** +## * 修改$!{table.comment} +## */ +## @PostMapping("/update") +###if(${cfg.requiresPermissions}) +## @RequiresPermissions("$!{cfg.colonTableName}:update") +###end +###if(${cfg.operationLog}) +## @OperationLog(name = "修改$!{table.comment}", type = OperationLogType.UPDATE) +###end +## @ApiOperation(value = "修改$!{table.comment}", response = ApiResult.class) +## public ApiResult update${entity}(#if(${cfg.paramValidation})@Validated(Update.class) #end@RequestBody ${entity} ${cfg.entityObjectName}) throws Exception { +## boolean flag = ${cfg.serviceObjectName}.update${entity}(${cfg.entityObjectName}); +## return ApiResult.result(flag); +## } +## +## /** +## * 删除$!{table.comment} +## */ +## @PostMapping("/delete/{id}") +###if(${cfg.requiresPermissions}) +## @RequiresPermissions("$!{cfg.colonTableName}:delete") +###end +###if(${cfg.operationLog}) +## @OperationLog(name = "删除$!{table.comment}", type = OperationLogType.DELETE) +###end +## @ApiOperation(value = "删除$!{table.comment}", response = ApiResult.class) +## public ApiResult delete${entity}(@PathVariable("id") Long id) throws Exception { +## boolean flag = ${cfg.serviceObjectName}.delete${entity}(id); +## return ApiResult.result(flag); +## } +## +## /** +## * 获取$!{table.comment}详情 +## */ +## @GetMapping("/info/{id}") +###if(${cfg.requiresPermissions}) +## @RequiresPermissions("$!{cfg.colonTableName}:info") +###end +###if(${cfg.operationLog}) +## @OperationLog(name = "$!{table.comment}详情", type = OperationLogType.INFO) +###end +## @ApiOperation(value = "$!{table.comment}详情", response = ${entity}${cfg.queryVo}.class) +## public ApiResult<${entity}${cfg.queryVo}> get${entity}(@PathVariable("id") Long id) throws Exception { +###if(${cfg.generatorStrategy} == 'SINGLE') +## ${entity}${cfg.queryVo} ${cfg.entityObjectName}${cfg.queryVo} = ${cfg.serviceObjectName}.getById(id); +###else +## ${entity}${cfg.queryVo} ${cfg.entityObjectName}${cfg.queryVo} = ${cfg.serviceObjectName}.get${entity}ById(id); +###end +## return ApiResult.ok(${cfg.entityObjectName}${cfg.queryVo}); +## } +## +## /** +## * $!{table.comment}分页列表 +## */ +## @PostMapping("/getPageList") +###if(${cfg.requiresPermissions}) +## @RequiresPermissions("$!{cfg.colonTableName}:page") +###end +###if(${cfg.operationLog}) +## @OperationLog(name = "$!{table.comment}分页列表", type = OperationLogType.PAGE) +###end +## @ApiOperation(value = "$!{table.comment}分页列表", response = ${entity}${cfg.queryVo}.class) +## public ApiResult> get${entity}PageList(#if(${cfg.paramValidation})@Validated #end@RequestBody ${entity}${cfg.pageParam} ${cfg.entityObjectName}${cfg.pageParam}) throws Exception { +## Paging<${entity}${cfg.queryVo}> paging = ${cfg.entityObjectName}Service.get${entity}PageList(${cfg.entityObjectName}${cfg.pageParam}); +## return ApiResult.ok(paging); +## } + +} \ No newline at end of file diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/CodeGenerator.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/CodeGenerator.java new file mode 100644 index 0000000..c1b1cad --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/CodeGenerator.java @@ -0,0 +1,450 @@ +package com.example.springboot225velocity;/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.toolkit.StringPool; +import com.baomidou.mybatisplus.generator.AutoGenerator; +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.baomidou.mybatisplus.generator.config.*; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.example.springboot225velocity.config.*; +import com.example.springboot225velocity.config.query.SpringBootPlusMySqlQuery; +import com.example.springboot225velocity.config.query.SpringBootPlusSqlServerQuery; +import com.example.springboot225velocity.constant.GeneratorConstant; +import com.example.springboot225velocity.exception.GeneratorException; +import com.example.springboot225velocity.properties.GeneratorProperties; +import lombok.Data; +import lombok.experimental.Accessors; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; + +/** + * spring-boot-plus代码生成器 + * + * @author geekidea + * @date 2018-11-08 + */ +@Slf4j +@Data +@Component +@Accessors(chain = true) +public class CodeGenerator { + + public void generator(GeneratorProperties generatorProperties) { + if (generatorProperties == null) { + throw new GeneratorException("generatorProperties不能为空"); + } + List tableConfig = generatorProperties.getTableConfig(); + if (CollectionUtils.isEmpty(tableConfig)) { + throw new GeneratorException("tableConfig不能为空"); + } + + // 循环生成 + for (TableConfig generatorTable : tableConfig) { + String tableName = generatorTable.getTableName(); + String pkIdName = generatorTable.getPkIdName(); + // 生成代码 + generator(tableName, pkIdName, generatorProperties); + } + } + + /** + * 初始化变量 + */ + public void init(String tableName, GeneratorProperties generatorProperties) { + String parentPackage = generatorProperties.getParentPackage(); + if (StringUtils.isBlank(parentPackage)) { + throw new GeneratorException("项目父包不能为空"); + } + // 如果包路径为空,转换包名称路径 + if (StringUtils.isNotBlank(parentPackage)) { + generatorProperties.setParentPackagePath(parentPackage.replaceAll("\\.", Matcher.quoteReplacement(File.separator))); + } + + String mavenModuleName = generatorProperties.getMavenModuleName(); + if (StringUtils.isBlank(mavenModuleName)) { + throw new GeneratorException("mavenModuleName不能为空"); + } + if (StringUtils.isBlank(tableName)) { + throw new GeneratorException("tableName不能为空"); + } + + // 如果是单表操作,不生成QueryVo + GeneratorConfig generatorConfig = generatorProperties.getGeneratorConfig(); + if (GeneratorStrategy.SINGLE == generatorConfig.generatorStrategy) { + generatorProperties.getGeneratorConfig().setGeneratorQueryVo(false); + } + + } + + + /** + * 生成代码 + */ + public void generator(String tableName, String pkIdName, GeneratorProperties generatorProperties) { + // 初始化变量 + init(tableName, generatorProperties); + + // 代码生成器 + AutoGenerator autoGenerator = new AutoGenerator(); + + MybatisPlusGeneratorConfig mybatisPlusGeneratorConfig = generatorProperties.getMybatisPlusGeneratorConfig(); + if (mybatisPlusGeneratorConfig == null) { + throw new GeneratorException("mybatisPlusGeneratorConfig不能为空"); + } + + // 全局配置 + GlobalConfig globalConfig = mybatisPlusGeneratorConfig.getGlobalConfig(); + if (globalConfig == null) { + throw new GeneratorException("globalConfig不能为空"); + } + + String mavenModuleName = generatorProperties.getMavenModuleName(); + String moduleName = generatorProperties.getModuleName(); + String outputDir = generatorProperties.getOutputDir(); + String javaOutputDir = null; + String resourcesOutputDir = null; + String mapperXmlOutputDir = null; + + if (StringUtils.isBlank(outputDir)) { + String rootProjectFile = System.getProperty(GeneratorConstant.USER_DIR); + outputDir = rootProjectFile + File.separator + mavenModuleName; + } + log.info("outputDir: {}", outputDir); + javaOutputDir = outputDir + GeneratorConstant.JAVA_DIR; + resourcesOutputDir = outputDir + GeneratorConstant.RESOURCES_DIR; + mapperXmlOutputDir = outputDir + GeneratorConstant.MAPPER_DIR; + + // 设置java代码输出目录绝对路径 + globalConfig.setOutputDir(javaOutputDir); + + // 是否覆盖文件 + globalConfig.setFileOverride(generatorProperties.isFileOverride()); + + // 设置作者 + globalConfig.setAuthor(generatorProperties.getAuthor()); + + if (StringUtils.isBlank(globalConfig.getServiceName())) { + // %sService 生成 UserService,%s 为占位符 + globalConfig.setServiceName(GeneratorConstant.SERVICE_NAME); + } + + // 设置全局配置 + autoGenerator.setGlobalConfig(globalConfig); + + // 数据源配置 + DataSourceConfig dataSourceConfig = generatorProperties.getDataSourceConfig(); + if (dataSourceConfig == null) { + throw new GeneratorException("dataSourceConfig不能为空"); + } + + // 设置元数据自定义查询 + DbType dbType = dataSourceConfig.getDbType(); + if (DbType.MYSQL == dbType) { + // 设置MySQL元数据自定义查询 + dataSourceConfig.setDbQuery(new SpringBootPlusMySqlQuery()); + } else if (DbType.SQL_SERVER2005 == dbType || DbType.SQL_SERVER == dbType) { + // 设置SQLServer元数据自定义查询 + dataSourceConfig.setDbQuery(new SpringBootPlusSqlServerQuery()); + } + + // 设置数据源 + autoGenerator.setDataSource(dataSourceConfig); + + // 包配置 + PackageConfig packageConfig = mybatisPlusGeneratorConfig.getPackageConfig(); + packageConfig.setModuleName(moduleName); + packageConfig.setParent(generatorProperties.getParentPackage()); + + // 设置包信息 + autoGenerator.setPackageInfo(packageConfig); + + // 策略配置 + StrategyConfig strategyConfig = mybatisPlusGeneratorConfig.getStrategyConfig(); + if (strategyConfig == null) { + throw new GeneratorException("strategyConfig不能为空"); + } + // 设置生成的表 + strategyConfig.setInclude(tableName); + // 表前缀 + List tablePrefixList = generatorProperties.getTablePrefix(); + if (CollectionUtils.isNotEmpty(tablePrefixList)) { + strategyConfig.setTablePrefix(tablePrefixList.toArray(new String[]{})); + } + + + if (StringUtils.isBlank(strategyConfig.getSuperEntityClass())) { + // 自定义继承的Entity类全称,带包名 + strategyConfig.setSuperEntityClass(GeneratorConstant.SUPER_ENTITY_CLASS); + } + if (StringUtils.isBlank(strategyConfig.getSuperControllerClass())) { + // 自定义继承的Controller类全称,带包名 + strategyConfig.setSuperControllerClass(GeneratorConstant.SUPER_CONTROLLER_CLASS); + } + // 自定义继承的Service类全称,带包名 + strategyConfig.setSuperServiceClass(GeneratorConstant.SUPER_SERVICE_CLASS); + // 自定义继承的ServiceImpl类全称,带包名 + strategyConfig.setSuperServiceImplClass(GeneratorConstant.SUPER_SERVICE_IMPL_CLASS); + + // 设置策略 + autoGenerator.setStrategy(strategyConfig); + + // 自定义配置 + InjectionConfig injectionConfig = new InjectionConfig() { + @Override + public void initMap() { + List tableInfos = this.getConfig().getTableInfoList(); + if (CollectionUtils.isEmpty(tableInfos)) { + throw new GeneratorException(tableName + "表不存在"); + } + + String finalModuleName = ""; + if (StringUtils.isNotBlank(moduleName)) { + finalModuleName = StringPool.DOT + moduleName; + } + TableInfo tableInfo = this.getConfig().getTableInfoList().get(0); + String entityName = tableInfo.getEntityName(); + String entityObjectName = toCamel(entityName); + String colonTableName = underlineToColon(tableName); + + String parentPackage = generatorProperties.getParentPackage(); + ProjectConfig projectConfig = generatorProperties.getProjectConfig(); + + String superPageParamClass = projectConfig.getSuperPageParamClass(); + String idParamClass = projectConfig.getIdParamClass(); + String pagingClass = projectConfig.getPagingClass(); + String pageInfoClass = projectConfig.getPageInfoClass(); + String apiResultClass = projectConfig.getApiResultClass(); + String superPageOrderParamClass = projectConfig.getSuperPageOrderParamClass(); + + GeneratorConfig generatorConfig = generatorProperties.getGeneratorConfig(); + + GeneratorStrategy generatorStrategy = generatorConfig.getGeneratorStrategy(); + String generatorStrategyName = generatorStrategy.name(); + boolean paramValidation = generatorConfig.isParamValidation(); + boolean requiresPermissions = generatorConfig.isRequiresPermissions(); + + Map map = new HashMap<>(); + // 查询参数包路径 + String pageParamPackage = parentPackage + finalModuleName + StringPool.DOT + GeneratorConstant.PARAM; + map.put("pageParamPackage", pageParamPackage); + // 查询参数类路径 + map.put("pageParamClass", pageParamPackage + StringPool.DOT + entityName + GeneratorConstant.PAGE_PARAM); + // 查询参数共公包路径 + map.put("superPageParamClass", superPageParamClass); + map.put("superPageOrderParamClass", superPageOrderParamClass); + // 查询参数共公包路径 + map.put("idParamClass", idParamClass); + // 响应结果包路径 + String queryVoPackage = parentPackage + finalModuleName + StringPool.DOT + GeneratorConstant.VO; + map.put("queryVoPackage", queryVoPackage); + // 响应结果类路径 + map.put("queryVoClass", queryVoPackage + StringPool.DOT + entityName + GeneratorConstant.QUERY_VO); + // 实体对象名称 + map.put("entityObjectName", entityObjectName); + // service对象名称 + map.put("serviceObjectName", entityObjectName + GeneratorConstant.SERVICE); + // mapper对象名称 + map.put("mapperObjectName", entityObjectName + GeneratorConstant.MAPPER); + // 主键ID列名 + map.put("pkIdName", pkIdName); + // 主键ID驼峰名称 + map.put("pkIdCamelName", underlineToCamel(pkIdName)); + // 导入分页类 + map.put("pagingClass", pagingClass); + map.put("pageInfoClass", pageInfoClass); + // ApiResult + map.put("apiResultClass", apiResultClass); + // 代码生成策略 + map.put("generatorStrategy", generatorStrategyName); + // 代码Validation校验 + map.put("paramValidation", paramValidation); + // 冒号连接的表名称 + map.put("colonTableName", colonTableName); + // 是否生成Shiro RequiresPermissions注解 + map.put("requiresPermissions", requiresPermissions); + // 设置常量值 + map.put("pageParam", GeneratorConstant.PAGE_PARAM); + map.put("validatorAddPackage", GeneratorConstant.VALIDATOR_ADD_PACKAGE); + map.put("validatorUpdatePackage", GeneratorConstant.VALIDATOR_UPDATE_PACKAGE); + // 如果是但表模式,queryVO值为null + if (GeneratorStrategy.SINGLE == generatorStrategy) { + map.put("queryVo", ""); + } else { + map.put("queryVo", GeneratorConstant.QUERY_VO); + } + map.put("generatorQueryVo", generatorConfig.isGeneratorQueryVo()); + map.put("generatorPageParam", generatorConfig.isGeneratorPageParam()); + map.put("pageListOrder", generatorConfig.isPageListOrder()); + map.put("swaggerTags", generatorConfig.isSwaggerTags()); + map.put("operationLog", generatorConfig.isOperationLog()); + map.put("module", moduleName); + this.setMap(map); + } + }; + List focList = new ArrayList<>(); + + + GeneratorConfig generatorConfig = generatorProperties.getGeneratorConfig(); + + String parentPackagePath = generatorProperties.getParentPackagePath(); + String finalJavaOutputDir = javaOutputDir; + String finalMapperXmlOutputDir = mapperXmlOutputDir; + + String modulePath = ""; + if (StringUtils.isNotBlank(moduleName)) { + modulePath = File.separator + moduleName; + } + final String finalModulePath = modulePath; + + // 生成Mapper XML + if (generatorConfig.isGeneratorMapperXml()) { + focList.add(new FileOutConfig(GeneratorConstant.MAPPER_XML_TEMPLATE_PATH) { + @Override + public String outputFile(TableInfo tableInfo) { + // 指定Mapper XML文件路径 + return finalMapperXmlOutputDir + finalModulePath + File.separator + + tableInfo.getEntityName() + GeneratorConstant.MAPPER + StringPool.DOT_XML; + } + }); + } + + // 自定义pageParam模板 + if (generatorConfig.isGeneratorPageParam()) { + focList.add(new FileOutConfig(GeneratorConstant.PAGE_PARAM_TEMPLATE_PATH) { + @Override + public String outputFile(TableInfo tableInfo) { + return finalJavaOutputDir + File.separator + parentPackagePath + finalModulePath + File.separator + GeneratorConstant.PARAM + + File.separator + tableInfo.getEntityName() + GeneratorConstant.PAGE_PARAM + StringPool.DOT_JAVA; + } + }); + } + + // 自定义queryVo模板 + if (generatorConfig.isGeneratorQueryVo()) { + focList.add(new FileOutConfig(GeneratorConstant.QUERY_VO_TEMPLATE_PATH) { + @Override + public String outputFile(TableInfo tableInfo) { + return finalJavaOutputDir + File.separator + parentPackagePath + finalModulePath + File.separator + GeneratorConstant.VO + + File.separator + tableInfo.getEntityName() + GeneratorConstant.QUERY_VO + StringPool.DOT_JAVA; + } + }); + } + + injectionConfig.setFileOutConfigList(focList); + + // 设置自定义配置 + autoGenerator.setCfg(injectionConfig); + + // 模版生成配置,设置为空,表示不生成 + TemplateConfig templateConfig = new TemplateConfig(); + // xml使用自定义输出 + templateConfig.setXml(null); + // 是否生成entity + if (!generatorConfig.isGeneratorEntity()) { + templateConfig.setEntity(null); + } + // 是否生成controller + if (!generatorConfig.isGeneratorController()) { + templateConfig.setController(null); + } + // 是否生成service + if (!generatorConfig.isGeneratorService()) { + templateConfig.setService(null); + } + // 是否生成serviceImpl + if (!generatorConfig.isGeneratorServiceImpl()) { + templateConfig.setServiceImpl(null); + } + // 是否生成mapper + if (!generatorConfig.isGeneratorMapper()) { + templateConfig.setMapper(null); + } + + // 设置模板引擎 + autoGenerator.setTemplate(templateConfig); + + // 执行代码生成 + autoGenerator.execute(); + } + + /** + * 下划线专程驼峰命名 + * sys_user --> sysUser + * + * @param underline + * @return + */ + public static String underlineToCamel(String underline) { + if (StringUtils.isNotBlank(underline)) { + return NamingStrategy.underlineToCamel(underline); + } + return null; + } + + /** + * 下划线转换成帕斯卡命名 + * sys_user --> SysUser + * + * @param underline + * @return + */ + public static String underlineToPascal(String underline) { + if (StringUtils.isNotBlank(underline)) { + return NamingStrategy.capitalFirst(NamingStrategy.underlineToCamel(underline)); + } + return null; + } + + /** + * 下划线转换成冒号连接命名 + * sys_user --> sys:user + * + * @param underline + * @return + */ + public static String underlineToColon(String underline) { + if (StringUtils.isBlank(underline)) { + return null; + } + String string = underline.toLowerCase(); + return string.replaceAll("_", ":"); + } + + /** + * 首字母小写 + * + * @param name + * @return + */ + public static String toCamel(String name) { + if (StringUtils.isBlank(name)) { + return null; + } + return name.substring(0, 1).toLowerCase() + name.substring(1); + } + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/SpringBootPlusGenerator.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/SpringBootPlusGenerator.java new file mode 100644 index 0000000..1ae4d73 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/SpringBootPlusGenerator.java @@ -0,0 +1,104 @@ +package com.example.springboot225velocity;/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.generator.config.rules.DateType; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.example.springboot225velocity.config.GeneratorStrategy; +import com.example.springboot225velocity.constant.GeneratorConstant; +import com.example.springboot225velocity.properties.GeneratorProperties; +import org.springframework.stereotype.Component; + +/** + * spring-boot-plus代码生成器入口类 + * + * @author geekidea + * @date 2019-10-22 + **/ +@Component +public class SpringBootPlusGenerator { + + /** + * 生成代码 + * @param args + */ + public static void main(String[] args) { + GeneratorProperties generatorProperties = new GeneratorProperties(); + + // 设置基本信息 + generatorProperties + .setMavenModuleName("example") + .setParentPackage("com.example") + .setModuleName("foobar") + .setAuthor("geekidea") + .setFileOverride(true); + + // 设置表信息 + generatorProperties.addTable("foo_bar","id"); + // 设置表前缀 + // generatorProperties.setTablePrefix(Arrays.asList("tb_")); + + // 数据源配置 + generatorProperties.getDataSourceConfig() + .setDbType(DbType.MYSQL) + .setUsername("root") + .setPassword("root") + .setDriverName("com.mysql.jdbc.Driver") + .setUrl("jdbc:mysql://localhost:3306/spring_boot_plus?useUnicode=true&characterEncoding=UTF-8&useSSL=false"); + + // 生成配置 + generatorProperties.getGeneratorConfig() + .setGeneratorStrategy(GeneratorStrategy.SINGLE) + .setGeneratorEntity(true) + .setGeneratorController(true) + .setGeneratorService(true) + .setGeneratorServiceImpl(true) + .setGeneratorMapper(true) + .setGeneratorMapperXml(true) + .setGeneratorPageParam(true) + .setGeneratorQueryVo(true) + .setRequiresPermissions(false) + .setPageListOrder(true) + .setParamValidation(true) + .setSwaggerTags(true) + .setOperationLog(true); + + // 全局配置 + generatorProperties.getMybatisPlusGeneratorConfig().getGlobalConfig() + .setOpen(true) + .setSwagger2(true) + .setIdType(IdType.AUTO) + .setDateType(DateType.ONLY_DATE); + + // 策略配置 + generatorProperties.getMybatisPlusGeneratorConfig().getStrategyConfig() + .setNaming(NamingStrategy.underline_to_camel) + .setColumnNaming(NamingStrategy.underline_to_camel) + .setEntityLombokModel(true) + .setRestControllerStyle(true) + .setControllerMappingHyphenStyle(true) + .setVersionFieldName(GeneratorConstant.VERSION) + .setLogicDeleteFieldName(GeneratorConstant.DELETED); + + // 生成代码 + CodeGenerator codeGenerator = new CodeGenerator(); + codeGenerator.generator(generatorProperties); + + } + + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/Springboot225VelocityApplicationTests.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/Springboot225VelocityApplicationTests.java new file mode 100644 index 0000000..ef2818c --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/Springboot225VelocityApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225velocity; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225VelocityApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorConfig.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorConfig.java new file mode 100644 index 0000000..e51556b --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorConfig.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + +/** + * 生成配置 + * + * @author geekidea + * @date 2020/3/13 + **/ +@Data +@Accessors(chain = true) +public class GeneratorConfig { + /** + * 代码生成策略 + */ + @NestedConfigurationProperty + public GeneratorStrategy generatorStrategy = GeneratorStrategy.ALL; + /** + * 是否生成实体类 + */ + private boolean generatorEntity = true; + /** + * 是否生成控制器 + */ + private boolean generatorController = true; + /** + * 是否生成service接口 + */ + private boolean generatorService = true; + /** + * 是否生成service实现类 + */ + private boolean generatorServiceImpl = true; + /** + * 是否生成Mapper + */ + private boolean generatorMapper = true; + /** + * 是否生成Mapper XML + */ + private boolean generatorMapperXml = true; + /** + * 是否生成查询参数 + */ + private boolean generatorPageParam = true; + /** + * 是否生成查询VO + */ + private boolean generatorQueryVo = true; + /** + * 是否生成Shiro RequiresPermissions 注解 + */ + private boolean requiresPermissions = true; + /** + * 分页列表查询是否排序 true:有排序参数/false:无 + */ + private boolean pageListOrder = true; + /** + * 是否生成validation校验,true:生成/false:不生成 + */ + private boolean paramValidation = true; + /** + * 是否生成Swagger tags + * true: @Api(value = "系统用户API",tags = {"系统用户"}) + * false: @Api("系统用户API") + */ + private boolean swaggerTags = true; + + /** + * 是否生成系统操作日志注解:@OperationLog + */ + private boolean operationLog = true; + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorStrategy.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorStrategy.java new file mode 100644 index 0000000..c069517 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/GeneratorStrategy.java @@ -0,0 +1,30 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config; + +/** + * 生成策略 + * SIMPLE 生成最基本的代码 + * SINGLE 生成单表操作代码 + * ALL 生成所有的代码 + * + * @author geekidea + * @date 2020/3/13 + **/ +public enum GeneratorStrategy { + SIMPLE, SINGLE, ALL +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/MybatisPlusGeneratorConfig.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/MybatisPlusGeneratorConfig.java new file mode 100644 index 0000000..b6f16a2 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/MybatisPlusGeneratorConfig.java @@ -0,0 +1,51 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config; + +import com.baomidou.mybatisplus.generator.config.GlobalConfig; +import com.baomidou.mybatisplus.generator.config.PackageConfig; +import com.baomidou.mybatisplus.generator.config.StrategyConfig; +import lombok.Data; +import lombok.experimental.Accessors; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + +/** + * mybatisplus相关配置 + * @author geekidea + * @date 2020/3/13 + **/ +@Data +@Accessors(chain = true) +public class MybatisPlusGeneratorConfig { + /** + * 全局配置 + */ + @NestedConfigurationProperty + private GlobalConfig globalConfig = new GlobalConfig(); + + /** + * 包配置 + */ + @NestedConfigurationProperty + private PackageConfig packageConfig = new PackageConfig(); + + /** + * 策略配置 + */ + private StrategyConfig strategyConfig = new StrategyConfig(); + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/ProjectConfig.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/ProjectConfig.java new file mode 100644 index 0000000..5e3af4c --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/ProjectConfig.java @@ -0,0 +1,64 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config; + +import com.example.springboot225velocity.constant.GeneratorConstant; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * 项目信息配置 + * @author geekidea + * @date 2020/3/13 + **/ +@Data +@Accessors(chain = true) +public class ProjectConfig { + + /** + * 分页参数后缀 + */ + private String pageParamSuffix = GeneratorConstant.PAGE_PARAM; + /** + * QueryVo后缀 + */ + private String queryVoSuffix = GeneratorConstant.QUERY_VO; + /** + * 分页参数父类全称,带包名 + */ + private String superPageParamClass = GeneratorConstant.SUPER_PAGE_PARAM_CLASS; + /** + * 分页对象类全称,带包名 + */ + private String pagingClass = GeneratorConstant.PAGING_CLASS; + /** + * 分页信息类全称,带包名 + */ + private String pageInfoClass = GeneratorConstant.PAGE_INFO_CLASS; + /** + * 分页排序参数父类全称,带包名 + */ + private String superPageOrderParamClass = GeneratorConstant.SUPER_PAGE_ORDER_PARAM_CLASS; + /** + * 公共id参数类全称,带包名 + */ + private String idParamClass = GeneratorConstant.ID_PARAM_CLASS; + /** + * 公共结果类全称,带包名 + */ + private String apiResultClass = GeneratorConstant.API_RESULT_CLASS; +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/TableConfig.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/TableConfig.java new file mode 100644 index 0000000..6e47a20 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/TableConfig.java @@ -0,0 +1,41 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config; + +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * 生成的表信息配置 + * @author geekidea + * @date 2020/3/13 + **/ +@Data +@Accessors(chain = true) +public class TableConfig { + + /** + * 生成的表名称 + */ + private String tableName; + + /** + * 主键数据库列名称 + */ + private String pkIdName = "id"; + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusMySqlQuery.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusMySqlQuery.java new file mode 100644 index 0000000..f290044 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusMySqlQuery.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config.query; + +import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery; + +/** + * MySQL代码生成查询是否为空的列 + * + * @author geekidea + * @date 2019-10-11 + **/ +public class SpringBootPlusMySqlQuery extends MySqlQuery { + + @Override + public String[] fieldCustom() { + return new String[]{"null", "default"}; + } + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusSqlServerQuery.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusSqlServerQuery.java new file mode 100644 index 0000000..249ed7e --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/config/query/SpringBootPlusSqlServerQuery.java @@ -0,0 +1,44 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.config.query; + +import com.baomidou.mybatisplus.generator.config.querys.SqlServerQuery; + +/** + * SQLServer自定义生成器查询SQL + * + * @author geekidea + * @date 2020-3-8 + **/ +public class SpringBootPlusSqlServerQuery extends SqlServerQuery { + + /** + * fix mybatisplus3.3.1 SQLServer SQL过滤表,TABLE_NAME报错问题 + * @return + */ + @Override + public String tablesSql() { + return "select TABLE_NAME,COMMENTS from (" + + " select cast(so.name as varchar(500)) as TABLE_NAME, " + + " cast(sep.value as varchar(500)) as COMMENTS from sysobjects so " + + " left JOIN sys.extended_properties sep on sep.major_id=so.id and sep.minor_id=0 " + + " where (xtype='U' or xtype='v')" + + ") tb " + + "where 1 = 1 "; + + } +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/constant/GeneratorConstant.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/constant/GeneratorConstant.java new file mode 100644 index 0000000..a45bded --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/constant/GeneratorConstant.java @@ -0,0 +1,141 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.constant; + +import java.io.File; + +/** + * 生成器常量 + * + * @author geekidea + * @date 2020/3/12 + **/ +public interface GeneratorConstant { + + /** + * 用户目录 + */ + String USER_DIR = "user.dir"; + /** + * java目录 src/main/java + */ + String JAVA_DIR = File.separator + "src" + File.separator + "main" + File.separator + "java"; + /** + * resources目录 src/main/resources + */ + String RESOURCES_DIR = File.separator + "src" + File.separator + "main" + File.separator + "resources"; + /** + * mapper目录 src/main/resources/mapper + */ + String MAPPER_DIR = RESOURCES_DIR + File.separator + "mapper"; + /** + * 参数 + */ + String PARAM = "param"; + /** + * 分页参数 + */ + String PAGE_PARAM = "PageParam"; + /** + * VO + */ + String VO = "vo"; + /** + * 查询VO + */ + String QUERY_VO = "QueryVo"; + /** + * Service + */ + String SERVICE = "Service"; + /** + * Mapper + */ + String MAPPER = "Mapper"; + /** + * Mapper XML template路径 + */ + String MAPPER_XML_TEMPLATE_PATH = File.separator + "templates" + File.separator + "mapper.xml.vm"; + /** + * 分页参数 template路径 + */ + String PAGE_PARAM_TEMPLATE_PATH = File.separator + "templates" + File.separator + "pageParam.java.vm"; + /** + * 查询VO template路径 + */ + String QUERY_VO_TEMPLATE_PATH = File.separator + "templates" + File.separator + "queryVo.java.vm"; + /** + * 乐观锁属性名称 + */ + String VERSION = "version"; + /** + * 逻辑删除属性名称 + */ + String DELETED = "deleted"; + /** + * Service名称 + */ + String SERVICE_NAME = "%sService"; + /** + * 自定义继承的Entity类全称,带包名 + */ + String SUPER_ENTITY_CLASS = "io.geekidea.springbootplus.framework.common.entity.BaseEntity"; + /** + * 自定义继承的Controller类全称,带包名 + */ + String SUPER_CONTROLLER_CLASS = "io.geekidea.springbootplus.framework.common.controller.BaseController"; + /** + * 自定义继承的Service类全称,带包名 + */ + String SUPER_SERVICE_CLASS = "io.geekidea.springbootplus.framework.common.service.BaseService"; + /** + * 自定义继承的ServiceImpl类全称,带包名 + */ + String SUPER_SERVICE_IMPL_CLASS = "io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl"; + /** + * 分页参数父类全称,带包名 + */ + String SUPER_PAGE_PARAM_CLASS = "io.geekidea.springbootplus.framework.core.pagination.BasePageParam"; + /** + * 分页排序参数父类全称,带包名 + */ + String SUPER_PAGE_ORDER_PARAM_CLASS = "io.geekidea.springbootplus.framework.core.pagination.BasePageOrderParam"; + /** + * 公共id参数类全称,带包名 + */ + String ID_PARAM_CLASS = "io.geekidea.springbootplus.framework.common.param.IdParam"; + /** + * 分页对象类全称,带包名 + */ + String PAGING_CLASS = "io.geekidea.springbootplus.framework.core.pagination.Paging"; + /** + * 分页信息类全称,带包名 + */ + String PAGE_INFO_CLASS = "io.geekidea.springbootplus.framework.core.pagination.PageInfo"; + /** + * 公共结果类全称,带包名 + */ + String API_RESULT_CLASS = "io.geekidea.springbootplus.framework.common.api.ApiResult"; + /** + * 分组验证Add.class类路径 + */ + String VALIDATOR_ADD_PACKAGE = "io.geekidea.springbootplus.framework.core.validator.groups.Add"; + /** + * 分组验证Update.class类路径 + */ + String VALIDATOR_UPDATE_PACKAGE = "io.geekidea.springbootplus.framework.core.validator.groups.Update"; +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/ApiCode.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/ApiCode.java new file mode 100644 index 0000000..70636af --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/ApiCode.java @@ -0,0 +1,132 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.exception; + +/** + *

+ * REST API 响应码 + *

+ * + * @author geekidea + * @since 2018-11-08 + */ +public enum ApiCode { + + /** + * 操作成功 + **/ + SUCCESS(200, "操作成功"), + /** + * 非法访问 + **/ + UNAUTHORIZED(401, "非法访问"), + /** + * 没有权限 + **/ + NOT_PERMISSION(403, "没有权限"), + /** + * 你请求的资源不存在 + **/ + NOT_FOUND(404, "你请求的资源不存在"), + /** + * 操作失败 + **/ + FAIL(500, "操作失败"), + /** + * 登录失败 + **/ + LOGIN_EXCEPTION(4000, "登录失败"), + /** + * 系统异常 + **/ + SYSTEM_EXCEPTION(5000, "系统异常"), + /** + * 请求参数校验异常 + **/ + PARAMETER_EXCEPTION(5001, "请求参数校验异常"), + /** + * 请求参数解析异常 + **/ + PARAMETER_PARSE_EXCEPTION(5002, "请求参数解析异常"), + /** + * HTTP内容类型异常 + **/ + HTTP_MEDIA_TYPE_EXCEPTION(5003, "HTTP内容类型异常"), + /** + * 系统处理异常 + **/ + SPRING_BOOT_PLUS_EXCEPTION(5100, "系统处理异常"), + /** + * 业务处理异常 + **/ + BUSINESS_EXCEPTION(5101, "业务处理异常"), + /** + * 数据库处理异常 + **/ + DAO_EXCEPTION(5102, "数据库处理异常"), + /** + * 验证码校验异常 + **/ + VERIFICATION_CODE_EXCEPTION(5103, "验证码校验异常"), + /** + * 登录授权异常 + **/ + AUTHENTICATION_EXCEPTION(5104, "登录授权异常"), + /** + * 没有访问权限 + **/ + UNAUTHENTICATED_EXCEPTION(5105, "没有访问权限"), + /** + * 没有访问权限 + **/ + UNAUTHORIZED_EXCEPTION(5106, "没有访问权限"), + /** + * JWT Token解析异常 + **/ + JWTDECODE_EXCEPTION(5107, "Token解析异常"), + + HTTP_REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION(5108, "METHOD NOT SUPPORTED"), + + ; + + private final int code; + private final String message; + + ApiCode(final int code, final String message) { + this.code = code; + this.message = message; + } + + public static ApiCode getApiCode(int code) { + ApiCode[] ecs = ApiCode.values(); + for (ApiCode ec : ecs) { + if (ec.getCode() == code) { + return ec; + } + } + return SUCCESS; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/GeneratorException.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/GeneratorException.java new file mode 100644 index 0000000..08514f4 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/GeneratorException.java @@ -0,0 +1,40 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.exception; + + +/** + * 代码生成异常 + * + * @author geekidea + * @date 2020/3/12 + */ +public class GeneratorException extends SpringBootPlusException { + private static final long serialVersionUID = 2556853577480934761L; + + public GeneratorException(String message) { + super(message); + } + + public GeneratorException(Integer errorCode, String message) { + super(errorCode, message); + } + + public GeneratorException(ApiCode apiCode) { + super(apiCode); + } +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/SpringBootPlusException.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/SpringBootPlusException.java new file mode 100644 index 0000000..c9c160c --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/exception/SpringBootPlusException.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.exception; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 自定义异常 + * @author geekidea + * @date 2018-11-08 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class SpringBootPlusException extends RuntimeException{ + + private static final long serialVersionUID = -2470461654663264392L; + + private Integer errorCode; + private String message; + + public SpringBootPlusException() { + super(); + } + + public SpringBootPlusException(String message) { + super(message); + this.message = message; + } + + public SpringBootPlusException(Integer errorCode, String message) { + super(message); + this.errorCode = errorCode; + this.message = message; + } + + public SpringBootPlusException(ApiCode apiCode) { + super(apiCode.getMessage()); + this.errorCode = apiCode.getCode(); + this.message = apiCode.getMessage(); + } + + public SpringBootPlusException(String message, Throwable cause) { + super(message, cause); + } + + public SpringBootPlusException(Throwable cause) { + super(cause); + } + +} diff --git a/springboot-225-velocity/src/test/java/com/example/springboot225velocity/properties/GeneratorProperties.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/properties/GeneratorProperties.java new file mode 100644 index 0000000..8260775 --- /dev/null +++ b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/properties/GeneratorProperties.java @@ -0,0 +1,135 @@ +/* + * Copyright 2019-2029 geekidea(https://github.com/geekidea) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.springboot225velocity.properties; + +import com.baomidou.mybatisplus.generator.config.DataSourceConfig; +import com.example.springboot225velocity.config.GeneratorConfig; +import com.example.springboot225velocity.config.MybatisPlusGeneratorConfig; +import com.example.springboot225velocity.config.ProjectConfig; +import com.example.springboot225velocity.config.TableConfig; +import lombok.Data; +import lombok.experimental.Accessors; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +/** + * spring-boot-plus代码生成配置属性 + * + * @author geekidea + * @date 2020/3/11 + **/ +@Data +@Accessors(chain = true) +@Component +@ConfigurationProperties(prefix = "spring-boot-plus.generator") +public class GeneratorProperties { + + /** + * Maven模块名称 + */ + private String mavenModuleName; + + /** + * 业务模块名称 + */ + private String moduleName; + + /** + * 生成的父包全路径名称 + */ + private String parentPackage; + + /** + * 生成的类文件路径 + */ + private String parentPackagePath; + + /** + * 开发人员名称 + */ + private String author; + + /** + * 生成文件的输出目录,root: 表示当前项目根目录 + */ + private String outputDir; + + /** + * 是否覆盖已有文件 + */ + private boolean fileOverride = false; + + /** + * 表前缀 + */ + private List tablePrefix; + + /** + * 表信息配置 + */ + @NestedConfigurationProperty + private List tableConfig = new ArrayList<>(); + + /** + * 数据库连接信息配置 + */ + @NestedConfigurationProperty + public DataSourceConfig dataSourceConfig = new DataSourceConfig(); + + /** + * 代码生成配置 + */ + @NestedConfigurationProperty + private GeneratorConfig generatorConfig = new GeneratorConfig(); + + /** + * mybatisplus相关配置 + */ + @NestedConfigurationProperty + private MybatisPlusGeneratorConfig mybatisPlusGeneratorConfig = new MybatisPlusGeneratorConfig(); + + /** + * 项目信息配置 + */ + @NestedConfigurationProperty + private ProjectConfig projectConfig = new ProjectConfig(); + + + public GeneratorProperties addTable(String tableName) { + this.addTable(tableName, null); + return this; + } + + public GeneratorProperties addTable(String tableName, String pkIdName) { + this.getTableConfig().add(new TableConfig().setTableName(tableName).setPkIdName(pkIdName)); + return this; + } + + public GeneratorProperties setTables(String... tableNames) { + if (tableNames == null) { + return this; + } + for (String tableName : tableNames) { + this.addTable(tableName); + } + return this; + } +} diff --git a/springboot-225-velocity/src/test/resources/templates/controller.java.vm b/springboot-225-velocity/src/test/resources/templates/controller.java.vm new file mode 100644 index 0000000..1553312 --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/controller.java.vm @@ -0,0 +1,162 @@ +package ${package.Controller}; + +import ${package.Entity}.${entity}; +import ${package.Service}.${table.serviceName}; +import lombok.extern.slf4j.Slf4j; +#if(${cfg.generatorStrategy} != 'SIMPLE') +#if(${cfg.generatorPageParam}) +import ${cfg.pageParamClass}; +#end +#if(${superControllerClassPackage}) +import ${superControllerClassPackage}; +#end +#if(${cfg.generatorQueryVo}) +import ${cfg.queryVoClass}; +#end +import ${cfg.apiResultClass}; +import ${cfg.pagingClass}; +import ${cfg.idParamClass}; +#if(${cfg.operationLog}) +import io.geekidea.springbootplus.framework.log.annotation.Module; +import io.geekidea.springbootplus.framework.log.annotation.OperationLog; +import io.geekidea.springbootplus.framework.log.enums.OperationLogType; +#end +#if(${cfg.paramValidation}) +import ${cfg.validatorAddPackage}; +import ${cfg.validatorUpdatePackage}; +import org.springframework.validation.annotation.Validated; +#end +#if(${cfg.requiresPermissions}) +import org.apache.shiro.authz.annotation.RequiresPermissions; +#end +#end +#if(${swagger2}) +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +#end +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +/** + * $!{table.comment} 控制器 + * + * @author ${author} + * @since ${date} + */ +@Slf4j +#if(${restControllerStyle}) +@RestController +#else +@Controller +#end +@RequestMapping("/${cfg.entityObjectName}") +#if(${cfg.operationLog}) +@Module("${cfg.module}") +#end +#if(${cfg.swaggerTags}) +@Api(value = "$!{table.comment}API", tags = {"$!{table.comment}"}) +#else +@Api("$!{table.comment}API") +#end +#if(${kotlin}) +class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end + +#else +#if(${superControllerClass}) +public class ${table.controllerName} extends ${superControllerClass} { +#else +public class ${table.controllerName} { +#end + + @Autowired + private ${table.serviceName} ${cfg.serviceObjectName}; + +#if(${cfg.generatorStrategy} != 'SIMPLE') + /** + * 添加$!{table.comment} + */ + @PostMapping("/add") +#if(${cfg.requiresPermissions}) + @RequiresPermissions("$!{cfg.colonTableName}:add") +#end +#if(${cfg.operationLog}) + @OperationLog(name = "添加$!{table.comment}", type = OperationLogType.ADD) +#end + @ApiOperation(value = "添加$!{table.comment}", response = ApiResult.class) + public ApiResult add${entity}(#if(${cfg.paramValidation})@Validated(Add.class) #end@RequestBody ${entity} ${cfg.entityObjectName}) throws Exception { + boolean flag = ${cfg.serviceObjectName}.save${entity}(${cfg.entityObjectName}); + return ApiResult.result(flag); + } + + /** + * 修改$!{table.comment} + */ + @PostMapping("/update") +#if(${cfg.requiresPermissions}) + @RequiresPermissions("$!{cfg.colonTableName}:update") +#end +#if(${cfg.operationLog}) + @OperationLog(name = "修改$!{table.comment}", type = OperationLogType.UPDATE) +#end + @ApiOperation(value = "修改$!{table.comment}", response = ApiResult.class) + public ApiResult update${entity}(#if(${cfg.paramValidation})@Validated(Update.class) #end@RequestBody ${entity} ${cfg.entityObjectName}) throws Exception { + boolean flag = ${cfg.serviceObjectName}.update${entity}(${cfg.entityObjectName}); + return ApiResult.result(flag); + } + + /** + * 删除$!{table.comment} + */ + @PostMapping("/delete/{id}") +#if(${cfg.requiresPermissions}) + @RequiresPermissions("$!{cfg.colonTableName}:delete") +#end +#if(${cfg.operationLog}) + @OperationLog(name = "删除$!{table.comment}", type = OperationLogType.DELETE) +#end + @ApiOperation(value = "删除$!{table.comment}", response = ApiResult.class) + public ApiResult delete${entity}(@PathVariable("id") Long id) throws Exception { + boolean flag = ${cfg.serviceObjectName}.delete${entity}(id); + return ApiResult.result(flag); + } + + /** + * 获取$!{table.comment}详情 + */ + @GetMapping("/info/{id}") +#if(${cfg.requiresPermissions}) + @RequiresPermissions("$!{cfg.colonTableName}:info") +#end +#if(${cfg.operationLog}) + @OperationLog(name = "$!{table.comment}详情", type = OperationLogType.INFO) +#end + @ApiOperation(value = "$!{table.comment}详情", response = ${entity}${cfg.queryVo}.class) + public ApiResult<${entity}${cfg.queryVo}> get${entity}(@PathVariable("id") Long id) throws Exception { +#if(${cfg.generatorStrategy} == 'SINGLE') + ${entity}${cfg.queryVo} ${cfg.entityObjectName}${cfg.queryVo} = ${cfg.serviceObjectName}.getById(id); +#else + ${entity}${cfg.queryVo} ${cfg.entityObjectName}${cfg.queryVo} = ${cfg.serviceObjectName}.get${entity}ById(id); +#end + return ApiResult.ok(${cfg.entityObjectName}${cfg.queryVo}); + } + + /** + * $!{table.comment}分页列表 + */ + @PostMapping("/getPageList") +#if(${cfg.requiresPermissions}) + @RequiresPermissions("$!{cfg.colonTableName}:page") +#end +#if(${cfg.operationLog}) + @OperationLog(name = "$!{table.comment}分页列表", type = OperationLogType.PAGE) +#end + @ApiOperation(value = "$!{table.comment}分页列表", response = ${entity}${cfg.queryVo}.class) + public ApiResult> get${entity}PageList(#if(${cfg.paramValidation})@Validated #end@RequestBody ${entity}${cfg.pageParam} ${cfg.entityObjectName}${cfg.pageParam}) throws Exception { + Paging<${entity}${cfg.queryVo}> paging = ${cfg.entityObjectName}Service.get${entity}PageList(${cfg.entityObjectName}${cfg.pageParam}); + return ApiResult.ok(paging); + } +#end + +} + +#end \ No newline at end of file diff --git a/springboot-225-velocity/src/test/resources/templates/entity.java.vm b/springboot-225-velocity/src/test/resources/templates/entity.java.vm new file mode 100644 index 0000000..3f0e37d --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/entity.java.vm @@ -0,0 +1,104 @@ +package ${package.Entity}; + +#foreach($pkg in ${table.importPackages}) +import ${pkg}; +#end +#if(${swagger2}) +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +#end +#if(${entityLombokModel}) +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +#end +#if(${cfg.paramValidation}) +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import ${cfg.validatorUpdatePackage}; +#end + +/** + * $!{table.comment} + * + * @author ${author} + * @since ${date} + */ +#if(${entityLombokModel}) +@Data +@Accessors(chain = true) +#if(${superEntityClass}) +@EqualsAndHashCode(callSuper = true) +#else +@EqualsAndHashCode(callSuper = false) +#end +#end +#if(${table.convert}) +@TableName("${table.name}") +#end +#if(${swagger2}) +@ApiModel(value = "${entity}对象") +#end +#if(${superEntityClass}) +public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { +#elseif(${activeRecord}) +public class ${entity} extends Model<${entity}> { +#else +public class ${entity} implements Serializable { +#end + private static final long serialVersionUID = 1L; + +## ---------- BEGIN 字段循环遍历 ---------- +#foreach($field in ${table.fields}) +## 如果没有默认值,且不为空,则设置非空校验 +#if(${cfg.paramValidation} && ${field.customMap.null} == 'NO' && !${field.customMap.default}) + #if(${field.keyIdentityFlag}) + @NotNull(message = "${field.propertyName}不能为空", groups = {Update.class}) + #elseif(${field.propertyType} == 'String') + @NotBlank(message = "${field.comment}不能为空") + #else + @NotNull(message = "${field.comment}不能为空") + #end +#end +#if("$!field.comment" != "") + #if(${swagger2}) + @ApiModelProperty("${field.comment}") + #else +/** + * ${field.comment} + */ + #end +#end +#if(${field.keyFlag}) +## 主键 +#if(${field.keyIdentityFlag}) + @TableId(value = "${field.name}", type = IdType.AUTO) +#elseif(!$null.isNull(${idType}) && "$!idType" != "") +## 设置主键注解 + @TableId(value = "${field.name}", type = IdType.${idType}) +#elseif(${field.convert}) + @TableId("${field.name}") +#end +## 普通字段 +#elseif(${field.fill}) +## ----- 存在字段填充设置 ----- +#if(${field.convert}) + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) +#else + @TableField(fill = FieldFill.${field.fill}) +#end +#elseif(${field.convert}) + @TableField("${field.name}") +#end +## 乐观锁注解 +#if(${versionFieldName}==${field.name}) + @Version +#end +## 逻辑删除注解 +#if(${logicDeleteFieldName}==${field.name}) + @TableLogic +#end + private ${field.propertyType} ${field.propertyName}; + +#end +} diff --git a/springboot-225-velocity/src/test/resources/templates/hello.java.vm b/springboot-225-velocity/src/test/resources/templates/hello.java.vm new file mode 100644 index 0000000..e69de29 diff --git a/springboot-225-velocity/src/test/resources/templates/mapper.java.vm b/springboot-225-velocity/src/test/resources/templates/mapper.java.vm new file mode 100644 index 0000000..3131cbe --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/mapper.java.vm @@ -0,0 +1,53 @@ +package ${package.Mapper}; + +import ${superMapperClassPackage}; +import ${package.Entity}.${entity}; +#if(${cfg.generatorPageParam}) +import ${cfg.pageParamClass}; +#end +#if(${cfg.generatorQueryVo}) +import ${cfg.queryVoClass}; +#end + +import org.springframework.stereotype.Repository; + +#if(${cfg.generatorStrategy} != 'SIMPLE') +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Param; +import java.io.Serializable; +#end + +/** + * $!{table.comment} Mapper 接口 + * + * @author ${author} + * @since ${date} + */ +#if(${kotlin}) +interface ${table.mapperName} : ${superMapperClass}<${entity}> +#else +@Repository +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { + +#if(${cfg.generatorStrategy} == 'ALL') + /** + * 根据ID获取查询对象 + * + * @param id + * @return + */ + ${entity}${cfg.queryVo} get${entity}ById(Serializable id); + + /** + * 获取分页对象 + * + * @param page + * @param ${cfg.entityObjectName}QueryParam + * @return + */ + IPage<${entity}${cfg.queryVo}> get${entity}PageList(@Param("page") Page page, @Param("param") ${entity}${cfg.pageParam} ${cfg.entityObjectName}${cfg.pageParam}); +#end + +} +#end diff --git a/springboot-225-velocity/src/test/resources/templates/mapper.xml.vm b/springboot-225-velocity/src/test/resources/templates/mapper.xml.vm new file mode 100644 index 0000000..b46f3ed --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/mapper.xml.vm @@ -0,0 +1,51 @@ + + + + +#if(${enableCache}) + + + +#end +#if(${baseResultMap}) + + +#foreach($field in ${table.fields}) +#if(${field.keyFlag})##生成主键排在第一位 + +#end +#end +#foreach($field in ${table.commonFields})##生成公共字段 + +#end +#foreach($field in ${table.fields}) +#if(!${field.keyFlag})##生成普通字段 + +#end +#end + + +#end +#if(${cfg.generatorStrategy} == 'ALL') + + +#foreach($field in ${table.commonFields}) + ${field.name}, +#end + ${table.fieldNames} + + + + + + +#end + diff --git a/springboot-225-velocity/src/test/resources/templates/pageParam.java.vm b/springboot-225-velocity/src/test/resources/templates/pageParam.java.vm new file mode 100644 index 0000000..7574529 --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/pageParam.java.vm @@ -0,0 +1,31 @@ +package ${cfg.pageParamPackage}; + +import io.swagger.annotations.ApiModel; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +#if(${cfg.pageListOrder}) +import ${cfg.superPageOrderParamClass}; +#else +import ${cfg.superPageParamClass}; +#end + +/** + *
+ * $!{table.comment} 分页参数对象
+ * 
+ * + * @author ${author} + * @date ${date} + */ +@Data +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = true) +@ApiModel(value = "$!{table.comment}分页参数") +#if(${cfg.pageListOrder}) +public class ${entity}${cfg.pageParam} extends BasePageOrderParam { +#else +public class ${entity}${cfg.pageParam} extends BasePageParam { +#end + private static final long serialVersionUID = 1L; +} diff --git a/springboot-225-velocity/src/test/resources/templates/queryVo.java.vm b/springboot-225-velocity/src/test/resources/templates/queryVo.java.vm new file mode 100644 index 0000000..027d7fa --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/queryVo.java.vm @@ -0,0 +1,46 @@ +package ${cfg.queryVoPackage}; + +#if(${swagger2}) +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +#end +#if(${entityLombokModel}) +import lombok.Data; +import lombok.experimental.Accessors; +#end +import java.io.Serializable; +import java.util.Date; + +/** + *
+ * $!{table.comment} 查询结果对象
+ * 
+ * + * @author ${author} + * @date ${date} + */ +#if(${entityLombokModel}) +@Data +@Accessors(chain = true) +#end +@ApiModel(value = "${entity}${cfg.queryVo}对象") +public class ${entity}${cfg.queryVo} implements Serializable { + private static final long serialVersionUID = 1L; +## ---------- BEGIN 字段循环遍历 ---------- +#foreach($field in ${table.fields}) + +#if(${field.keyFlag}) +#set($keyPropertyName=${field.propertyName}) +#end +#if("$!field.comment" != "") + #if(${swagger2}) + @ApiModelProperty("${field.comment}") + #else +/** + * ${field.comment} + */ + #end +#end + private ${field.propertyType} ${field.propertyName}; +#end +} \ No newline at end of file diff --git a/springboot-225-velocity/src/test/resources/templates/service.java.vm b/springboot-225-velocity/src/test/resources/templates/service.java.vm new file mode 100644 index 0000000..e78827f --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/service.java.vm @@ -0,0 +1,72 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +#if(${cfg.generatorPageParam}) +import ${cfg.pageParamClass}; +#end +import ${superServiceClassPackage}; +#if(${cfg.generatorQueryVo}) +import ${cfg.queryVoClass}; +#end +#if(${cfg.generatorStrategy} != 'SIMPLE') +import ${cfg.pagingClass}; +#end + +/** + * $!{table.comment} 服务类 + * + * @author ${author} + * @since ${date} + */ +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { +#if(${cfg.generatorStrategy} != 'SIMPLE') + + /** + * 保存 + * + * @param ${cfg.entityObjectName} + * @return + * @throws Exception + */ + boolean save${entity}(${entity} ${cfg.entityObjectName}) throws Exception; + + /** + * 修改 + * + * @param ${cfg.entityObjectName} + * @return + * @throws Exception + */ + boolean update${entity}(${entity} ${cfg.entityObjectName}) throws Exception; + + /** + * 删除 + * + * @param id + * @return + * @throws Exception + */ + boolean delete${entity}(Long id) throws Exception; + + #if(${cfg.generatorStrategy} != 'SINGLE') + /** + * 根据ID获取查询对象 + * + * @param id + * @return + * @throws Exception + */ + ${entity}${cfg.queryVo} get${entity}ById(Serializable id) throws Exception; + #end + + /** + * 获取分页对象 + * + * @param ${cfg.entityObjectName}QueryParam + * @return + * @throws Exception + */ + Paging<${entity}${cfg.queryVo}> get${entity}PageList(${entity}${cfg.pageParam} ${cfg.entityObjectName}${cfg.pageParam}) throws Exception; +#end + +} diff --git a/springboot-225-velocity/src/test/resources/templates/serviceImpl.java.vm b/springboot-225-velocity/src/test/resources/templates/serviceImpl.java.vm new file mode 100644 index 0000000..e77efe6 --- /dev/null +++ b/springboot-225-velocity/src/test/resources/templates/serviceImpl.java.vm @@ -0,0 +1,80 @@ +package ${package.ServiceImpl}; + +import ${package.Entity}.${entity}; +import ${package.Mapper}.${table.mapperName}; +import ${package.Service}.${table.serviceName}; +#if(${cfg.generatorPageParam}) +import ${cfg.pageParamClass}; +#end +#if(${cfg.generatorQueryVo}) +import ${cfg.queryVoClass}; +#end +#if(${cfg.generatorStrategy} == 'SINGLE') +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +#end +import ${superServiceImplClassPackage}; +#if(${cfg.generatorStrategy} != 'SIMPLE') +import ${cfg.pagingClass}; +import ${cfg.pageInfoClass}; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.transaction.annotation.Transactional; +#end +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * $!{table.comment} 服务实现类 + * + * @author ${author} + * @since ${date} + */ +@Slf4j +@Service +public class ${table.serviceImplName} extends BaseServiceImpl<${table.mapperName}, ${entity}> implements ${table.serviceName} { + + @Autowired + private ${table.mapperName} ${cfg.mapperObjectName}; +#if(${cfg.generatorStrategy} != 'SIMPLE') + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean save${entity}(${entity} ${cfg.entityObjectName}) throws Exception { + return super.save(${cfg.entityObjectName}); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean update${entity}(${entity} ${cfg.entityObjectName}) throws Exception { + return super.updateById(${cfg.entityObjectName}); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean delete${entity}(Long id) throws Exception { + return super.removeById(id); + } + + #if(${cfg.generatorStrategy} != 'SINGLE') + @Override + public ${entity}${cfg.queryVo} get${entity}ById(Serializable id) throws Exception { + return ${cfg.mapperObjectName}.get${entity}ById(id); + } + + #end + @Override + public Paging<${entity}${cfg.queryVo}> get${entity}PageList(${entity}${cfg.pageParam} ${cfg.entityObjectName}${cfg.pageParam}) throws Exception { + Page<${entity}${cfg.queryVo}> page = new PageInfo<>(${cfg.entityObjectName}${cfg.pageParam}, OrderItem.desc(getLambdaColumn(${entity}::getCreateTime))); + #if(${cfg.generatorStrategy} != 'SINGLE') + IPage<${entity}${cfg.queryVo}> iPage = ${cfg.mapperObjectName}.get${entity}PageList(page, ${cfg.entityObjectName}${cfg.pageParam}); + #else + LambdaQueryWrapper<${entity}> wrapper = new LambdaQueryWrapper<>(); + IPage<${entity}${cfg.queryVo}> iPage = ${cfg.mapperObjectName}.selectPage(page, wrapper); + #end + return new Paging<${entity}${cfg.queryVo}>(iPage); + } +#end + +} -- Gitee From 29ce129aa97adb40ef576d59ef081a61a61a676d Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 27 May 2020 19:36:01 +0800 Subject: [PATCH 40/49] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VelocityGeneratorController.java | 40 ++++++++++++------- .../src/main/resources/controller.java.vm | 19 ++++++--- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java index ff42816..045da90 100644 --- a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java @@ -10,9 +10,6 @@ import org.springframework.web.bind.annotation.RestController; import java.io.FileNotFoundException; import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; import java.util.Properties; @RestController @@ -33,31 +30,44 @@ public class VelocityGeneratorController { // 文件输出路径 //使用这个目录生成的代码,是在target目录下的 // String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; - p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\"); + p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); String rootPath = p.getProperty("parent_path"); - Template helloTpt = ve.getTemplate("HelloVelocity.vm"); - VelocityContext ctx = new VelocityContext(); - ctx.put("name", "velocity"); - ctx.put("date", (new Date()).toString()); - List temp = new ArrayList(); - temp.add("1"); - temp.add("2"); - ctx.put("list", temp); - merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); +// Template helloTpt = ve.getTemplate("HelloVelocity.vm"); +// VelocityContext ctx = new VelocityContext(); +// ctx.put("name", "velocity"); +// ctx.put("date", (new Date()).toString()); +// List temp = new ArrayList(); +// temp.add("1"); +// temp.add("2"); +// ctx.put("list", temp); +// merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); Template controllerTemplate = ve.getTemplate("controller.java.vm"); VelocityContext controllerContext = new VelocityContext(); - controllerContext.put("package","controller"); + controllerContext.put("package","com.example.springboot225velocity.controller"); controllerContext.put("restControllerStyle",true); controllerContext.put("entityObjectName","test"); + controllerContext.put("swaggerTags",true); + controllerContext.put("tableComment","Test控制器"); controllerContext.put("controllerName","TestController"); controllerContext.put("serviceName","TestService"); controllerContext.put("serviceObjectName","testServiceImpl"); merge(controllerTemplate,controllerContext,rootPath+"/controller/TestController.java"); - +// Template serviceTemplate = ve.getTemplate("service.java.vm"); +// VelocityContext serviceContext = new VelocityContext(); +// serviceContext.put("package","controller"); +// serviceContext.put("restControllerStyle",true); +// serviceContext.put("entityObjectName","test"); +// serviceContext.put("controllerName","TestController"); +// serviceContext.put("serviceName","TestService"); +// serviceContext.put("serviceObjectName","testServiceImpl"); +// merge(serviceTemplate,serviceContext,rootPath+"/controller/TestController.java"); + + // todo 在这个接口中,编译新生成的接口代码,编译后的代码就是在target目录下面的 + System.out.println("success..."); } diff --git a/springboot-225-velocity/src/main/resources/controller.java.vm b/springboot-225-velocity/src/main/resources/controller.java.vm index c0a16ac..30225be 100644 --- a/springboot-225-velocity/src/main/resources/controller.java.vm +++ b/springboot-225-velocity/src/main/resources/controller.java.vm @@ -1,6 +1,7 @@ package ${package}; -import lombok.*; +import io.swagger.annotations.Api; +import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; ##/** @@ -16,16 +17,22 @@ import org.springframework.web.bind.annotation.*; @Controller #end @RequestMapping("/${entityObjectName}") -#if(${swaggerTags}) -@Api(value = "$!{tableComment}API", tags = {"$!{tableComment}"}) -#else -@Api("$!{tableComment}API") -#end +###if(${swaggerTags}) +##@Api(value = "$!{tableComment}API", tags = {"$!{tableComment}"}) +###else +##@Api("$!{tableComment}API") +###end +@Api(description = "$!{tableComment}") public class ${controllerName} { ## @Autowired ## private ${serviceName} ${serviceObjectName}; + @GetMapping("/test") + public String test(){ + return "success"; + } + ## /** ## * 添加$!{table.comment} ## */ -- Gitee From 97638927f908cefb53eb1f674ac6ba0a21d99075 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 28 May 2020 09:30:03 +0800 Subject: [PATCH 41/49] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VelocityGeneratorController.java | 2 +- .../{main => test}/java/HelloVelocity.java | 2 +- .../java/VelocityGenerator.java | 24 +++++++++---------- 3 files changed, 13 insertions(+), 15 deletions(-) rename springboot-225-velocity/src/{main => test}/java/HelloVelocity.java (92%) rename springboot-225-velocity/src/{main => test}/java/VelocityGenerator.java (78%) diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java index 045da90..3a7fc5d 100644 --- a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java @@ -30,7 +30,7 @@ public class VelocityGeneratorController { // 文件输出路径 //使用这个目录生成的代码,是在target目录下的 // String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; - p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); + p.setProperty("parent_path","H:\\Projects\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); String rootPath = p.getProperty("parent_path"); // Template helloTpt = ve.getTemplate("HelloVelocity.vm"); diff --git a/springboot-225-velocity/src/main/java/HelloVelocity.java b/springboot-225-velocity/src/test/java/HelloVelocity.java similarity index 92% rename from springboot-225-velocity/src/main/java/HelloVelocity.java rename to springboot-225-velocity/src/test/java/HelloVelocity.java index 68a0a76..85eee73 100644 --- a/springboot-225-velocity/src/main/java/HelloVelocity.java +++ b/springboot-225-velocity/src/test/java/HelloVelocity.java @@ -16,7 +16,7 @@ public class HelloVelocity { // ve.init(); // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 Properties p = new Properties(); - p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); + p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\resources\\"); ve.init(p); Template t = ve.getTemplate("HelloVelocity.vm"); diff --git a/springboot-225-velocity/src/main/java/VelocityGenerator.java b/springboot-225-velocity/src/test/java/VelocityGenerator.java similarity index 78% rename from springboot-225-velocity/src/main/java/VelocityGenerator.java rename to springboot-225-velocity/src/test/java/VelocityGenerator.java index 6230ca4..b52ae86 100644 --- a/springboot-225-velocity/src/main/java/VelocityGenerator.java +++ b/springboot-225-velocity/src/test/java/VelocityGenerator.java @@ -6,9 +6,6 @@ import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import java.io.FileNotFoundException; import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; import java.util.Properties; public class VelocityGenerator { @@ -25,18 +22,19 @@ public class VelocityGenerator { // 文件输出路径 //使用这个目录生成的代码,是在target目录下的 // String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; - p.setProperty("parent_path","H:\\Projects\\01study_code\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\"); + // TODO: 2020/5/28 这里的路径到时候不能写死 + p.setProperty("parent_path","H:\\Projects\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); String rootPath = p.getProperty("parent_path"); - Template helloTpt = ve.getTemplate("HelloVelocity.vm"); - VelocityContext ctx = new VelocityContext(); - ctx.put("name", "velocity"); - ctx.put("date", (new Date()).toString()); - List temp = new ArrayList(); - temp.add("1"); - temp.add("2"); - ctx.put("list", temp); - merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); +// Template helloTpt = ve.getTemplate("HelloVelocity.vm"); +// VelocityContext ctx = new VelocityContext(); +// ctx.put("name", "velocity"); +// ctx.put("date", (new Date()).toString()); +// List temp = new ArrayList(); +// temp.add("1"); +// temp.add("2"); +// ctx.put("list", temp); +// merge(helloTpt,ctx,rootPath+"/controller/HelloVelocity.txt"); Template controllerTemplate = ve.getTemplate("controller.java.vm"); -- Gitee From 314a926b4589509f4dbf114457ef48b292b61293 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Thu, 28 May 2020 17:02:02 +0800 Subject: [PATCH 42/49] =?UTF-8?q?springboot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88httpclient?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-httpclient/.gitignore | 31 ++++ springboot-225-httpclient/pom.xml | 81 +++++++++ .../Springboot225HttpclientApplication.java | 13 ++ .../schedule/HttpScheduled.java | 27 +++ .../util/HttpClientUtil.java | 154 ++++++++++++++++++ .../src/main/resources/application.properties | 1 + ...ringboot225HttpclientApplicationTests.java | 13 ++ 7 files changed, 320 insertions(+) create mode 100644 springboot-225-httpclient/.gitignore create mode 100644 springboot-225-httpclient/pom.xml create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java create mode 100644 springboot-225-httpclient/src/main/resources/application.properties create mode 100644 springboot-225-httpclient/src/test/java/com/example/springboot225httpclient/Springboot225HttpclientApplicationTests.java diff --git a/springboot-225-httpclient/.gitignore b/springboot-225-httpclient/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/springboot-225-httpclient/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/springboot-225-httpclient/pom.xml b/springboot-225-httpclient/pom.xml new file mode 100644 index 0000000..2151652 --- /dev/null +++ b/springboot-225-httpclient/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-httpclient + 0.0.1-SNAPSHOT + springboot-225-httpclient + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + io.projectreactor + reactor-test + test + + + + + org.apache.httpcomponents + httpclient + 4.5.5 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java new file mode 100644 index 0000000..71cc488 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225httpclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225HttpclientApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot225HttpclientApplication.class, args); + } + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java new file mode 100644 index 0000000..1625009 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java @@ -0,0 +1,27 @@ +package com.example.springboot225httpclient.schedule; + +import com.example.springboot225httpclient.util.HttpClientUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/test") +public class HttpScheduled { + + /** + * 每过10秒 访问接口 + */ +// @Scheduled(fixedRate = 10) + @GetMapping("/test") + public void http(){ + String result = HttpClientUtil.doGet("http://192.168.0.120:9998/sup-medical/medical-institution/list"); + log.info(result); + + //保存到我们自己的数据库中 + + } + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java new file mode 100644 index 0000000..0433fe5 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java @@ -0,0 +1,154 @@ +package com.example.springboot225httpclient.util; + +import lombok.extern.slf4j.Slf4j; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Slf4j +public class HttpClientUtil { + public static String get(String url){ + RestTemplate template = new RestTemplate(); + ResponseEntity responseEntity = template.getForEntity(url, String.class); + return responseEntity.getBody(); + } + + public static String doGet(String url, Map param) { + + // 创建Httpclient对象 + CloseableHttpClient httpclient = HttpClients.createDefault(); + + String resultString = ""; + CloseableHttpResponse response = null; + try { + // 创建uri + URIBuilder builder = new URIBuilder(url); + if (param != null) { + for (String key : param.keySet()) { + builder.addParameter(key, param.get(key)); + } + } + URI uri = builder.build(); + + // 创建http GET请求 + HttpGet httpGet = new HttpGet(uri); + + // 执行请求 + response = httpclient.execute(httpGet); + // 判断返回状态是否为200 + if (response.getStatusLine().getStatusCode() == 200) { + resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return resultString; + } + + public static String doGet(String url) { + return doGet(url, null); + } + + public static String doPost(String url, Map param, HttpServletRequest request) { + // 创建Httpclient对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = null; + String resultString = ""; + try { + // 创建Http Post请求 + log.info("url地址:{}",url); + HttpPost httpPost = new HttpPost(url); + // 设置请求头 + if (request!=null){ + String authorization = request.getHeader("Authorization"); + httpPost.setHeader("Authorization",authorization); + } + // 创建参数列表 + if (param != null) { + List paramList = new ArrayList<>(); + for (String key : param.keySet()) { + paramList.add(new BasicNameValuePair(key, param.get(key))); + } + // 模拟表单 + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); + httpPost.setEntity(entity); + } + // 执行http请求 + response = httpClient.execute(httpPost); + resultString = EntityUtils.toString(response.getEntity(), "utf-8"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + response.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + return resultString; + } + + public static String doPost(String url) { + return doPost(url, null,null); + } + + public static String doPostJson(String url, String json) { + // 创建Httpclient对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse response = null; + String resultString = ""; + try { + // 创建Http Post请求 + HttpPost httpPost = new HttpPost(url); + // 创建请求内容 + StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); + httpPost.setEntity(entity); + // 执行http请求 + response = httpClient.execute(httpPost); + resultString = EntityUtils.toString(response.getEntity(), "utf-8"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + return resultString; + } + +} diff --git a/springboot-225-httpclient/src/main/resources/application.properties b/springboot-225-httpclient/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/springboot-225-httpclient/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/springboot-225-httpclient/src/test/java/com/example/springboot225httpclient/Springboot225HttpclientApplicationTests.java b/springboot-225-httpclient/src/test/java/com/example/springboot225httpclient/Springboot225HttpclientApplicationTests.java new file mode 100644 index 0000000..cbd2f45 --- /dev/null +++ b/springboot-225-httpclient/src/test/java/com/example/springboot225httpclient/Springboot225HttpclientApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225httpclient; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225HttpclientApplicationTests { + + @Test + void contextLoads() { + } + +} -- Gitee From 91bd1b0f172cb041ea71622d6d72e20045895b43 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Fri, 29 May 2020 14:23:27 +0800 Subject: [PATCH 43/49] =?UTF-8?q?springboot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88okhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-httpclient/pom.xml | 65 +++++ .../Springboot225HttpclientApplication.java | 4 + .../config/CommonProperties.java | 23 ++ .../MedicalInstitutionController.java | 20 ++ .../entity/MedicalInstitution.java | 252 ++++++++++++++++++ .../mapper/MedicalInstitutionMapper.java | 18 ++ .../schedule/HttpScheduled.java | 93 ++++++- .../service/IMedicalInstitutionService.java | 18 ++ .../impl/MedicalInstitutionServiceImpl.java | 20 ++ .../util/HttpClientUtil.java | 2 + .../util/OAuth2Utils.java | 27 ++ .../util/OkHttp3Util.java | 122 +++++++++ .../src/main/resources/application.properties | 1 - .../src/main/resources/application.yml | 17 ++ 14 files changed, 674 insertions(+), 8 deletions(-) create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/config/CommonProperties.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/controller/MedicalInstitutionController.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/entity/MedicalInstitution.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/mapper/MedicalInstitutionMapper.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/impl/MedicalInstitutionServiceImpl.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OAuth2Utils.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OkHttp3Util.java delete mode 100644 springboot-225-httpclient/src/main/resources/application.properties create mode 100644 springboot-225-httpclient/src/main/resources/application.yml diff --git a/springboot-225-httpclient/pom.xml b/springboot-225-httpclient/pom.xml index 2151652..ea6f84f 100644 --- a/springboot-225-httpclient/pom.xml +++ b/springboot-225-httpclient/pom.xml @@ -67,6 +67,71 @@ httpclient 4.5.5 + + + + com.alibaba + fastjson + 1.2.68 + + + + + com.google.guava + guava + 20.0 + + + + + com.squareup.okhttp3 + okhttp + 3.10.0 + + + + + mysql + mysql-connector-java + 8.0.19 + + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + io.swagger + swagger-annotations + 1.6.1 + + + + com.baomidou + mybatis-plus-generator + 3.2.0 + + + org.apache.velocity + velocity-engine-core + 2.1 + + + org.apache.velocity + velocity + 1.7 + test + + + + + com.baomidou + mybatis-plus-boot-starter + 3.2.0 + diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java index 71cc488..f523474 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java @@ -1,9 +1,13 @@ package com.example.springboot225httpclient; +import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication +@MapperScan("com.example.springboot225httpclient.mapper") +@EnableScheduling public class Springboot225HttpclientApplication { public static void main(String[] args) { diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/config/CommonProperties.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/config/CommonProperties.java new file mode 100644 index 0000000..9f8f73f --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/config/CommonProperties.java @@ -0,0 +1,23 @@ +package com.example.springboot225httpclient.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@Data +@ConfigurationProperties(prefix = "supervision.auth") +public class CommonProperties { + + private String authUrl; + + private String basicCode; + + private String username; + + private String password; + + private String grantType; + + private String scope; +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/controller/MedicalInstitutionController.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/controller/MedicalInstitutionController.java new file mode 100644 index 0000000..4f736e7 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/controller/MedicalInstitutionController.java @@ -0,0 +1,20 @@ +package com.example.springboot225httpclient.controller; + + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + *

+ * 医疗机构 前端控制器 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +@RestController +@RequestMapping("/medical-institution") +public class MedicalInstitutionController { + +} + diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/entity/MedicalInstitution.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/entity/MedicalInstitution.java new file mode 100644 index 0000000..e4523f8 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/entity/MedicalInstitution.java @@ -0,0 +1,252 @@ +package com.example.springboot225httpclient.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 医疗机构 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@ApiModel(value="MedicalInstitution对象", description="医疗机构") +public class MedicalInstitution implements Serializable { + + private static final long serialVersionUID=1L; + + @ApiModelProperty(value = "id") + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + @ApiModelProperty(value = "机构名称") + private String compName; + + @ApiModelProperty(value = "机构第二名称") + private String compSecName; + + @ApiModelProperty(value = "机构编号") + private String orgCode; + + @ApiModelProperty(value = "登记号") + private String registrationNo; + + @ApiModelProperty(value = "全国唯一识别码") + private String nationalIdentifyCode; + + @ApiModelProperty(value = "社会信用代码") + private String creditCode; + + @ApiModelProperty(value = "电话号码") + private String phoneNumber; + + @ApiModelProperty(value = "邮政编码") + private String zipCode; + + @ApiModelProperty(value = "机构地址") + private String address; + + @ApiModelProperty(value = "法人姓名") + private String principalName; + + @ApiModelProperty(value = "法人证件号") + private String principalIdCard; + + @ApiModelProperty(value = "负责人姓名") + private String managerName; + + @ApiModelProperty(value = "负责人证件号") + private String managerIdCard; + + @ApiModelProperty(value = "申请日期") + private LocalDateTime filingDate; + + @ApiModelProperty(value = "批准日期") + private LocalDateTime approvalDate; + + @ApiModelProperty(value = "批准文号") + private String approvalNumber; + + @ApiModelProperty(value = "有效期开始日期") + private LocalDateTime expiryStartDate; + + @ApiModelProperty(value = "有效期截止日期") + private LocalDateTime expiryEndDate; + + @ApiModelProperty(value = "登记发证机关Id") + private Integer certificateAuthorityId; + + @ApiModelProperty(value = "行政区划") + private String regionCode; + + @ApiModelProperty(value = "所有制形式") + private String ownershipFormCode; + + @ApiModelProperty(value = "隶属关系") + private String affiliation; + + @ApiModelProperty(value = "服务对象") + private String serviceObject; + + @ApiModelProperty(value = "服务方式") + private String serviceTypeCodes; + + @ApiModelProperty(value = "机构类别") + private Integer categoryCode; + + @ApiModelProperty(value = "机构级别") + private String levelCode; + + @ApiModelProperty(value = "机构等次") + private String gradeCode; + + @ApiModelProperty(value = "经营性质") + private String natureCode; + + @ApiModelProperty(value = "床位数") + private Integer bedCount; + + @ApiModelProperty(value = "牙椅数") + private Integer dentalChairCount; + + @ApiModelProperty(value = "开业日期") + private LocalDateTime openingDate; + + @ApiModelProperty(value = "注册资金") + private Integer regCapital; + + @ApiModelProperty(value = "下一校验日期") + private LocalDateTime nextCheckDate; + + @ApiModelProperty(value = "诊疗科目代码") + private String treatmentSubjectCode; + + @ApiModelProperty(value = "备注一") + private String remark; + + @ApiModelProperty(value = "备注二") + private String remarkSec; + + @ApiModelProperty(value = "当前状态") + private String status; + + @ApiModelProperty(value = "删除标示位") + private Boolean deleted; + + @ApiModelProperty(value = "记录创建时间") + private LocalDateTime createdAt; + + @ApiModelProperty(value = "监督创建人ID") + private Integer createdUserId; + + @ApiModelProperty(value = "最后更新时间") + private LocalDateTime updatedAt; + + @ApiModelProperty(value = "最后更新人ID") + private Integer updatedUserId; + + @ApiModelProperty(value = "诊疗科目名称") + private String treatmentSubjectName; + + + public static final String ID = "id"; + + public static final String COMP_NAME = "comp_name"; + + public static final String COMP_SEC_NAME = "comp_sec_name"; + + public static final String ORG_CODE = "org_code"; + + public static final String REGISTRATION_NO = "registration_no"; + + public static final String NATIONAL_IDENTIFY_CODE = "national_identify_code"; + + public static final String CREDIT_CODE = "credit_code"; + + public static final String PHONE_NUMBER = "phone_number"; + + public static final String ZIP_CODE = "zip_code"; + + public static final String ADDRESS = "address"; + + public static final String PRINCIPAL_NAME = "principal_name"; + + public static final String PRINCIPAL_ID_CARD = "principal_id_card"; + + public static final String MANAGER_NAME = "manager_name"; + + public static final String MANAGER_ID_CARD = "manager_id_card"; + + public static final String FILING_DATE = "filing_date"; + + public static final String APPROVAL_DATE = "approval_date"; + + public static final String APPROVAL_NUMBER = "approval_number"; + + public static final String EXPIRY_START_DATE = "expiry_start_date"; + + public static final String EXPIRY_END_DATE = "expiry_end_date"; + + public static final String CERTIFICATE_AUTHORITY_ID = "certificate_authority_id"; + + public static final String REGION_CODE = "region_code"; + + public static final String OWNERSHIP_FORM_CODE = "ownership_form_code"; + + public static final String AFFILIATION = "affiliation"; + + public static final String SERVICE_OBJECT = "service_object"; + + public static final String SERVICE_TYPE_CODES = "service_type_codes"; + + public static final String CATEGORY_CODE = "category_code"; + + public static final String LEVEL_CODE = "level_code"; + + public static final String GRADE_CODE = "grade_code"; + + public static final String NATURE_CODE = "nature_code"; + + public static final String BED_COUNT = "bed_count"; + + public static final String DENTAL_CHAIR_COUNT = "dental_chair_count"; + + public static final String OPENING_DATE = "opening_date"; + + public static final String REG_CAPITAL = "reg_capital"; + + public static final String NEXT_CHECK_DATE = "next_check_date"; + + public static final String TREATMENT_SUBJECT_CODE = "treatment_subject_code"; + + public static final String REMARK = "remark"; + + public static final String REMARK_SEC = "remark_sec"; + + public static final String STATUS = "status"; + + public static final String DELETED = "deleted"; + + public static final String CREATED_AT = "created_at"; + + public static final String CREATED_USER_ID = "created_user_id"; + + public static final String UPDATED_AT = "updated_at"; + + public static final String UPDATED_USER_ID = "updated_user_id"; + + public static final String TREATMENT_SUBJECT_NAME = "treatment_subject_name"; + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/mapper/MedicalInstitutionMapper.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/mapper/MedicalInstitutionMapper.java new file mode 100644 index 0000000..c46563e --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/mapper/MedicalInstitutionMapper.java @@ -0,0 +1,18 @@ +package com.example.springboot225httpclient.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.example.springboot225httpclient.entity.MedicalInstitution; +import org.apache.ibatis.annotations.Mapper; + +/** + *

+ * 医疗机构 Mapper 接口 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +@Mapper +public interface MedicalInstitutionMapper extends BaseMapper { + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java index 1625009..88e1d0c 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java @@ -1,27 +1,106 @@ package com.example.springboot225httpclient.schedule; -import com.example.springboot225httpclient.util.HttpClientUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225httpclient.config.CommonProperties; +import com.example.springboot225httpclient.entity.MedicalInstitution; +import com.example.springboot225httpclient.service.IMedicalInstitutionService; +import com.example.springboot225httpclient.util.OAuth2Utils; +import com.example.springboot225httpclient.util.OkHttp3Util; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + @Slf4j @RestController @RequestMapping("/test") public class HttpScheduled { + @Resource + private IMedicalInstitutionService iMedicalInstitutionService; + /** * 每过10秒 访问接口 */ -// @Scheduled(fixedRate = 10) - @GetMapping("/test") + @Scheduled(fixedRate = 5*1000) +// @PostMapping("/test") public void http(){ - String result = HttpClientUtil.doGet("http://192.168.0.120:9998/sup-medical/medical-institution/list"); - log.info(result); - + // 未授权,返回空字符串 +// String result = HttpClientUtil.doPost("http://192.168.0.120:9998/sup-medical/medical-institution/list"); +// log.info(result); //保存到我们自己的数据库中 + // 进行oauth2.0授权 + String requestUrl = "http://192.168.0.120:9998/sup-medical/"; + String domain = "medical-institution/list"; + String startDateTime = ""; + String endDateTime = ""; + // 获取最终返回结果 + JSONObject result = this.oauthGetData(requestUrl, domain, startDateTime, endDateTime); + log.info(result.toJSONString()); + if (result.getIntValue("code") == 0) { + log.info("成功获取接口返回值!"); + JSONArray jsonArray = result.getJSONObject("data").getJSONArray("records"); + List medicalInstitutionList = jsonArray.toJavaList(MedicalInstitution.class); + log.info("医疗机构列表信息:{}", medicalInstitutionList.size()); + log.info("list:{}",medicalInstitutionList); + + List medicalInstitutions = iMedicalInstitutionService.list(); + List idList = medicalInstitutions.stream().map(MedicalInstitution::getId).collect(Collectors.toList()); + + List insertData = Lists.newArrayList(); + for (MedicalInstitution medicalInstitution: + medicalInstitutionList) { + if (!idList.contains(medicalInstitution.getId())){ + insertData.add(medicalInstitution); + } + } + log.info("医疗机构新增数据:{}", insertData.size()); + iMedicalInstitutionService.saveBatch(insertData); + } else { + log.info(result.getString("msg")); + } + } + + @Resource + private CommonProperties commonProperties; + + /** + * OAuth2验证获取数据 + */ + private JSONObject oauthGetData(String requestUrl, String domain, String startDateTime, String endDateTime) { + + String authUrl = commonProperties.getAuthUrl(); + String basicInfo = commonProperties.getBasicCode(); + + HashMap params = Maps.newHashMap(); + params.put("username", commonProperties.getUsername()); + params.put("password", commonProperties.getPassword()); + params.put("grant_type", commonProperties.getGrantType()); + params.put("scope", commonProperties.getScope()); + + // 获取OAuth Token + JSONObject tokenInfo = OAuth2Utils.authToken(authUrl, params, basicInfo); + + // 拼接数据请求地址 +// String dataUrl = String.format(requestUrl, domain, startDateTime, endDateTime); + String dataUrl = requestUrl + domain + startDateTime + endDateTime; + + Map authInfo = Maps.newHashMap(); + authInfo.put("Authorization", "Bearer " + tokenInfo.getString("access_token")); + + String s = OkHttp3Util.sendByGetUrlWithHeader(dataUrl, authInfo); + + return JSONObject.parseObject(s); } } diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java new file mode 100644 index 0000000..5f8e568 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java @@ -0,0 +1,18 @@ +package com.example.springboot225httpclient.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.example.springboot225httpclient.entity.MedicalInstitution; +import org.springframework.stereotype.Service; + +/** + *

+ * 医疗机构 服务类 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +@Service +public interface IMedicalInstitutionService extends IService { + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/impl/MedicalInstitutionServiceImpl.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/impl/MedicalInstitutionServiceImpl.java new file mode 100644 index 0000000..a33bc42 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/impl/MedicalInstitutionServiceImpl.java @@ -0,0 +1,20 @@ +package com.example.springboot225httpclient.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.example.springboot225httpclient.entity.MedicalInstitution; +import com.example.springboot225httpclient.mapper.MedicalInstitutionMapper; +import com.example.springboot225httpclient.service.IMedicalInstitutionService; +import org.springframework.stereotype.Service; + +/** + *

+ * 医疗机构 服务实现类 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +@Service +public class MedicalInstitutionServiceImpl extends ServiceImpl implements IMedicalInstitutionService { + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java index 0433fe5..3e67798 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java @@ -50,6 +50,8 @@ public class HttpClientUtil { // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); +// httpGet.setHeader("Access Token","9edb2c5c-7df5-455b-9c11-b9b92e7b41de"); + httpGet.setHeader("Authorization","Bearer 9edb2c5c-7df5-455b-9c11-b9b92e7b41de"); // 执行请求 response = httpclient.execute(httpGet); diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OAuth2Utils.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OAuth2Utils.java new file mode 100644 index 0000000..21460b2 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OAuth2Utils.java @@ -0,0 +1,27 @@ +package com.example.springboot225httpclient.util; + + +import com.alibaba.fastjson.JSONObject; +import com.google.common.collect.Maps; + +import java.util.HashMap; +import java.util.Map; + +/** + * OAuth2工具 + */ +public final class OAuth2Utils { + + /** + * 获取验证信息 + */ + public static JSONObject authToken(String url, Map params, String authInfo) { + + HashMap headers = Maps.newHashMap(); + headers.put("Authorization", "Basic " + authInfo); + + String response = OkHttp3Util.sendByPostMapWithHeader(url, params, headers); + + return JSONObject.parseObject(response); + } +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OkHttp3Util.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OkHttp3Util.java new file mode 100644 index 0000000..a0b3f88 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/OkHttp3Util.java @@ -0,0 +1,122 @@ +package com.example.springboot225httpclient.util; + +import okhttp3.*; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class OkHttp3Util { + + //MEDIA_TYPE <==> Content-Type + private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); + //MEDIA_TYPE_TEXT post请求不是application/x-www-form-urlencoded的,全部直接返回,不作处理,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。只能使用最原始的方式,读取输入流来获取。 + private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); + + /** + * Get请求 + */ + public static String sendByGetUrl(String url) { + + return sendByGetUrlWithHeader(url, null); + } + + public static String sendByGetUrlWithHeader(String url, Map headers) { + String result; + OkHttpClient client = new OkHttpClient(); + + Request.Builder builder = new Request.Builder() + .url(url); + + if (headers != null) { + builder.headers(Headers.of(headers)); + } + + Request request = builder.build(); + + Response response = null; + try { + response = client.newCall(request).execute(); + assert response.body() != null; + result = response.body().string(); + return result; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Post JSON + */ + public static String sendByPostJson(String url, String json) { + OkHttpClient client = new OkHttpClient(); + RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json); + Request request = new Request.Builder() + .url(url) + .post(body) + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + assert response.body() != null; + return response.body().string(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + + + /** + * post方式请求 + */ + public static String sendByPostMap(String url, Map params) { + + return sendByPostMapWithHeader(url, params, null); + } + + /** + * post方式请求 可配置headers + */ + public static String sendByPostMapWithHeader(String url, Map params, Map headers) { + String result; + OkHttpClient client = new OkHttpClient(); + StringBuilder content = new StringBuilder(); + Set> entrys = params.entrySet(); + Iterator> iterator = params.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + content.append(entry.getKey()).append("=").append(entry.getValue()); + if (iterator.hasNext()) { + content.append("&"); + } + } + + RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString()); + + Request.Builder builder = new Request.Builder() + .url(url); + + if (headers != null) { + builder.headers(Headers.of(headers)); + } + + Request request = builder + .post(requestBody).build(); + Response response = null; + try { + response = client.newCall(request).execute(); + assert response.body() != null; + result = response.body().string(); + System.out.println("result = " + result); + return result; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + +} \ No newline at end of file diff --git a/springboot-225-httpclient/src/main/resources/application.properties b/springboot-225-httpclient/src/main/resources/application.properties deleted file mode 100644 index 8b13789..0000000 --- a/springboot-225-httpclient/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/springboot-225-httpclient/src/main/resources/application.yml b/springboot-225-httpclient/src/main/resources/application.yml new file mode 100644 index 0000000..0d6e9ac --- /dev/null +++ b/springboot-225-httpclient/src/main/resources/application.yml @@ -0,0 +1,17 @@ +logging: + level: + com.example.springboot225httpclient.mapper: debug +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + password: root + url: jdbc:mysql://192.168.0.183:3306/hc_supervision_1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true + username: root +supervision: + auth: + authUrl: http://192.168.0.120:9998/auth/oauth/token + basicCode: dGVzdDp0ZXN0 + grantType: password + password: 123456 + scope: server + username: test -- Gitee From 4e502b0c03682c4a985fb150072ca35c835b7180 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Fri, 29 May 2020 15:42:11 +0800 Subject: [PATCH 44/49] =?UTF-8?q?springboot2.2.5=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88okhttp=EF=BC=8C=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../schedule/HttpScheduled.java | 20 ++++++++----------- .../src/main/resources/application.yml | 3 +++ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java index 88e1d0c..dc66451 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java @@ -11,8 +11,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.HashMap; @@ -21,24 +20,23 @@ import java.util.Map; import java.util.stream.Collectors; @Slf4j -@RestController -@RequestMapping("/test") +//@RestController +//@RequestMapping("/test") +@Component public class HttpScheduled { @Resource private IMedicalInstitutionService iMedicalInstitutionService; + @Resource + private CommonProperties commonProperties; + /** * 每过10秒 访问接口 */ @Scheduled(fixedRate = 5*1000) // @PostMapping("/test") public void http(){ - // 未授权,返回空字符串 -// String result = HttpClientUtil.doPost("http://192.168.0.120:9998/sup-medical/medical-institution/list"); -// log.info(result); - //保存到我们自己的数据库中 - // 进行oauth2.0授权 String requestUrl = "http://192.168.0.120:9998/sup-medical/"; String domain = "medical-institution/list"; @@ -65,15 +63,13 @@ public class HttpScheduled { } } log.info("医疗机构新增数据:{}", insertData.size()); + //保存到我们自己的数据库中 iMedicalInstitutionService.saveBatch(insertData); } else { log.info(result.getString("msg")); } } - @Resource - private CommonProperties commonProperties; - /** * OAuth2验证获取数据 */ diff --git a/springboot-225-httpclient/src/main/resources/application.yml b/springboot-225-httpclient/src/main/resources/application.yml index 0d6e9ac..6f6cd1a 100644 --- a/springboot-225-httpclient/src/main/resources/application.yml +++ b/springboot-225-httpclient/src/main/resources/application.yml @@ -15,3 +15,6 @@ supervision: password: 123456 scope: server username: test + +server: + port: 8081 -- Gitee From 1bea02e2a39a21868b750b56de265a53eb7a16ec Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 2 Jun 2020 11:18:19 +0800 Subject: [PATCH 45/49] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=94=9F=E6=88=90?= =?UTF-8?q?=E7=9A=84java=E6=96=87=E4=BB=B6=E7=9A=84=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/VelocityGeneratorController.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java index 3a7fc5d..a5e7e5e 100644 --- a/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java @@ -10,7 +10,6 @@ import org.springframework.web.bind.annotation.RestController; import java.io.FileNotFoundException; import java.io.PrintWriter; -import java.util.Properties; @RestController @RequestMapping("/velocityGenerator") @@ -23,15 +22,12 @@ public class VelocityGeneratorController { ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 - Properties p = new Properties(); +// Properties p = new Properties(); // p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); // ve.init(p); // 文件输出路径 - //使用这个目录生成的代码,是在target目录下的 -// String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; - p.setProperty("parent_path","H:\\Projects\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); - String rootPath = p.getProperty("parent_path"); + String rootPath = System.getProperty("user.dir") + "\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"; // Template helloTpt = ve.getTemplate("HelloVelocity.vm"); // VelocityContext ctx = new VelocityContext(); -- Gitee From c5b7b83b5d1ab0048f5cfd92895e83446872d93c Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 2 Jun 2020 11:26:46 +0800 Subject: [PATCH 46/49] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=94=9F=E6=88=90?= =?UTF-8?q?=E7=9A=84java=E6=96=87=E4=BB=B6=E7=9A=84=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/test/java/VelocityGenerator.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/springboot-225-velocity/src/test/java/VelocityGenerator.java b/springboot-225-velocity/src/test/java/VelocityGenerator.java index b52ae86..bc0cc40 100644 --- a/springboot-225-velocity/src/test/java/VelocityGenerator.java +++ b/springboot-225-velocity/src/test/java/VelocityGenerator.java @@ -6,7 +6,6 @@ import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import java.io.FileNotFoundException; import java.io.PrintWriter; -import java.util.Properties; public class VelocityGenerator { public static void main(String[] args) { @@ -15,16 +14,12 @@ public class VelocityGenerator { ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); // 本地运行的时候,应该用这个,不要用上面的代码,否则找不到指定路径; 除非放到resources根目录下,这样编译完成之后,模板能被找到 - Properties p = new Properties(); +// Properties p = new Properties(); // p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "H:\\Projects\\01study_code\\springboot-demo\\src\\main\\resources\\templates\\"); // ve.init(p); // 文件输出路径 - //使用这个目录生成的代码,是在target目录下的 -// String rootPath = VelocityGenerator.class.getClassLoader().getResource("").getFile() + "/com"; - // TODO: 2020/5/28 这里的路径到时候不能写死 - p.setProperty("parent_path","H:\\Projects\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"); - String rootPath = p.getProperty("parent_path"); + String rootPath = System.getProperty("user.dir") + "\\springboot-225-velocity\\src\\main\\java\\com\\example\\springboot225velocity\\"; // Template helloTpt = ve.getTemplate("HelloVelocity.vm"); // VelocityContext ctx = new VelocityContext(); -- Gitee From e74b7376f3d27f815e090ef8145c1862a0f84943 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 2 Jun 2020 13:19:46 +0800 Subject: [PATCH 47/49] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/IMedicalInstitutionService.java | 2 -- springboot-225-httpclient/src/main/resources/application.yml | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java index 5f8e568..7246b3d 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java @@ -2,7 +2,6 @@ package com.example.springboot225httpclient.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.springboot225httpclient.entity.MedicalInstitution; -import org.springframework.stereotype.Service; /** *

@@ -12,7 +11,6 @@ import org.springframework.stereotype.Service; * @author Bazinga * @since 2020-05-29 */ -@Service public interface IMedicalInstitutionService extends IService { } diff --git a/springboot-225-httpclient/src/main/resources/application.yml b/springboot-225-httpclient/src/main/resources/application.yml index 6f6cd1a..857fe2c 100644 --- a/springboot-225-httpclient/src/main/resources/application.yml +++ b/springboot-225-httpclient/src/main/resources/application.yml @@ -1,6 +1,9 @@ logging: level: com.example.springboot225httpclient.mapper: debug + org: + springframework: + ws: DEBUG spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver -- Gitee From a20b18f3e853f73da5b73bd9ecc5250adf1c36fe Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Tue, 2 Jun 2020 13:20:27 +0800 Subject: [PATCH 48/49] =?UTF-8?q?=E6=B7=BB=E5=8A=A0webservice=E7=9A=84?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E5=92=8C=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot-225-httpclient/pom.xml | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/springboot-225-httpclient/pom.xml b/springboot-225-httpclient/pom.xml index ea6f84f..53af905 100644 --- a/springboot-225-httpclient/pom.xml +++ b/springboot-225-httpclient/pom.xml @@ -27,6 +27,16 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot @@ -134,12 +144,53 @@ + + + + java11 + + [11,) + + + + + org.glassfish.jaxb + jaxb-runtime + + + + + + org.springframework.boot spring-boot-maven-plugin + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + com.example.consumingwebservice.wsdl + + + http://localhost:8080/ws/countries.wsdl + + + + + -- Gitee From c6adf68a9e23708a92109a5682aca9eeab9c9615 Mon Sep 17 00:00:00 2001 From: yanghaojie <13486032976@163.com> Date: Wed, 3 Jun 2020 16:29:11 +0800 Subject: [PATCH 49/49] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Springboot225HttpclientApplication.java | 16 +++ .../schedule/CountryClient.java | 30 +++++ .../schedule/CountryConfiguration.java | 29 +++++ .../schedule/WebServiceScheduled.java | 103 ++++++++++++++++++ 4 files changed, 178 insertions(+) create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryClient.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryConfiguration.java create mode 100644 springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/WebServiceScheduled.java diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java index f523474..01b1547 100644 --- a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java @@ -1,8 +1,12 @@ package com.example.springboot225httpclient; +import com.example.consumingwebservice.wsdl.GetCountryResponse; +import com.example.springboot225httpclient.schedule.CountryClient; import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @@ -14,4 +18,16 @@ public class Springboot225HttpclientApplication { SpringApplication.run(Springboot225HttpclientApplication.class, args); } + @Bean + CommandLineRunner lookup(CountryClient quoteClient) { + return args -> { + String country = "Spain"; + + if (args.length > 0) { + country = args[0]; + } + GetCountryResponse response = quoteClient.getCountry(country); + System.err.println(response.getCountry().getCurrency()); + }; + } } diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryClient.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryClient.java new file mode 100644 index 0000000..d2146d0 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryClient.java @@ -0,0 +1,30 @@ + +package com.example.springboot225httpclient.schedule; + +import com.example.consumingwebservice.wsdl.GetCountryRequest; +import com.example.consumingwebservice.wsdl.GetCountryResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ws.client.core.support.WebServiceGatewaySupport; +import org.springframework.ws.soap.client.core.SoapActionCallback; + +public class CountryClient extends WebServiceGatewaySupport { + + private static final Logger log = LoggerFactory.getLogger(CountryClient.class); + + public GetCountryResponse getCountry(String country) { + + GetCountryRequest request = new GetCountryRequest(); + request.setName(country); + + log.info("Requesting location for " + country); + + GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate() + .marshalSendAndReceive("http://localhost:8080/ws/countries", request, + new SoapActionCallback( + "http://spring.io/guides/gs-producing-web-service/GetCountryRequest")); + + return response; + } + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryConfiguration.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryConfiguration.java new file mode 100644 index 0000000..29c5713 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryConfiguration.java @@ -0,0 +1,29 @@ + +package com.example.springboot225httpclient.schedule; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +@Configuration +public class CountryConfiguration { + + @Bean + public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + // this package must match the package in the specified in + // pom.xml + marshaller.setContextPath("com.example.consumingwebservice.wsdl"); + return marshaller; + } + + @Bean + public CountryClient countryClient(Jaxb2Marshaller marshaller) { + CountryClient client = new CountryClient(); + client.setDefaultUri("http://localhost:8080/ws"); + client.setMarshaller(marshaller); + client.setUnmarshaller(marshaller); + return client; + } + +} diff --git a/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/WebServiceScheduled.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/WebServiceScheduled.java new file mode 100644 index 0000000..14d45e9 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/WebServiceScheduled.java @@ -0,0 +1,103 @@ +package com.example.springboot225httpclient.schedule; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.example.springboot225httpclient.config.CommonProperties; +import com.example.springboot225httpclient.entity.MedicalInstitution; +import com.example.springboot225httpclient.service.IMedicalInstitutionService; +import com.example.springboot225httpclient.util.OAuth2Utils; +import com.example.springboot225httpclient.util.OkHttp3Util; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@RestController +@RequestMapping("/test") +@Component +public class WebServiceScheduled { + + @Resource + private IMedicalInstitutionService iMedicalInstitutionService; + + @Resource + private CommonProperties commonProperties; + + /** + * 每过10秒 访问接口 + */ +// @Scheduled(fixedRate = 5*1000) + @PostMapping("/test") + public void http(){ + // 进行oauth2.0授权 + String requestUrl = "http://192.168.0.120:9998/sup-medical/"; + String domain = "medical-institution/list"; + String startDateTime = ""; + String endDateTime = ""; + // 获取最终返回结果 + JSONObject result = this.oauthGetData(requestUrl, domain, startDateTime, endDateTime); + log.info(result.toJSONString()); + if (result.getIntValue("code") == 0) { + log.info("成功获取接口返回值!"); + JSONArray jsonArray = result.getJSONObject("data").getJSONArray("records"); + List medicalInstitutionList = jsonArray.toJavaList(MedicalInstitution.class); + log.info("医疗机构列表信息:{}", medicalInstitutionList.size()); + log.info("list:{}",medicalInstitutionList); + + List medicalInstitutions = iMedicalInstitutionService.list(); + List idList = medicalInstitutions.stream().map(MedicalInstitution::getId).collect(Collectors.toList()); + + List insertData = Lists.newArrayList(); + for (MedicalInstitution medicalInstitution: + medicalInstitutionList) { + if (!idList.contains(medicalInstitution.getId())){ + insertData.add(medicalInstitution); + } + } + log.info("医疗机构新增数据:{}", insertData.size()); + //保存到我们自己的数据库中 + iMedicalInstitutionService.saveBatch(insertData); + } else { + log.info(result.getString("msg")); + } + } + + /** + * OAuth2验证获取数据 + */ + private JSONObject oauthGetData(String requestUrl, String domain, String startDateTime, String endDateTime) { + + String authUrl = commonProperties.getAuthUrl(); + String basicInfo = commonProperties.getBasicCode(); + + HashMap params = Maps.newHashMap(); + params.put("username", commonProperties.getUsername()); + params.put("password", commonProperties.getPassword()); + params.put("grant_type", commonProperties.getGrantType()); + params.put("scope", commonProperties.getScope()); + + // 获取OAuth Token + JSONObject tokenInfo = OAuth2Utils.authToken(authUrl, params, basicInfo); + + // 拼接数据请求地址 +// String dataUrl = String.format(requestUrl, domain, startDateTime, endDateTime); + String dataUrl = requestUrl + domain + startDateTime + endDateTime; + + Map authInfo = Maps.newHashMap(); + authInfo.put("Authorization", "Bearer " + tokenInfo.getString("access_token")); + + String s = OkHttp3Util.sendByGetUrlWithHeader(dataUrl, authInfo); + + return JSONObject.parseObject(s); + } +} -- Gitee