diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5f8578f9d53206c5ce7d93a0e25013068988334d --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,16 @@ +# Default ignored files +/workspace.xml +/compiler.xml +/encodings.xml +/misc.xml +/modules.xml +/SpringBootLearning.iml +/vcs.xml +/inspectionProfiles/ +/sonarlint/ +/libraries/ +# Datasource local storage ignored files +/dataSources.local.xml +/dataSources/ +dataSources.xml +sqldialects.xml \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000000000000000000000000000000000000..e96534fb27b68192f27f985d3879e173ec77adb8 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 02aa14c66c01e3b45f1c2645248cc911c3c8287b..490e20a105bb37baa60cc48ee2fffd6f0d29c719 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,14 @@ ->转载请标明出处: -> 原文首发于: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 - -
-

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

-

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

-
- - - +# 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非官方教程 | 终章:文章汇总 - 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/ @@ -104,17 +84,6 @@ ## 未完结 * 待续。。。 -
-

- -
- 扫码关注有惊喜 -

-

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

-
- diff --git a/demo/.gitignore b/demo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /dev/null +++ b/demo/.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/demo/mvnw b/demo/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 new file mode 100644 index 0000000000000000000000000000000000000000..306307542c7a51c09bc7177d19367aa1a959d4ee --- /dev/null +++ b/demo/pom.xml @@ -0,0 +1,84 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.example + demo + 0.0.1-SNAPSHOT + 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} + + + + + junit + junit + 4.12 + + + + org.springframework + spring-test + 5.1.9.RELEASE + + + + javax.servlet + javax.servlet-api + 3.1.0 + + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + 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 0000000000000000000000000000000000000000..094d95b93ffb2708ff7037793fd189908b1ea6fb --- /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 0000000000000000000000000000000000000000..7a6d94167acb8cbfc88ac7f3578662e9e353ffcf --- /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 0000000000000000000000000000000000000000..cf76d3df60b6d9534bff7c57adf9d83a12263f34 --- /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 0000000000000000000000000000000000000000..b464e5f5812a1f49c6cd8b301b8686f02eb1ab82 --- /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 0000000000000000000000000000000000000000..d6cbdf56b84d89646f89273265ba920e73117332 --- /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/com/example/demo/test/Test01.java b/demo/src/main/java/com/example/demo/test/Test01.java new file mode 100644 index 0000000000000000000000000000000000000000..7142997da7f372367b271a5cedfeb3715dc4f886 --- /dev/null +++ b/demo/src/main/java/com/example/demo/test/Test01.java @@ -0,0 +1,19 @@ +package com.example.demo.test; + +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/com/example/demo/test/Test02.java b/demo/src/main/java/com/example/demo/test/Test02.java new file mode 100644 index 0000000000000000000000000000000000000000..9d89a9106df19e91688d95962c18d5840f4975c9 --- /dev/null +++ b/demo/src/main/java/com/example/demo/test/Test02.java @@ -0,0 +1,27 @@ +package com.example.demo.test; + +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/com/example/demo/test/TestThread.java b/demo/src/main/java/com/example/demo/test/TestThread.java new file mode 100644 index 0000000000000000000000000000000000000000..07c52906eb8441e90ac2585d7a50ce5a0f59306c --- /dev/null +++ b/demo/src/main/java/com/example/demo/test/TestThread.java @@ -0,0 +1,17 @@ +package com.example.demo.test; + +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"); + } +} diff --git a/demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java b/demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0100f1dfd0acbf654e814241460f4c3703bf53d7 --- /dev/null +++ b/demo/src/main/java/com/example/demo/xuliankeji/JasyptTest.java @@ -0,0 +1,36 @@ +package com.example.demo.xuliankeji; + +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); + } +} diff --git a/demo/src/main/resources/application.properties b/demo/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /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 0000000000000000000000000000000000000000..eaa99696e2ab439159031a591b363c39f4c240c1 --- /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() { + } + +} diff --git a/springboot-001-demo/.gitignore b/springboot-001-demo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7bd258a358f0dcd37ad107f1a9f9af2654a111a9 --- /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 0000000000000000000000000000000000000000..a16b5431b4c3cab50323a3f558003fd0abd87dad --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 0000000000000000000000000000000000000000..2e74946751eb41f86570e4e7d3c9aa8a3f0613bf --- /dev/null +++ b/springboot-001-demo/pom.xml @@ -0,0 +1,70 @@ + + + 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 + 2.4.0.RELEASE + + + + + + + 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 0000000000000000000000000000000000000000..e8b40270bca45b62eee379a56bc265db3e961a65 --- /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 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /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 0000000000000000000000000000000000000000..fe61e8f2cefbc8019452e1069b9a86b301dc2599 --- /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 0000000000000000000000000000000000000000..1494db1369146f626d36ee28a38102a9cd388028 --- /dev/null +++ b/springboot-001-demo/src/test/java/com/example/springboot001demo/xuliankeji/PigxAdminApplicationTest.java @@ -0,0 +1,32 @@ +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; + +/** + * application.yml文件中数据库密码,使用jasypt加密 + */ +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")); + + } +} diff --git a/springboot-225-aliiot/.gitignore b/springboot-225-aliiot/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /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 0000000000000000000000000000000000000000..fd8eb0a07219c415d123d063b6494ae5a8fc2ecf --- /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 0000000000000000000000000000000000000000..70c16cdc3ad2c39cd507913fc7e3d852ca1ca6e5 --- /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 0000000000000000000000000000000000000000..649d6758bcc76796538da86b1c69e4b1d64d5aa1 --- /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 0000000000000000000000000000000000000000..7409862e90cb26ed42f0143a6cb96ec2526bcf95 --- /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 0000000000000000000000000000000000000000..d0ee1236b47bf6e326e738fb688e04e2e4d4c588 --- /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 0000000000000000000000000000000000000000..973088497bf2d4f3dd2de8b7e62c0982f57f86fc --- /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 0000000000000000000000000000000000000000..fd99b2e5fbc47acf3a280ef1cf786294763e8b4f --- /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 0000000000000000000000000000000000000000..cb082d36b20962822bf7ecefb43c8c7e2580763d --- /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 0000000000000000000000000000000000000000..240e0ff31a93b9901c606968a56bf05bc0dee362 --- /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 0000000000000000000000000000000000000000..55e35266bace28d03ccd02ee169dd92e2d58c22c --- /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 0000000000000000000000000000000000000000..2d0e806313dff13eb1fcf9ebb38d6f87f06eaeeb --- /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 0000000000000000000000000000000000000000..04761ef0a5c27dabae11017302136913542cc00a --- /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 0000000000000000000000000000000000000000..5240a85fb945559b93fcb133eb825bc17570d31f --- /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 0000000000000000000000000000000000000000..13ef9ff6ad6ae24e8e60f218b5bf15ca56e82b2a --- /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 0000000000000000000000000000000000000000..1cd09ce160b5a498f5a44309cce209c7a13e1f7b --- /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 0000000000000000000000000000000000000000..1129299dcb6f88645455fe4c5e57363d6519921e --- /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 0000000000000000000000000000000000000000..160cfe9d61ab8a2ac6bfbaa69a259fbc8ba31095 --- /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 0000000000000000000000000000000000000000..fc01d22db0a5b93bcd7a3933c8ecac64a06067c8 --- /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 0000000000000000000000000000000000000000..8c21f75400465f071478ec9a7bd892a9805c8442 --- /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 0000000000000000000000000000000000000000..b03a20947d64b0c76663df3d9f40622c208360c5 --- /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 0000000000000000000000000000000000000000..91250e93235f9b0b3df61ce5f7f987a214efada5 --- /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 0000000000000000000000000000000000000000..017ebb91f30dcd9b3aa6faf27c2627fd97a6b688 --- /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 0000000000000000000000000000000000000000..32511010d6f5658030cdb8761c3b55d3e08c4d5b --- /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 0000000000000000000000000000000000000000..c2081536582f3d1a553cc04ed9b3977f7ec7d433 --- /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 0000000000000000000000000000000000000000..1624c78b61dbaa3b09e41d7981bfc87441405a3e --- /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 0000000000000000000000000000000000000000..a04c28fb324684e1700cf8fde1e48396f05bfe49 --- /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 0000000000000000000000000000000000000000..188ddcabd4821aba016662cdd426d14d40385f2c --- /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 0000000000000000000000000000000000000000..33eb1d94424a3ed95eed0e4744c3bc88e3a7a3e0 --- /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 0000000000000000000000000000000000000000..2c2c8ddf67017519bf4a64dd72a12470b0fbf121 --- /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 0000000000000000000000000000000000000000..db17324523037fdd8ac429cea0e787d52b260c7f --- /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 0000000000000000000000000000000000000000..2f62d04b8bba3030eadf1b96e75f0839546877ac --- /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 0000000000000000000000000000000000000000..35fa71ef5ca7c13abb9c11393fbb1ecd8fe4335b --- /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 0000000000000000000000000000000000000000..5787d43d78c67a3a5851b70670501db3607ca02e --- /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 0000000000000000000000000000000000000000..8a3883c4322c89aa40867d75e11b19e012f67736 --- /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 0000000000000000000000000000000000000000..bc87734962364a7038122b1b64130882ec6ea83a --- /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 0000000000000000000000000000000000000000..30c6fe525fd50b804287904f3ab5b3ceca50c4aa --- /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 0000000000000000000000000000000000000000..bc672c066bda82c80ac280578dddbb9c351a0765 --- /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 diff --git a/springboot-225-elasticsearch/.gitignore b/springboot-225-elasticsearch/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0054eae2e08c2009405bd95b292f12eb7ba26cf7 --- /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/README.md b/springboot-225-elasticsearch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..abeb30a82b7675fb92413dffbd1689aa41c7319a --- /dev/null +++ b/springboot-225-elasticsearch/README.md @@ -0,0 +1,19 @@ +# 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 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 0000000000000000000000000000000000000000..03ab5b0979d2f4bbc1b9afda82733fa1ebcc1186 --- /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 0000000000000000000000000000000000000000..5fff9f16071bd36f6ac3160bc9be010552d55e47 --- /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 0000000000000000000000000000000000000000..5af86bff970c89559537202e5601dce5e32407e4 --- /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 0000000000000000000000000000000000000000..aa87baa87e416e80f44e0abb233a5c4718676179 --- /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 0000000000000000000000000000000000000000..a900d64aabf6183a7eb5aec846aa5ce37a3e567d --- /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 0000000000000000000000000000000000000000..d0aeb8c616e4113a50a74b3269926ee40c42f0bd --- /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 0000000000000000000000000000000000000000..d452153e8f1a6231c25eb6c2b0a8f56709ea9fe7 --- /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 0000000000000000000000000000000000000000..eefadb8bca525116d62fa4ced8b4c56119035f2c --- /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 0000000000000000000000000000000000000000..5f3d6da129336d45143d5c638b162ca9bf78d653 --- /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() { + } + +} diff --git a/springboot-225-httpclient/.gitignore b/springboot-225-httpclient/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /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 0000000000000000000000000000000000000000..53af905926f3644dcf8296069eaff2a00ef5dd21 --- /dev/null +++ b/springboot-225-httpclient/pom.xml @@ -0,0 +1,197 @@ + + + 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-starter-web-services + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + 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 + + + + + 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 + + + + + + + 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 + + + + + + + + + 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 0000000000000000000000000000000000000000..01b15474546974c2f78c2f7f7385b3f7c6d44fd6 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/Springboot225HttpclientApplication.java @@ -0,0 +1,33 @@ +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 +@MapperScan("com.example.springboot225httpclient.mapper") +@EnableScheduling +public class Springboot225HttpclientApplication { + + public static void main(String[] args) { + 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/config/CommonProperties.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/config/CommonProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..9f8f73f54352066ea4535914d6937250acfce8a5 --- /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 0000000000000000000000000000000000000000..4f736e765bfcb84258041fe04fc16f40406c8bda --- /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 0000000000000000000000000000000000000000..e4523f8daec6e33d424559404592c87f83bd8c5d --- /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 0000000000000000000000000000000000000000..c46563ef434a6c085a78b81e72a87759da13aaf0 --- /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/CountryClient.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/CountryClient.java new file mode 100644 index 0000000000000000000000000000000000000000..d2146d07d2ab0ac6b7a571c3efe0cb945bc5c32a --- /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 0000000000000000000000000000000000000000..29c57133816be2687127f69e557a0c5873b4700f --- /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/HttpScheduled.java b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java new file mode 100644 index 0000000000000000000000000000000000000000..dc664516619e917a1fee0560d5826084fdeff283 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/schedule/HttpScheduled.java @@ -0,0 +1,102 @@ +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.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +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 HttpScheduled { + + @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); + } + +} 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 0000000000000000000000000000000000000000..14d45e911963341142ee28c215e776a15c81ccb1 --- /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); + } +} 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 0000000000000000000000000000000000000000..7246b3d93cacddaa1f4cc5810d37647f568db03f --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/service/IMedicalInstitutionService.java @@ -0,0 +1,16 @@ +package com.example.springboot225httpclient.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.example.springboot225httpclient.entity.MedicalInstitution; + +/** + *

+ * 医疗机构 服务类 + *

+ * + * @author Bazinga + * @since 2020-05-29 + */ +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 0000000000000000000000000000000000000000..a33bc4270b1f33a49301d1fbfa52f0951135b2cf --- /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 new file mode 100644 index 0000000000000000000000000000000000000000..3e6779866d33e7d5cc224edc4c147d62cedeb101 --- /dev/null +++ b/springboot-225-httpclient/src/main/java/com/example/springboot225httpclient/util/HttpClientUtil.java @@ -0,0 +1,156 @@ +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); +// httpGet.setHeader("Access Token","9edb2c5c-7df5-455b-9c11-b9b92e7b41de"); + httpGet.setHeader("Authorization","Bearer 9edb2c5c-7df5-455b-9c11-b9b92e7b41de"); + + // 执行请求 + 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/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 0000000000000000000000000000000000000000..21460b2a07ecd39985488081541bff5fc733130a --- /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 0000000000000000000000000000000000000000..a0b3f8822dfbefb8d56ec1b3d08772d2182a62a6 --- /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.yml b/springboot-225-httpclient/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..857fe2c4af55daa07774e7cfbda12dad9888a8a2 --- /dev/null +++ b/springboot-225-httpclient/src/main/resources/application.yml @@ -0,0 +1,23 @@ +logging: + level: + com.example.springboot225httpclient.mapper: debug + org: + springframework: + ws: 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 + +server: + port: 8081 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 0000000000000000000000000000000000000000..cbd2f450564442c9d370bc397d2496ad5f0e547a --- /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() { + } + +} diff --git a/springboot-225-jpa/.gitignore b/springboot-225-jpa/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0054eae2e08c2009405bd95b292f12eb7ba26cf7 --- /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 0000000000000000000000000000000000000000..3c16566d0cf0c5d7d15509bd49176d4fac1f9934 --- /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 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 0000000000000000000000000000000000000000..6f21f1315a5d3a6c7c9faebe8fd60a3461c1e6f2 --- /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 0000000000000000000000000000000000000000..b6c473586eb250daf616c079692bde6ace27db62 --- /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 0000000000000000000000000000000000000000..9dc9538f38c26120d10f43de682fe80b5370df87 --- /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 0000000000000000000000000000000000000000..0b36b3168a3cc684b2047f41348624e04cae4afa --- /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 0000000000000000000000000000000000000000..66896169179546da89f8406e0912c70ea61d0aea --- /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 0000000000000000000000000000000000000000..0a8508edde7ac7c322f3198088e9837bfc50ed6f --- /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 0000000000000000000000000000000000000000..b8f521f5be071bb3a65204eedbd6694237ac82c3 --- /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() { + } + +} diff --git a/springboot-225-kafka/.gitignore b/springboot-225-kafka/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /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 0000000000000000000000000000000000000000..1dc2ebe01762c0dcbf63ac4919c257e29b7c4986 --- /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 0000000000000000000000000000000000000000..979768e0c06be0364a16996da514ef986f9c3914 --- /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 0000000000000000000000000000000000000000..a2a9b4d8b1aa3f800a86b8e494b10bc2fe86f54a --- /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 0000000000000000000000000000000000000000..71b085de6765e20d71c52920418627cd1ab2e5c6 --- /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 0000000000000000000000000000000000000000..475fa589bd084ab589b54ac446dd6587cb478cb1 --- /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 0000000000000000000000000000000000000000..4e3efb854ace913aad0c64a2e1085e8da142ac66 --- /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() { + } + +} diff --git a/springboot-225-logback/.gitignore b/springboot-225-logback/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..28f9535b265eae087bbff4e027822ebc87cc33cd --- /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 0000000000000000000000000000000000000000..fe638f0e118420ad1906f8287d0b58f0693b385c --- /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 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 0000000000000000000000000000000000000000..47ded9e4a65b92a58e9e5243cc760c8dd0d926dc --- /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 0000000000000000000000000000000000000000..7e3165e9618bd6f8c1e7b9c40b50ee9d08d0087b --- /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 0000000000000000000000000000000000000000..d6349236957edbc10456147db4848c427d89b22f --- /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.controller.*.*(..))") + 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 0000000000000000000000000000000000000000..c30cf0b1f7296586999936fa8fccf12d3600f5f4 --- /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 0000000000000000000000000000000000000000..d61c65fc8633aee86f2be92863656f49a7ef1c57 --- /dev/null +++ b/springboot-225-logback/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.application.name=springboot-logback + +logging.config=classpath:logback-spring.xml +# 使用logback-spring.xml以后,就不需要下面的配置了 +#logging.file.name=D:/logs/${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 0000000000000000000000000000000000000000..75289941e5711913b696e43565f0e78d9f250a09 --- /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 0000000000000000000000000000000000000000..3abaf004c37b17e3a8cb6f2623a93709f07213b4 --- /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() { + } + +} diff --git a/springboot-225-mongodb/.gitignore b/springboot-225-mongodb/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3a568a50285aee9b3852fc541414c6db16090ab2 --- /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 0000000000000000000000000000000000000000..eb0a7afa15e1e0dd9e6cbdd20e321e30126a48ec --- /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 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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 0000000000000000000000000000000000000000..1ae9bac16557b46270fe5abd50c89854ada04ea9 --- /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 0000000000000000000000000000000000000000..49c2e88b6702354451b18b26cf4c9ca629787483 --- /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 0000000000000000000000000000000000000000..359157889b163b22869569aa4907355cd8afa85e --- /dev/null +++ b/springboot-225-mongodb/src/main/java/com/example/springboot225mongodb/Book.java @@ -0,0 +1,28 @@ +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; + //价格 + 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 0000000000000000000000000000000000000000..308076c2efb56be4ade5dde9968ed0a39ee9a268 --- /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 0000000000000000000000000000000000000000..8830331becef36635eb53345548adc8207a17546 --- /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 0000000000000000000000000000000000000000..c705c92d49e412f753a363656f7375918ab1832e --- /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/Customer.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Customer.java new file mode 100644 index 0000000000000000000000000000000000000000..669db243b45ea8fd32ab8a0969bbf3143486855d --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Customer.java @@ -0,0 +1,28 @@ +package com.example.springboot225mongodb; + +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 diff --git a/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..d0977b0ee5ef5c1bda008a19e58f6383907527ec --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/CustomerRepository.java @@ -0,0 +1,12 @@ +package com.example.springboot225mongodb; + +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/Springboot225MongodbApplicationTests.java b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..39647afe8032c76df0b3f902cc3c723c8fdd7ed1 --- /dev/null +++ b/springboot-225-mongodb/src/test/java/com/example/springboot225mongodb/Springboot225MongodbApplicationTests.java @@ -0,0 +1,42 @@ +package com.example.springboot225mongodb; + +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-rabbitmq-consumer/.gitignore b/springboot-225-rabbitmq-consumer/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3a568a50285aee9b3852fc541414c6db16090ab2 --- /dev/null +++ b/springboot-225-rabbitmq-consumer/.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-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java b/springboot-225-rabbitmq-consumer/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000000000000000000000000000000000..d6d1381397d7c2a76eb73590f5da7e0cde818815 --- /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 Binary files /dev/null and b/springboot-225-rabbitmq-consumer/.mvn/wrapper/maven-wrapper.jar differ 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 0000000000000000000000000000000000000000..642d572ce90e5085986bdd9c9204b9404f028084 --- /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/README.md b/springboot-225-rabbitmq-consumer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5eb74928b1d6725187a78471f284f6d59205fef6 --- /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-consumer/mvnw b/springboot-225-rabbitmq-consumer/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..3c8a5537314954d53ec2fb774b34fe5d5a5f253a --- /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-consumer/mvnw.cmd b/springboot-225-rabbitmq-consumer/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /dev/null +++ b/springboot-225-rabbitmq-consumer/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-consumer/pom.xml b/springboot-225-rabbitmq-consumer/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..e25f0b79e15feed81ae421ed2e414132ae1b3444 --- /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/Springboot225RabbitmqConsumerApplication.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/Springboot225RabbitmqConsumerApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..dc294fe711523862bf4cf6d8334936a9fb2b3394 --- /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 0000000000000000000000000000000000000000..6de49905cf90d1c5861fb2e020f037757f99f2f1 --- /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/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 0000000000000000000000000000000000000000..a5b172d6a7b69d22c0c27dc161517f2aabb0533a --- /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 0000000000000000000000000000000000000000..a8c11f228e12865ca6782b291e304c69feb47828 --- /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/receiver/DirectReceiver.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/DirectReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..bbc7ce06ae9bdf870785de8eb5fd46edf27c9bfb --- /dev/null +++ b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/DirectReceiver.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 = "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/receiver/FanoutReceiverA.java b/springboot-225-rabbitmq-consumer/src/main/java/com/example/springboot225rabbitmqconsumer/receiver/FanoutReceiverA.java new file mode 100644 index 0000000000000000000000000000000000000000..ff8d822dcf70405c95faa0c39b978325cff2ea4e --- /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 0000000000000000000000000000000000000000..1151663eb9f2d104db30dacfb2c566f8a9c62563 --- /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 0000000000000000000000000000000000000000..e3f788f5971e87a51053adcaae74a926e93d21b5 --- /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 0000000000000000000000000000000000000000..9ef3e775268ada0f8e56aef1e96934bbdb8d890f --- /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 0000000000000000000000000000000000000000..9181887483462c3af63d7e8e747148e03488e76f --- /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-consumer/src/main/resources/application.yml b/springboot-225-rabbitmq-consumer/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..582c2191eeca4f72a7aa49e56e08a2f627657920 --- /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 0000000000000000000000000000000000000000..51415152c63a360f9853cdd50b9131f27609a79d --- /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-provider/.gitignore b/springboot-225-rabbitmq-provider/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0054eae2e08c2009405bd95b292f12eb7ba26cf7 --- /dev/null +++ b/springboot-225-rabbitmq-provider/.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-rabbitmq-provider/README.md b/springboot-225-rabbitmq-provider/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5eb74928b1d6725187a78471f284f6d59205fef6 --- /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-rabbitmq-provider/mvnw b/springboot-225-rabbitmq-provider/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..a16b5431b4c3cab50323a3f558003fd0abd87dad --- /dev/null +++ b/springboot-225-rabbitmq-provider/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-rabbitmq-provider/mvnw.cmd b/springboot-225-rabbitmq-provider/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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-provider/pom.xml b/springboot-225-rabbitmq-provider/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..9319a006fde471c70a5613de0d1e0d3e25fc9b12 --- /dev/null +++ b/springboot-225-rabbitmq-provider/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-provider + 0.0.1-SNAPSHOT + springboot-225-rabbitmq-provider + 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-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..8523e867aa40bf535d1a1c2bb6862eaa6f8fe61b --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplication.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmq; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot225RabbitmqProviderApplication { + + public static void main(String[] 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 0000000000000000000000000000000000000000..fede519ec3fa5d88e214af98aa0cd1c15ec9aee1 --- /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/config/FanoutRabbitConfig.java b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/config/FanoutRabbitConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..3ec3b9764183dadf053b1d93b7bd6ebb3091909c --- /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 0000000000000000000000000000000000000000..c90d0fa91f98716e54cf3a37dc93a318321b02e2 --- /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 0000000000000000000000000000000000000000..1a496e80f434439fceffaa803a12c4586eda6503 --- /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 new file mode 100644 index 0000000000000000000000000000000000000000..e3100b758d2c66508d142fcd9e4db9c1c3a9da55 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/java/com/example/springboot225rabbitmq/controller/SendMessageController.java @@ -0,0 +1,86 @@ +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"; + } + + @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 new file mode 100644 index 0000000000000000000000000000000000000000..c63454981d7b0486407db39f134390fe5ceea334 --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/main/resources/application.yml @@ -0,0 +1,20 @@ +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: / + #消息确认配置项 + #确认消息已发送到交换机(Exchange) + publisher-confirms: on +# publisher-confirm-type: simple + #确认消息已发送到队列(Queue) + publisher-returns: on \ No newline at end of file diff --git a/springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java b/springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..1ce3402bcda77cc2c0bad528dfd9f3379df6622b --- /dev/null +++ b/springboot-225-rabbitmq-provider/src/test/java/com/example/springboot225rabbitmq/Springboot225RabbitmqProviderApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.springboot225rabbitmq; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot225RabbitmqProviderApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-225-redis/.gitignore b/springboot-225-redis/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0054eae2e08c2009405bd95b292f12eb7ba26cf7 --- /dev/null +++ b/springboot-225-redis/.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-redis/README.md b/springboot-225-redis/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9781f90460fe43ffa84a0d3b87eaadbff1bc1801 --- /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/) + diff --git a/springboot-225-redis/mvnw b/springboot-225-redis/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..a16b5431b4c3cab50323a3f558003fd0abd87dad --- /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 0000000000000000000000000000000000000000..c8d43372c986d97911cdc21bd87e0cbe3d83bdda --- /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-225-redis/pom.xml b/springboot-225-redis/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..2e305683e6970e9f672565763f5e6a243ddee030 --- /dev/null +++ b/springboot-225-redis/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.5.RELEASE + + + com.example + springboot-225-redis + 0.0.1-SNAPSHOT + springboot-225-redis + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.apache.commons + commons-pool2 + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + 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 new file mode 100644 index 0000000000000000000000000000000000000000..2b6bb52c85968bd2fc390b4abf9a1e242969d29c --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/SpringbootRedisApplication.java @@ -0,0 +1,16 @@ +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(exclude= DataSourceAutoConfiguration.class) +@EnableCaching +public class SpringbootRedisApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootRedisApplication.class, args); + } + +} 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 new file mode 100644 index 0000000000000000000000000000000000000000..1d409fef59b9066a059b7bc956c54ca1c6364a0c --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/config/RedisConfig.java @@ -0,0 +1,30 @@ +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; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.io.Serializable; + +@Configuration +// @AutoConfigureAfter 在加载配置的类之后再加载当前类; 这里就是在加载RedisAutoConfiguration之后,再加载RedisConfig +@AutoConfigureAfter(RedisAutoConfiguration.class) +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 new file mode 100644 index 0000000000000000000000000000000000000000..52bbd6c0da4b7f09c670d1d8a25b20f46bc1aa87 --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/controller/UserController.java @@ -0,0 +1,84 @@ +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; +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; +import java.util.HashMap; + +@RestController +@RequestMapping("/user") +@Slf4j +public class UserController { + + public static Logger logger = LogManager.getLogger(UserController.class); + + // String(字符串) + @Resource + private StringRedisTemplate stringRedisTemplate; + // Hash(散列),List(列表),Set(集合),Sorted Set(有序不重复集合) + @Resource + private RedisTemplate redisCacheTemplate; + + @Resource + private UserService userService; + + @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; + } + + @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)); + 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-225-redis/src/main/java/com/example/springbootredis/entity/User.java b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..d465ec7303f89b03311c0fb84c1c299071b9b272 --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/entity/User.java @@ -0,0 +1,20 @@ +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; + + private String name; + + private Integer age; + +} diff --git a/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java new file mode 100644 index 0000000000000000000000000000000000000000..d32f79984a7ebadc43ea9a526dfe1f064be0b0dd --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserService.java @@ -0,0 +1,12 @@ +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-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5c30d5286c096bd1bf0b4cd6fd445bbcfd006a4b --- /dev/null +++ b/springboot-225-redis/src/main/java/com/example/springbootredis/service/UserServiceImpl.java @@ -0,0 +1,48 @@ +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)); + userMap.put(4, new User(4, "李现", 30)); + } + + + @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-225-redis/src/main/resources/application.properties b/springboot-225-redis/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..5981b681ae34377feab802dc2e29241ffe40ed36 --- /dev/null +++ b/springboot-225-redis/src/main/resources/application.properties @@ -0,0 +1,18 @@ +# redis +# 连接设置 +spring.cache.type=redis +spring.redis.host=localhost +spring.redis.port=6379 +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 new file mode 100644 index 0000000000000000000000000000000000000000..62a9c2b0e5967fa682401a31b284560d8e77401a --- /dev/null +++ b/springboot-225-redis/src/test/java/com/example/springbootredis/SpringbootRedisApplicationTests.java @@ -0,0 +1,8 @@ +package com.example.springbootredis; + +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class SpringbootRedisApplicationTests { + +} diff --git a/springboot-225-velocity/.gitignore b/springboot-225-velocity/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a2a3040aa86debfd8826d9c2b5c816314c17d9fe --- /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 0000000000000000000000000000000000000000..ca523633ed0abbc49b40f1a8624b75612108e77a --- /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/com/example/springboot225velocity/Springboot225VelocityApplication.java b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/Springboot225VelocityApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..c3710725bf85be1a59a1dbf8d699d7c8f65ec13a --- /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 0000000000000000000000000000000000000000..5b60ae47a374a3ff5bbd1081143cb501fb3d85d2 --- /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 0000000000000000000000000000000000000000..99083ddd8e2d7335c2b6f008acf4a988ef0f3f80 --- /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 0000000000000000000000000000000000000000..a5e7e5e3ea7a6fd0fb5b21aa3b7c92be5b24904e --- /dev/null +++ b/springboot-225-velocity/src/main/java/com/example/springboot225velocity/controller/VelocityGeneratorController.java @@ -0,0 +1,83 @@ +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; + +@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); + + // 文件输出路径 + 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(); +// 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","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..."); + } + + 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 0000000000000000000000000000000000000000..ea8cd68562869f557be2836f5936e0381121bb45 --- /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 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /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 0000000000000000000000000000000000000000..30225be53d30b2ca1c0b1200cf7106dbc4914bef --- /dev/null +++ b/springboot-225-velocity/src/main/resources/controller.java.vm @@ -0,0 +1,120 @@ +package ${package}; + +import io.swagger.annotations.Api; +import lombok.extern.slf4j.Slf4j; +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 +@Api(description = "$!{tableComment}") +public class ${controllerName} { + +## @Autowired +## private ${serviceName} ${serviceObjectName}; + + @GetMapping("/test") + public String test(){ + return "success"; + } + +## /** +## * 添加$!{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/HelloVelocity.java b/springboot-225-velocity/src/test/java/HelloVelocity.java new file mode 100644 index 0000000000000000000000000000000000000000..85eee73c324369965a8228d0350ba2f0d695e394 --- /dev/null +++ b/springboot-225-velocity/src/test/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\\01StudyProject\\SpringBootLearning\\springboot-225-velocity\\src\\main\\resources\\"); + 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/test/java/VelocityGenerator.java b/springboot-225-velocity/src/test/java/VelocityGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..bc0cc4055d3bc1e4b2c20f6310d579c3e4ba3540 --- /dev/null +++ b/springboot-225-velocity/src/test/java/VelocityGenerator.java @@ -0,0 +1,60 @@ +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; + +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); + + // 文件输出路径 + 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(); +// 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/test/java/com/example/springboot225velocity/CodeGenerator.java b/springboot-225-velocity/src/test/java/com/example/springboot225velocity/CodeGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..c1b1cadae35f66c484ee82b717c0cd439dddf22e --- /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 0000000000000000000000000000000000000000..1ae4d736c522ea94df426bef984279d2a8dd52e0 --- /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 0000000000000000000000000000000000000000..ef2818c99f92737b5bf88968abb701a93472e254 --- /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 0000000000000000000000000000000000000000..e51556b5d5f82b9087923936ca4ad7c67eb904aa --- /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 0000000000000000000000000000000000000000..c069517dff85165113016e2d3b2c52a10ba02524 --- /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 0000000000000000000000000000000000000000..b6f16a21c98cafabf8fbcd176723232d3cdb5cf0 --- /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 0000000000000000000000000000000000000000..5e3af4cf1f38124acea7b24356abce8a1e3c3812 --- /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 0000000000000000000000000000000000000000..6e47a206e5ced09c3aab452cefff174a34b57d6b --- /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 0000000000000000000000000000000000000000..f290044d3fa0ee7597e784d7d54c37b2f07d4e31 --- /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 0000000000000000000000000000000000000000..249ed7e949d43766d742a25d2126ef5dc4c973dc --- /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 0000000000000000000000000000000000000000..a45bdedd52fd4bfd4b38806aa932fb8f302f80bd --- /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 0000000000000000000000000000000000000000..70636af1ea65120a0e4a9c6846f0d7322660893f --- /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 0000000000000000000000000000000000000000..08514f4d8ab0fd4e09e385603c5d27c7c25f2c75 --- /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 0000000000000000000000000000000000000000..c9c160c016db09110df884f491e0edf208149d3b --- /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 0000000000000000000000000000000000000000..8260775e523e5e69a30877a645d33db98e6c5a98 --- /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 0000000000000000000000000000000000000000..1553312909f6ba26bb48c3b962057743a219b05e --- /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 0000000000000000000000000000000000000000..3f0e37d68845bd8f83a9c018bce8d1939cc7f56e --- /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 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 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 0000000000000000000000000000000000000000..3131cbef5d9f10d346fcf26986170cb6ea2a534f --- /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 0000000000000000000000000000000000000000..b46f3ed075309172bc75c25e1dff9fdfcf6bca0d --- /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 0000000000000000000000000000000000000000..75745291540556a62c3d02d337d427a37476b1bf --- /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 0000000000000000000000000000000000000000..027d7fa97455ef58345749dccd2ca472c61b4ee9 --- /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 0000000000000000000000000000000000000000..e78827fffff057ac9949302cf4e3131b84e94816 --- /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 0000000000000000000000000000000000000000..e77efe6bf3764d793773b342ebb9aaebb243a146 --- /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 + +} diff --git a/springboot-mybatis-tx/pom.xml b/springboot-mybatis-tx/pom.xml index d7ff404ea97f5ce84da34731b1c6ca921130d4d0..2a695fb40862955237418f20530505b1932f4f77 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 diff --git a/springboot-redis-message/pom.xml b/springboot-redis-message/pom.xml index 9c707d19743b51d744b77b006bf92c65ef413017..3793add51ba89f98c8a0e2113278e6abba33eceb 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 eea096b611ac0ed449fe417fbc0ff6fbd55e9bf2..4bc80adda1cbe694a818f4e62124c74b8689896a 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 8b148703c0a7622dbd48ce67381b0457dd461def..bbca0c9fd2c63af16fbb6f4a4dcc58f07f4d1598 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");