diff --git a/README.md b/README.md index 27989b8..c18f471 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +由于github下载太慢,所以大家可以在码云下载~ https://gitee.com/lixiyan4633/SpringBoot # SpringBoot ## 这是一个B站的SpringBoot的从入门程序集锦 @@ -15,5 +16,7 @@     - ElasticSearch 全文检索     - SpringCould 分布式管理 +     - RabbitMQ中间件 + - Cache缓存 ## 我是法律小白,我自己照着写的文档,如果侵权的话,请给我发邮箱告知一下lixiyan4633@163.com diff --git a/SpringBoot2/amqp/.gitignore b/SpringBoot2/amqp/.gitignore new file mode 100644 index 0000000..82eca33 --- /dev/null +++ b/SpringBoot2/amqp/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.jar b/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..9cc84ea Binary files /dev/null and b/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.jar differ diff --git a/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.properties b/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..b573bb5 --- /dev/null +++ b/SpringBoot2/amqp/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/SpringBoot2/amqp/mvnw b/SpringBoot2/amqp/mvnw new file mode 100644 index 0000000..5bf251c --- /dev/null +++ b/SpringBoot2/amqp/mvnw @@ -0,0 +1,225 @@ +#!/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 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 Migwn, 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)`" + # TODO classpath? +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 + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +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 + +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/SpringBoot2/amqp/mvnw.cmd b/SpringBoot2/amqp/mvnw.cmd new file mode 100644 index 0000000..019bd74 --- /dev/null +++ b/SpringBoot2/amqp/mvnw.cmd @@ -0,0 +1,143 @@ +@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 http://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 Maven2 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 key stroke 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 enable echoing my 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 + +%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/SpringBoot2/amqp/pom.xml b/SpringBoot2/amqp/pom.xml new file mode 100644 index 0000000..a1c251c --- /dev/null +++ b/SpringBoot2/amqp/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.wdjr + amqp + 0.0.1-SNAPSHOT + jar + + amqp + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.13.RELEASE + + + + + UTF-8 + UTF-8 + 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.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/AmqpApplication.java b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/AmqpApplication.java new file mode 100644 index 0000000..a50f6d7 --- /dev/null +++ b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/AmqpApplication.java @@ -0,0 +1,14 @@ +package com.wdjr.amqp; + +import org.springframework.amqp.rabbit.annotation.EnableRabbit; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@EnableRabbit //开启基于注解的rabbitmq +@SpringBootApplication +public class AmqpApplication { + + public static void main(String[] args) { + SpringApplication.run(AmqpApplication.class, args); + } +} diff --git a/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/bean/Book.java b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/bean/Book.java new file mode 100644 index 0000000..b17b205 --- /dev/null +++ b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/bean/Book.java @@ -0,0 +1,39 @@ +package com.wdjr.amqp.bean; + +public class Book { + private String bookName; + private String author; + + public Book(){ + + } + + public Book(String bookName, String author) { + this.bookName = bookName; + this.author = author; + } + + public String getBookName() { + return bookName; + } + + public void setBookName(String bookName) { + this.bookName = bookName; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Book{" + + "bookName='" + bookName + '\'' + + ", author='" + author + '\'' + + '}'; + } +} diff --git a/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/config/MyAMQPConfig.java b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/config/MyAMQPConfig.java new file mode 100644 index 0000000..7e43d11 --- /dev/null +++ b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/config/MyAMQPConfig.java @@ -0,0 +1,16 @@ +package com.wdjr.amqp.config; + + +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.amqp.support.converter.MessageConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MyAMQPConfig { + + @Bean + public MessageConverter messageConverter(){ + return new Jackson2JsonMessageConverter(); + } +} diff --git a/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/service/BookService.java b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/service/BookService.java new file mode 100644 index 0000000..d237ce1 --- /dev/null +++ b/SpringBoot2/amqp/src/main/java/com/wdjr/amqp/service/BookService.java @@ -0,0 +1,20 @@ +package com.wdjr.amqp.service; + +import com.wdjr.amqp.bean.Book; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Service; + +@Service +public class BookService { + @RabbitListener(queues = "wdjr.news") + public void receive(Book book){ + System.out.println(book); + } + + @RabbitListener(queues = "wdjr") + public void receive02(Message message){ + System.out.println(message.getBody()); + System.out.println(message.getMessageProperties()); + } +} diff --git a/SpringBoot2/amqp/src/main/resources/application.properties b/SpringBoot2/amqp/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/SpringBoot2/amqp/src/main/resources/application.yml b/SpringBoot2/amqp/src/main/resources/application.yml new file mode 100644 index 0000000..85292ad --- /dev/null +++ b/SpringBoot2/amqp/src/main/resources/application.yml @@ -0,0 +1,8 @@ +spring: + rabbitmq: + host: 192.168.179.131 + port: 5672 + username: guest + password: guest +server: + port: 9000 \ No newline at end of file diff --git a/SpringBoot2/amqp/src/test/java/com/wdjr/amqp/AmqpApplicationTests.java b/SpringBoot2/amqp/src/test/java/com/wdjr/amqp/AmqpApplicationTests.java new file mode 100644 index 0000000..d000ed2 --- /dev/null +++ b/SpringBoot2/amqp/src/test/java/com/wdjr/amqp/AmqpApplicationTests.java @@ -0,0 +1,72 @@ +package com.wdjr.amqp; + +import com.wdjr.amqp.bean.Book; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.amqp.core.AmqpAdmin; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class AmqpApplicationTests { + + @Autowired + RabbitTemplate rabbitTemplate; + + @Autowired + AmqpAdmin amqpAdmin; + + @Test + public void contextLoads() { + //Message需要自己构建一个;定义消息体内容和消息头 + // rabbitTemplate.send(exchange, routingKey, message); + //Object 默认当成消息体,只需要传入要发送的对象,自动化序列发送给rabbitmq; + Map map = new HashMap<>(); + map.put("msg", "这是第一个信息"); + map.put("data", Arrays.asList("helloWorld",123,true)); + //对象被默认序列以后发送出去 + rabbitTemplate.convertAndSend("exchange.direct","wdjr.news",new Book("百年孤独", "季羡林")); + //rabbitTemplate.convertAndSend("exchange.direct","wdjr.news",map); + } +// 接受数据,如何将数据转成json + @Test + public void reciverAndConvert(){ + + Object o = rabbitTemplate.receiveAndConvert("wdjr.news"); + //Book o = (Book) rabbitTemplate.receiveAndConvert("wdjr.news"); + System.out.println(o.getClass()); + System.out.println(o); + + } + + @Test + public void createExchange(){ + amqpAdmin.declareExchange(new DirectExchange("amqpadmin.direct")); + System.out.println("Create Finish"); + } + + @Test + public void createQueue(){ + amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true)); + System.out.println("Create Queue Finish"); + } + @Test + public void createBind(){ + amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE , "amqpadmin.direct", "amqp.haha", null)); + } + @Test + public void deleteExchange(){ + amqpAdmin.deleteExchange("amqpadmin.direct"); + System.out.println("delete Finish"); + } +} diff --git a/SpringBoot2/springboot-01-cache/.gitignore b/SpringBoot2/springboot-01-cache/.gitignore new file mode 100644 index 0000000..82eca33 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.jar b/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..9cc84ea Binary files /dev/null and b/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.jar differ diff --git a/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.properties b/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..b573bb5 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/SpringBoot2/springboot-01-cache/mvnw b/SpringBoot2/springboot-01-cache/mvnw new file mode 100644 index 0000000..5bf251c --- /dev/null +++ b/SpringBoot2/springboot-01-cache/mvnw @@ -0,0 +1,225 @@ +#!/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 +# +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 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 Migwn, 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)`" + # TODO classpath? +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 + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +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 + +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/SpringBoot2/springboot-01-cache/mvnw.cmd b/SpringBoot2/springboot-01-cache/mvnw.cmd new file mode 100644 index 0000000..019bd74 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/mvnw.cmd @@ -0,0 +1,143 @@ +@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 http://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 Maven2 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 key stroke 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 enable echoing my 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 + +%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/SpringBoot2/springboot-01-cache/pom.xml b/SpringBoot2/springboot-01-cache/pom.xml new file mode 100644 index 0000000..189125b --- /dev/null +++ b/SpringBoot2/springboot-01-cache/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.wdjr + springboot-01-cache + 0.0.1-SNAPSHOT + jar + + springboot-01-cache + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.13.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mybatis + mybatis-spring + 1.3.1 + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.2 + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/Springboot01CacheApplication.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/Springboot01CacheApplication.java new file mode 100644 index 0000000..bc92972 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/Springboot01CacheApplication.java @@ -0,0 +1,16 @@ +package com.wdjr.cache; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@MapperScan("com.wdjr.cache.mapper") +@SpringBootApplication +public class Springboot01CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot01CacheApplication.class, args); + } +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Department.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Department.java new file mode 100644 index 0000000..d992932 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Department.java @@ -0,0 +1,39 @@ +package com.wdjr.cache.bean; + +public class Department { + private Integer id; + private String deptName; + + public Department(){ + + } + + public Department(Integer id, String deptName) { + this.id = id; + this.deptName = deptName; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + @Override + public String toString() { + return "Department{" + + "id=" + id + + ", deptName='" + deptName + '\'' + + '}'; + } +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Employee.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Employee.java new file mode 100644 index 0000000..ba39113 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/bean/Employee.java @@ -0,0 +1,62 @@ +package com.wdjr.cache.bean; + +import java.io.Serializable; + +public class Employee implements Serializable { + private Integer id; + private String lastName; + private String gender; + private String email; + private Integer dId; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Integer getdId() { + return dId; + } + + public void setdId(Integer dId) { + this.dId = dId; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", lastName='" + lastName + '\'' + + ", gender='" + gender + '\'' + + ", email='" + email + '\'' + + ", dId=" + dId + + '}'; + } +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/config/MyRedisConfig.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/config/MyRedisConfig.java new file mode 100644 index 0000000..9998676 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/config/MyRedisConfig.java @@ -0,0 +1,24 @@ +package com.wdjr.cache.config; + +import com.wdjr.cache.bean.Employee; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; + +import java.net.UnknownHostException; + +@Configuration +public class MyRedisConfig { + @Bean + public RedisTemplate empRedisTemplate( + RedisConnectionFactory redisConnectionFactory) + throws UnknownHostException { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(redisConnectionFactory); + Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Employee.class); + template.setDefaultSerializer(jsonRedisSerializer); + return template; + } +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/controller/EmployeeController.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/controller/EmployeeController.java new file mode 100644 index 0000000..c6f6439 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/controller/EmployeeController.java @@ -0,0 +1,37 @@ +package com.wdjr.cache.controller; + +import com.wdjr.cache.bean.Employee; +import com.wdjr.cache.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class EmployeeController { + @Autowired + EmployeeService employeeService; + + @GetMapping("/emp/{id}") + public Employee getEmp(@PathVariable("id")Integer id){ + return employeeService.getEmp(id); + } + @GetMapping("/emp") + public Employee updateEmp(Employee employee){ + + employeeService.updateEmp(employee); + return employee; + + } + @GetMapping("/emp/delete/{id}") + public String deleteEmp(@PathVariable Integer id){ + employeeService.deleteEmp(id); + return "delete的id是:"+id; + } + @GetMapping("/empName/{lastName}") + public Employee getByLastName(@PathVariable String lastName){ + Employee emp = employeeService.getEmpByLastName(lastName); + return emp; + } + +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/DepartmentMapper.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/DepartmentMapper.java new file mode 100644 index 0000000..edd173f --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/DepartmentMapper.java @@ -0,0 +1,4 @@ +package com.wdjr.cache.mapper; + +public interface DepartmentMapper { +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/EmployeeMapper.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/EmployeeMapper.java new file mode 100644 index 0000000..240513b --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/mapper/EmployeeMapper.java @@ -0,0 +1,22 @@ +package com.wdjr.cache.mapper; + + +import com.wdjr.cache.bean.Employee; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +@Mapper +public interface EmployeeMapper { + + @Select("SELECT * FROM employee WHERE id = #{id}") + public Employee getEmpById(Integer id); + @Update("UPDATE employee SET last_name=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}") + public void updateEmp(Employee employee); + @Delete("DELETE FROM employee WHERE employee.id=#{id}") + public void deleteEmp(Integer id); + + @Select("SELECT * FROM employee WHERE last_name=#{lastName}") + public Employee getEmpByLastName(String lastName); +} diff --git a/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/service/EmployeeService.java b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/service/EmployeeService.java new file mode 100644 index 0000000..1cd0882 --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/java/com/wdjr/cache/service/EmployeeService.java @@ -0,0 +1,65 @@ +package com.wdjr.cache.service; + +import com.wdjr.cache.bean.Employee; +import com.wdjr.cache.mapper.EmployeeMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.*; +import org.springframework.stereotype.Service; + +@CacheConfig(cacheNames = "emp") +@Service +public class EmployeeService { + + @Autowired + EmployeeMapper employeeMapper; + + /** + * 将方法的运行结果进行缓存,以后要是再有相同的数据,直接从缓存中获取,不用调用方法 + * CacheManager中管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每个缓存组件都有自己的唯一名字; + * + * 属性: + * CacheName/value:指定存储缓存组件的名字 + * key:缓存数据使用的key,可以使用它来指定。默认是使用方法参数的值,1-方法的返回值 + * 编写Spel表达式:#id 参数id的值, #a0/#p0 #root.args[0] + * keyGenerator:key的生成器,自己可以指定key的生成器的组件id + * key/keyGendertor二选一使用 + * + * cacheManager指定Cache管理器,或者cacheReslover指定获取解析器 + * condition:指定符合条件的情况下,才缓存; + * unless:否定缓存,unless指定的条件为true,方法的返回值就不会被缓存,可以获取到结果进行判断 + * sync:是否使用异步模式 + * + * + * @param id + * @return + */ + @Cacheable(cacheNames = {"emp"},key = "#id",condition = "#id>0",unless = "#result==null") + public Employee getEmp(Integer id){ + System.out.println("查询id= "+id+"的员工"); + return employeeMapper.getEmpById(id); + } + + @CachePut(value = {"emp"},key = "#result.id") + public Employee updateEmp(Employee employee){ + System.out.println("updateEmp"+employee); + employeeMapper.updateEmp(employee); + return employee; + } + + @CacheEvict(value = "emp",key = "#id",allEntries = true) + public void deleteEmp(Integer id){ + System.out.println("delete的id"+id); + } + @Caching( + cacheable = { + @Cacheable(value = "emp",key = "#lastName") + }, + put = { + @CachePut(value = "emp",key = "#result.id"), + @CachePut(value = "emp",key = "#result.gender") + } + ) + public Employee getEmpByLastName(String lastName){ + return employeeMapper.getEmpByLastName(lastName); + } +} diff --git a/SpringBoot2/springboot-01-cache/src/main/resources/application.properties b/SpringBoot2/springboot-01-cache/src/main/resources/application.properties new file mode 100644 index 0000000..dd8eb3b --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://192.168.179.131:3306/mybatis01 +spring.datasource.username=root +spring.datasource.password=Welcome_1 +mybatis.configuration.map-underscore-to-camel-case=true +server.port=9000 +debug=true +spring.redis.host=192.168.179.131 \ No newline at end of file diff --git a/SpringBoot2/springboot-01-cache/src/test/java/com/wdjr/cache/Springboot01CacheApplicationTests.java b/SpringBoot2/springboot-01-cache/src/test/java/com/wdjr/cache/Springboot01CacheApplicationTests.java new file mode 100644 index 0000000..db58a9b --- /dev/null +++ b/SpringBoot2/springboot-01-cache/src/test/java/com/wdjr/cache/Springboot01CacheApplicationTests.java @@ -0,0 +1,55 @@ +package com.wdjr.cache; + +import com.wdjr.cache.bean.Employee; +import com.wdjr.cache.mapper.EmployeeMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Springboot01CacheApplicationTests { + + @Autowired + EmployeeMapper employeeMapper; + + @Autowired + StringRedisTemplate stringRedisTemplate;//操作字符串【常用】 + + @Autowired + RedisTemplate redisTemplate;//操作k-v都是对象 + + @Autowired + RedisTemplate empRedisTemplate; + + @Test + public void contextLoads() { + Employee emp = employeeMapper.getEmpById(53); + System.out.println(emp); + } + + /** + * redis的操作 + * + */ + @Test + public void test01(){ +// stringRedisTemplate.opsForValue().append("msg", "hello"); + String msg = stringRedisTemplate.opsForValue().get("msg"); + + System.out.println(msg); + } + @Test + public void test02(){ + Employee emp = employeeMapper.getEmpById(2); + empRedisTemplate.opsForValue().set("emp-01", emp); + + } + + + +} diff --git "a/SpringBoot\351\253\230\347\272\247\346\225\231\347\250\213.md" "b/SpringBoot\351\253\230\347\272\247\346\225\231\347\250\213.md" index c355245..3433878 100644 --- "a/SpringBoot\351\253\230\347\272\247\346\225\231\347\250\213.md" +++ "b/SpringBoot\351\253\230\347\272\247\346\225\231\347\250\213.md" @@ -2,7 +2,452 @@ ## 一、SpringBoot缓存 -### 1、Redis +缓存的场景 + +- 临时性数据存储【校验码】 +- 避免频繁因为相同的内容查询数据库【查询的信息】 + +## 1、JSR107缓存规范 + +> 用的比较少 + +Java Caching定义了5个核心接口 + +- CachingProvider + + 定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期间访问多个CachingProvider + +- CacheManager + + 定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于CacheManage的上下文中,一个CacheManage只被一个CachingProvider拥有 + +- Cache + + 类似于Map的数据结构并临时储存以key为索引的值,一个Cache仅仅被一个CacheManage所拥有 + +- Entry + + 存储在Cache中的key-value对 + +- Expiry + + 存储在Cache的条目有一个定义的有效期,一旦超过这个时间,就会设置过期的状态,过期无法被访问,更新,删除。缓存的有效期可以通过ExpiryPolicy设置。 + + ![35.cache](E:\工作文档\SpringBoot\images2\35.cache.png) + + + +## 2、Spring的缓存抽象 + +包括一些JSR107的注解 + +CahceManager + +Cache + +### 1、基本概念 + +**重要的概念&缓存注解** + +| | 功能 | +| -------------- | :----------------------------------------------------------- | +| Cache | 缓存接口,定义缓存操作,实现有:RedisCache、EhCacheCache、ConcurrentMapCache等 | +| CacheManager | 缓存管理器,管理各种缓存(Cache)组件 | +| @Cacheable | 针对方法配置,根据方法的请求参数对其结果进行缓存 | +| @CacheEvict | 清空缓存 | +| @CachePut | 保证方法被调用,又希望结果被缓存 update,调用,将信息更新缓存 | +| @EnableCaching | 开启基于注解的缓存 | +| KeyGenerator | 缓存数据时key生成的策略 | +| serialize | 缓存数据时value序列化策略 | + +### 2、整合项目 + +1、新建一个SpringBoot1.5+web+mysql+mybatis+cache + +2、编写配置文件,连接Mysql + +```properties +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://192.168.179.131:3306/mybatis01 +spring.datasource.username=root +spring.datasource.password=Welcome_1 +mybatis.configuration.map-underscore-to-camel-case=true +server.port=9000 +``` + +3、创建一个bean实例 + +Department + +```java +package com.wdjr.cache.bean; + +public class Department { + private Integer id; + private String deptName; + + public Department(){ + + } + + public Department(Integer id, String deptName) { + this.id = id; + this.deptName = deptName; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + @Override + public String toString() { + return "Department{" + + "id=" + id + + ", deptName='" + deptName + '\'' + + '}'; + } +} +``` + +Employee + +```java +package com.wdjr.cache.bean; + +public class Employee { + private Integer id; + private String lastName; + private String gender; + private String email; + private Integer dId; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Integer getdId() { + return dId; + } + + public void setdId(Integer dId) { + this.dId = dId; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", lastName='" + lastName + '\'' + + ", gender='" + gender + '\'' + + ", email='" + email + '\'' + + ", dId=" + dId + + '}'; + } +} +``` + +4、创建mapper接口映射数据库,并访问数据库中的数据 + +```java +package com.wdjr.cache.mapper; + + +import com.wdjr.cache.bean.Employee; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +@Mapper +public interface EmployeeMapper { + + @Select("SELECT * FROM employee WHERE id = #{id}") + public Employee getEmpById(Integer id); + @Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}") + public void updateEmp(Employee employee); +} +``` + +5、主程序添加注解MapperScan,并且使用@EnableCaching开启缓存 + +```java +package com.wdjr.cache; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@MapperScan("com.wdjr.cache.mapper") +@SpringBootApplication +public class Springboot01CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot01CacheApplication.class, args); + } +} +``` + +6、编写service,来具体实现mapper中的方法 + +```java +package com.wdjr.cache.service; + +import com.wdjr.cache.bean.Employee; +import com.wdjr.cache.mapper.EmployeeMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +@Service +public class EmployeeService { + + @Autowired + EmployeeMapper employeeMapper; + + /** + * 将方法的运行结果进行缓存,以后要是再有相同的数据,直接从缓存中获取,不用调用方法 + * CacheManager中管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每个缓存组件都有自己的唯一名字; + * + * 属性: + * CacheName/value:指定存储缓存组件的名字 + * key:缓存数据使用的key,可以使用它来指定。默认是使用方法参数的值,1-方法的返回值 + * 编写Spel表达式:#id 参数id的值, #a0/#p0 #root.args[0] + * keyGenerator:key的生成器,自己可以指定key的生成器的组件id + * key/keyGendertor二选一使用 + * + * cacheManager指定Cache管理器,或者cacheReslover指定获取解析器 + * condition:指定符合条件的情况下,才缓存; + * unless:否定缓存,unless指定的条件为true,方法的返回值就不会被缓存,可以获取到结果进行判断 + * sync:是否使用异步模式,unless不支持 + * + * + * @param id + * @return + */ + @Cacheable(cacheNames = {"emp"},key = "#id",condition = "#id>0",unless = "#result==null") + public Employee getEmp(Integer id){ + System.out.println("查询id= "+id+"的员工"); + return employeeMapper.getEmpById(id); + } +} +``` + +7、编写controller测试 + +```java +@RestController +public class EmployeeController { + @Autowired + EmployeeService employeeService; + + @GetMapping("/emp/{id}") + public Employee getEmp(@PathVariable("id")Integer id){ + return employeeService.getEmp(id); + } +} +``` + +8、测试结果 + +![35.cache](E:\工作文档\SpringBoot\images2\35.cache.jpg) + +继续访问,就不会执行方法,因为直接在缓存中取值 + +### 3、缓存原理 + +原理: + +1、CacheAutoConfiguration + +2、导入缓存组件 + +![36.importcache](E:\工作文档\SpringBoot\images2\36.importcache.jpg) + +3、查看哪个缓存配置生效 + +``` +SimpleCacheConfiguration生效 +``` + +4、给容器注册一个CacheManager:ConcurrentMapCacheManager + +5、可以获取和创建ConcurrentMapCache,作用是将数据保存在ConcurrentMap中 + +运行流程 + +1、方法运行之前,先查Cache(缓存组件),按照cacheName的指定名字获取; + +(CacheManager先获取相应的缓存),第一次获取缓存如果没有cache组件会自己创建 + +2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数; + +key是按照某种策略生成的,默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key + +没有参数 key=new SimpleKey() + +如果有一个参数 key=参数值 + +如果多个参数 key=new SimpleKey(params); + +3、没有查到缓存就调用目标方法 + +4、将目标方法返回的结果,放回缓存中 + +方法执行之前,@Cacheable先来检查缓存中是否有数据,按照参数的值作为key去查询缓存,如果没有,就运行方法,存入缓存,如果有数据,就取出map的值。 + +### 4、Cache的注解 + +#### 1、@Cacheput + +修改数据库的某个数据,同时更新缓存 + +运行时机 + +先运行方法,再将目标结果缓存起来 + + + +> cacheable的key是不能使用result的参数的 + +1、编写更新方法 + +```java +@CachePut(value = {"emp"},key = "#result.id") +public Employee updateEmp(Employee employee){ + System.out.println("updateEmp"+employee); + employeeMapper.updateEmp(employee); + return employee; +} +``` + +2、编写Controller方法 + +```java +@GetMapping("/emp") +public Employee updateEmp(Employee employee){ + employeeService.updateEmp(employee); + return employee; +} +``` + +测试 + +测试步骤 + +1、先查询1号员工 + +2、更新1号员工数据 + +3、查询1号员工 + +可能并没有更新, + +是因为查询和更新的key不同 + +效果: + +- 第一次查询:查询mysql +- 第二次更新:更新mysql +- 第三次查询:调用内存 + +#### 2、CacheEvict + +清除缓存 + +编写测试方法 + +```java +@CacheEvict(value = "emp",key = "#id") +public void deleteEmp(Integer id){ + System.out.println("delete的id"+id); +} +``` + +allEntries = true,代表不论清除那个key,都重新刷新缓存 + +beforeInvocation=true.方法执行前,清空缓存,默认是false,如果程序异常,就不会清除缓存 + +#### 3、Caching + +组合 + +- Cacheable +- CachePut +- CacheEvict + +CacheConfig抽取缓存的公共配置 + +```java +@CacheConfig(cacheNames = "emp") +@Service +public class EmployeeService { +``` + +然后下面的value=emp就不用写了 + + + +```java +@Caching( + cacheable = { + @Cacheable(value = "emp",key = "#lastName") + }, + put = { + @CachePut(value = "emp",key = "#result.id"), + @CachePut(value = "emp",key = "#result.gender") + } +) +public Employee getEmpByLastName(String lastName){ + return employeeMapper.getEmpByLastName(lastName); +} +``` + +如果查完lastName,再查的id是刚才的值,就会直接从缓存中获取数据 + + + +### 5、Redis 默认的缓存是在内存中定义HashMap,生产中使用Redis的缓存中间件 @@ -10,7 +455,611 @@ Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统 -## 二、SpringBoot的消息中间件 +#### 1、安装Docker + +安装redis在docker上 + +```shell +#拉取redis镜像 +docker pull redis +#启动redis[bfcb1f6df2db]docker images的id + docker run -d -p 6379:6379 --name redis01 bfcb1f6df2db +``` + +#### 2、Redis的Template + +Redis的常用五大数据类型 + +String【字符串】、List【列表】、Set【集合】、Hash【散列】、ZSet【有序集合】 + +分为两种一种是**StringRedisTemplate**,另一种是**RedisTemplate** + +根据不同的数据类型,大致的操作也分为这5种,以StringRedisTemplate为例 + +``` +stringRedisTemplate.opsForValue() --String +stringRedisTemplate.opsForList() --List +stringRedisTemplate.opsForSet() --Set +stringRedisTemplate.opsForHash() --Hash +stringRedisTemplate.opsForZset() -Zset +``` + +1、导入依赖 + +```xml + + org.springframework.boot + spring-boot-starter-data-redis + +``` + +2、修改配置文件 + +```properties +spring.redis.host=192.168.179.131 +``` + +3、添加测试类 + +```java + @Autowired + StringRedisTemplate stringRedisTemplate;//操作字符串【常用】 + + @Autowired + RedisTemplate redisTemplate;//操作k-v都是对象 + @Test + public void test01(){ +// stringRedisTemplate.opsForValue().append("msg", "hello"); + String msg = stringRedisTemplate.opsForValue().get("msg"); + System.out.println(msg); + } +``` + +写入数据 + +![37.redis](E:\工作文档\SpringBoot\images2\37.redis.jpg) + +读取数据 + +![38.redis02](E:\工作文档\SpringBoot\images2\38.redis02.jpg) + + + +#### 3、测试保存对象 + +> 对象需要序列化 + +1、序列化bean对象 + +```java +public class Employee implements Serializable { +``` + +2、将对象存储到Redis + +```java +@Test +public void test02(){ + Employee emp = employeeMapper.getEmpById(2); + redisTemplate.opsForValue().set("emp-01", emp); +} +``` + +3、效果演示 + +![38.redis03](E:\工作文档\SpringBoot\images2\38.redis03.jpg) + +#### 4、以json方式传输对象 + +1、新建一个Redis的配置类MyRedisConfig, + +```java +@Configuration +public class MyRedisConfig { + @Bean + public RedisTemplate empRedisTemplate( + RedisConnectionFactory redisConnectionFactory) + throws UnknownHostException { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(redisConnectionFactory); + Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Employee.class); + template.setDefaultSerializer(jsonRedisSerializer); + return template; + } +``` + +2、编写测试类 + +```java + @Autowired + RedisTemplate empRedisTemplate; +@Test +public void test02(){ + Employee emp = employeeMapper.getEmpById(2); + empRedisTemplate.opsForValue().set("emp-01", emp); + +} +``` + +3、测试效果 + +![39.redis04](E:\工作文档\SpringBoot\images2\39.redis04.jpg) + + + +## 二、SpringBoot的消息中间件 + +### 1、JMS&AMQP简介 + +1、异步处理 + +同步机制 + +![09.同步](E:\工作文档\SpringBoot\images2\09.同步.png) + +并发机制 + +![10.异步](E:\工作文档\SpringBoot\images2\10.异步.png) + +消息队列机制 + +![11.消息](E:\工作文档\SpringBoot\images2\11.消息.png) + + + +2、应用解耦 + +使用中间件,将两个服务解耦,一个写入,一个订阅 + +3、流量削锋 + +例如消息队列的FIFO,限定元素的长度,防止出现多次请求导致的误操作 + +#### 概述 + +1、大多数应用,可以通过消息服务中间件来提升系统的异步通信、拓展解耦能力 + +2、消息服务中的两个重要概念: + +消息代理(message broker)和目的地(destination),当消息发送者发送消息以后,将由消息代理接管,消息代理保证消息传递到指定的目的地。 + +3、消息队列主要的两种形式的目的地 + +1)、队列(queue):点对点消息通信【point-to-point】,取出一个没一个,一个发布,多个消费 + +2)、主题(topic):发布(publish)/订阅(subscribe)消息通信,多人【订阅者】可以同时接到消息 + +4、JMS(Java Message Service) Java消息服务: + +- 基于JVM消息规范的代理。ActiveMQ/HornetMQ是JMS的实现 + +5、AMQP(Advanced Message Queuing Protocol) + +- 高级消息队列协议,也是一个消息代理的规范,兼容JMS +- RabbitMQ是AMQP的实现 + +| | JMS | AMQP | +| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 定义 | Java API | 网络线级协议 | +| 跨平台 | 否 | 是 | +| 跨语言 | 否 | 是 | +| Model | (1)、Peer-2-Peer
(2)、Pub/Sub | (1)、direct exchange
(2)、fanout exchange
(3)、topic change
(4)、headers exchange
(5)、system exchange
后四种都是pub/sub ,差别路由机制做了更详细的划分 | +| 支持消息类型 | TextMessage
MapMessage
ByteMessage
StreamMessage
ObjectMessage
Message | byte[]通常需要序列化 | + +6、SpringBoot的支持 + +spring-jms提供了对JMS的支持 + +spring-rabbit提供了对AMQP的支持 + +需要创建ConnectionFactory的实现来连接消息代理 + +提供JmsTemplate,RabbitTemplate来发送消息 + +@JmsListener(JMS).@RabbitListener(AMQP)注解在方法上的监听消息代理发布的消息 + +@EnableJms,@EnableRabbit开启支持 + +7、SpringBoot的自动配置 + +- JmsAutoConfiguration +- RabbitAutoConfiguration + +### 2、RabbitMQ简介 + +> AMQP的实现 + +#### 1、核心概念 + +**Message**:消息头和消息体组成,消息体是不透明的,而消息头上则是由一系列的可选属性组成,属性:路由键【routing-key】,优先级【priority】,指出消息可能需要持久性存储【delivery-mode】 + +**Publisher**:消息的生产者,也是一个向交换器发布消息的客户端应用程序 + +**Exchange**:交换器,用来接收生产者发送的消息并将这些消息路由给服务器中的队列 + +Exchange的4中类型:direct【默认】点对点,fanout,topic和headers, 发布订阅,不同类型的Exchange转发消息的策略有所区别 + +**Queue**:消息队列,用来保存消息直到发送给消费者,它是消息的容器,也是消息的终点,一个消息可投入一个或多个队列,消息一直在队列里面,等待消费者连接到这个队列将数据取走。 + +**Binding**:绑定,队列和交换机之间的关联,多对多关系 + +**Connection**:网络连接,例如TCP连接 + +Channel:信道,多路复用连接中的一条独立的双向数据流通道,信道是建立在真是的TCP链接之内的虚拟连接AMQP命令都是通过信道发送出去的。不管是发布消息,订阅队列还是接受消息,都是信道,减少TCP的开销,复用一条TCP连接。 + +**Consumer**:消息的消费者,表示一个从消息队列中取得消息的客户端的 应用程序 + +**VirtualHost**:小型的rabbitMQ,相互隔离 + +**Broker**:表示消息队列 服务实体 + +![13.RabbitMQ结构](E:\工作文档\SpringBoot\images2\13.RabbitMQ结构.png) + + + +#### 2、RabbitMQ的运行机制 + +Exchange的三种方式 + +direct:根据路由键直接匹配,一对一 + +![14.RabbitMQDirect](E:\工作文档\SpringBoot\images2\14.RabbitMQDirect.png) + +fanout:不经过路由键,直接发送到每一个队列 + +![14.RabbitMQfaout](E:\工作文档\SpringBoot\images2\14.RabbitMQfaout.png) + +topic:类似模糊匹配的根据路由键,来分配绑定的队列 + +![14.RabbitMQtopic](E:\工作文档\SpringBoot\images2\14.RabbitMQtopic.png) + + + +#### 3、RabbitMQ安装测试 + +1、打开虚拟机,在docker中安装RabbitMQ + +```shell +#1.安装rabbitmq,使用镜像加速 +docker pull registry.docker-cn.com/library/rabbitmq:3-management +[root@node1 ~]# docker images +REPOSITORY TAG IMAGE ID CREATED SIZE +registry.docker-cn.com/library/rabbitmq 3-management c51d1c73d028 11 days ago 149 MB +#2.运行rabbitmq +##### 端口:5672 客户端和rabbitmq通信 15672:管理界面的web页面 + +docker run -d -p 5672:5672 -p 15672:15672 --name myrabbitmq c51d1c73d028 + +#3.查看运行 +docker ps +``` + +2、打开网页客户端并登陆,账号【guest】,密码【guest】,登陆 + +![13.rabbitmq](E:\工作文档\SpringBoot\images2\13.rabbitmq.jpg) + + + +3、添加 【direct】【faout】【topic】的绑定关系等 + +1)、添加Exchange,分别添加**exchange.direct**、**exchange.fanout**、**exchange.topic** + +![15.exchanges](E:\工作文档\SpringBoot\images2\15.exchanges.jpg) + +2)、添加 Queues,分别添加**lxy.news、wdjr、wdjr.emps、wdjr.news** + +![16.queues](E:\工作文档\SpringBoot\images2\16.queues.jpg) + +3)、点击【exchange.direct】添加绑定规则 + +![17.bind](E:\工作文档\SpringBoot\images2\17.bind.jpg) + + + +4)、点击【exchange.fanout】添加绑定规则 + +![18,bindfanout](E:\工作文档\SpringBoot\images2\18,bindfanout.jpg) + +5)、点击【exchange.topic】添加绑定规则 + +![19,bind_topic](E:\工作文档\SpringBoot\images2\19,bind_topic.jpg) + + + +> /*: 代表匹配1个单词 +> +> /#:代表匹配0个或者多个单词 + +4、发布信息测试 + +【direct】发布命令,点击 Publish message + +![20.publish-direct](E:\工作文档\SpringBoot\images2\20.publish-direct.jpg) + +查看队列的数量 + +![21.queue-direct](E:\工作文档\SpringBoot\images2\21.queue-direct.jpg) + +点击查看发送的信息 + +![22.msg-direct](E:\工作文档\SpringBoot\images2\22.msg-direct.jpg) + +【fanout】的发布消息 + +![23.pub-fanout](E:\工作文档\SpringBoot\images2\23.pub-fanout.jpg) + +队列信息 + +![24.queue-fanout](E:\工作文档\SpringBoot\images2\24.queue-fanout.jpg) + + + +随意一个数据信息例如:wdjr.emp + +![25.msg-fanout](E:\工作文档\SpringBoot\images2\25.msg-fanout.jpg) + +【topic】发布信息测试 + +![26.pub-topic](E:\工作文档\SpringBoot\images2\26.pub-topic.jpg) + +队列的值 + +![27.que-topic](E:\工作文档\SpringBoot\images2\27.que-topic.jpg) + +信息查看 + +![28.msg-topic](E:\工作文档\SpringBoot\images2\28.msg-topic.jpg) + +#### 4、创建工程整合 + +```java +1、RabbitAutoConfiguration +2、自动配置了连接工厂 ConnectionFactory +3、RabbitProperties封装了 RabbitMQ +4、RabbitTemplate:给RabbitMQ发送和接受消息的 +5、AmqpAdmin:RabbitMQ的系统管理功能组件 +``` + +##### 1、RabbitTemplate + +1、新建SpringBoot工程,SpringBoot1.5+Integeration/RabbitMQ+Web + +2、RabbitAutoConfiguration文件 + +3、编写配置文件application.yml + +```yaml +spring: + rabbitmq: + host: 192.168.179.131 + port: 5672 + username: guest + password: guest +``` + +4、编写测试类,将HashMap写入Queue + +```java + @Autowired + RabbitTemplate rabbitTemplate; + + @Test + public void contextLoads() { + //Message需要自己构建一个;定义消息体内容和消息头 + // rabbitTemplate.send(exchange, routingKey, message); + //Object 默认当成消息体,只需要传入要发送的对象,自动化序列发送给rabbitmq; + Map map = new HashMap<>(); + map.put("msg", "这是第一个信息"); + map.put("data", Arrays.asList("helloWorld",123,true)); + //对象被默认序列以后发送出去 + rabbitTemplate.convertAndSend("exchange.direct","wdjr.news",map); + } +``` + +5、查看网页的信息 + +![29.dir-idea](E:\工作文档\SpringBoot\images2\29.dir-idea.jpg) + +6、取出队列的值 + +> 取出队列中数据就没了 + +```java +@Test +public void reciverAndConvert(){ + + Object o = rabbitTemplate.receiveAndConvert("wdjr.news"); + System.out.println(o.getClass()); + System.out.println(o); + +} +``` + +结果 + +``` +class java.util.HashMap +{msg=这是第一个信息, data=[helloWorld, 123, true]} +``` + +7、使用Json方式传递,并传入对象Book + +1)、MyAMQPConfig + +```java +@Configuration +public class MyAMQPConfig { + + @Bean + public MessageConverter messageConverter(){ + return new Jackson2JsonMessageConverter(); + } +} +``` + +2)、编写Book实体类 + +```java +package com.wdjr.amqp.bean; + +public class Book { + private String bookName; + private String author; + + public Book(){ + + } + + public Book(String bookName, String author) { + this.bookName = bookName; + this.author = author; + } + + public String getBookName() { + return bookName; + } + + public void setBookName(String bookName) { + this.bookName = bookName; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Book{" + + "bookName='" + bookName + '\'' + + ", author='" + author + '\'' + + '}'; + } +} +``` + +3)、测试类 + +```java +@Test +public void contextLoads() { + //对象被默认序列以后发送出去 + rabbitTemplate.convertAndSend("exchange.direct","wdjr.news",new Book("百年孤独", "季羡林")); +} +``` + +4)、查看wdjr.news + +![30.dir-idea-json](E:\工作文档\SpringBoot\images2\30.dir-idea-json.jpg) + +5)、取出数据 + +```java +@Test +public void reciverAndConvert(){ + Object o = rabbitTemplate.receiveAndConvert("wdjr.news"); + System.out.println(o.getClass()); + System.out.println(o); +} +``` + +6)、结果演示 + +``` +class com.wdjr.amqp.bean.Book +Book{bookName='百年孤独', author='季羡林'} +``` + +##### 2、开启基于注解的方式 + +1、新建一个BookService + +```java +@Service +public class BookService { + @RabbitListener(queues = "wdjr.news") + public void receive(Book book){ + System.out.println(book); + } + + @RabbitListener(queues = "wdjr") + public void receive02(Message message){ + System.out.println(message.getBody()); + System.out.println(message.getMessageProperties()); + } +} +``` + +2、主程序开启RabbitMQ的注解 + +```java +@EnableRabbit //开启基于注解的rabbitmq +@SpringBootApplication +public class AmqpApplication { + + public static void main(String[] args) { + SpringApplication.run(AmqpApplication.class, args); + } +} +``` + +##### 3、AmqpAdmin + +> 创建和删除 Exchange 、Queue、Bind + +1)、创建Exchange + +```java +@Test +public void createExchange(){ + amqpAdmin.declareExchange(new DirectExchange("amqpadmin.direct")); + System.out.println("Create Finish"); +} +``` + +效果演示 + +![31.createAMQP](E:\工作文档\SpringBoot\images2\31.createAMQP.jpg) + + + +2)、创建Queue + +```java +@Test +public void createQueue(){ + amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true)); + System.out.println("Create Queue Finish"); +} +``` + + + +![32.createQueue](E:\工作文档\SpringBoot\images2\32.createQueue.jpg) + +3)、创建Bind规则 + +```java +@Test +public void createBind(){ + amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE , "amqpadmin.direct", "amqp.haha", null)); +} +``` + +![33.createBinding](E:\工作文档\SpringBoot\images2\33.createBinding.jpg) + +删除类似 + +```java +@Test +public void deleteExchange(){ + amqpAdmin.deleteExchange("amqpadmin.direct"); + System.out.println("delete Finish"); +} +``` ## 三、SpringBoot的检索 diff --git a/images2/13.rabbitmq.jpg b/images2/13.rabbitmq.jpg new file mode 100644 index 0000000..13e0cc9 Binary files /dev/null and b/images2/13.rabbitmq.jpg differ diff --git a/images2/15.exchanges.jpg b/images2/15.exchanges.jpg new file mode 100644 index 0000000..79fc85f Binary files /dev/null and b/images2/15.exchanges.jpg differ diff --git a/images2/16.queues.jpg b/images2/16.queues.jpg new file mode 100644 index 0000000..da3bb39 Binary files /dev/null and b/images2/16.queues.jpg differ diff --git a/images2/17.bind.jpg b/images2/17.bind.jpg new file mode 100644 index 0000000..6ef0427 Binary files /dev/null and b/images2/17.bind.jpg differ diff --git a/images2/18,bindfanout.jpg b/images2/18,bindfanout.jpg new file mode 100644 index 0000000..2f33ccd Binary files /dev/null and b/images2/18,bindfanout.jpg differ diff --git a/images2/19,bind_topic.jpg b/images2/19,bind_topic.jpg new file mode 100644 index 0000000..6607b1b Binary files /dev/null and b/images2/19,bind_topic.jpg differ diff --git a/images2/20.publish-direct.jpg b/images2/20.publish-direct.jpg new file mode 100644 index 0000000..dd15c29 Binary files /dev/null and b/images2/20.publish-direct.jpg differ diff --git a/images2/21.queue-direct.jpg b/images2/21.queue-direct.jpg new file mode 100644 index 0000000..d568903 Binary files /dev/null and b/images2/21.queue-direct.jpg differ diff --git a/images2/22.msg-direct.jpg b/images2/22.msg-direct.jpg new file mode 100644 index 0000000..28f000f Binary files /dev/null and b/images2/22.msg-direct.jpg differ diff --git a/images2/23.pub-fanout.jpg b/images2/23.pub-fanout.jpg new file mode 100644 index 0000000..0aa4363 Binary files /dev/null and b/images2/23.pub-fanout.jpg differ diff --git a/images2/24.queue-fanout.jpg b/images2/24.queue-fanout.jpg new file mode 100644 index 0000000..6acf6ca Binary files /dev/null and b/images2/24.queue-fanout.jpg differ diff --git a/images2/25.msg-fanout.jpg b/images2/25.msg-fanout.jpg new file mode 100644 index 0000000..40463c2 Binary files /dev/null and b/images2/25.msg-fanout.jpg differ diff --git a/images2/26.pub-topic.jpg b/images2/26.pub-topic.jpg new file mode 100644 index 0000000..2ccc200 Binary files /dev/null and b/images2/26.pub-topic.jpg differ diff --git a/images2/27.que-topic.jpg b/images2/27.que-topic.jpg new file mode 100644 index 0000000..fcfb047 Binary files /dev/null and b/images2/27.que-topic.jpg differ diff --git a/images2/28.msg-topic.jpg b/images2/28.msg-topic.jpg new file mode 100644 index 0000000..4c5f684 Binary files /dev/null and b/images2/28.msg-topic.jpg differ diff --git a/images2/29.dir-idea.jpg b/images2/29.dir-idea.jpg new file mode 100644 index 0000000..e83790e Binary files /dev/null and b/images2/29.dir-idea.jpg differ diff --git a/images2/30.dir-idea-json.jpg b/images2/30.dir-idea-json.jpg new file mode 100644 index 0000000..c0ec0c8 Binary files /dev/null and b/images2/30.dir-idea-json.jpg differ diff --git a/images2/31.createAMQP.jpg b/images2/31.createAMQP.jpg new file mode 100644 index 0000000..da88b67 Binary files /dev/null and b/images2/31.createAMQP.jpg differ diff --git a/images2/32.createQueue.jpg b/images2/32.createQueue.jpg new file mode 100644 index 0000000..c9046ce Binary files /dev/null and b/images2/32.createQueue.jpg differ diff --git a/images2/33.createBinding.jpg b/images2/33.createBinding.jpg new file mode 100644 index 0000000..75bb00a Binary files /dev/null and b/images2/33.createBinding.jpg differ diff --git a/images2/34.elastic-head.jpg b/images2/34.elastic-head.jpg new file mode 100644 index 0000000..b10a457 Binary files /dev/null and b/images2/34.elastic-head.jpg differ diff --git a/images2/35.cache.jpg b/images2/35.cache.jpg new file mode 100644 index 0000000..4593900 Binary files /dev/null and b/images2/35.cache.jpg differ diff --git a/images2/35.cache.png b/images2/35.cache.png new file mode 100644 index 0000000..3c50ea4 Binary files /dev/null and b/images2/35.cache.png differ diff --git a/images2/36.importcache.jpg b/images2/36.importcache.jpg new file mode 100644 index 0000000..bad2ab9 Binary files /dev/null and b/images2/36.importcache.jpg differ diff --git a/images2/37.redis.jpg b/images2/37.redis.jpg new file mode 100644 index 0000000..0a69f09 Binary files /dev/null and b/images2/37.redis.jpg differ diff --git a/images2/38.redis02.jpg b/images2/38.redis02.jpg new file mode 100644 index 0000000..a4c8ffa Binary files /dev/null and b/images2/38.redis02.jpg differ diff --git a/images2/38.redis03.jpg b/images2/38.redis03.jpg new file mode 100644 index 0000000..533a4a9 Binary files /dev/null and b/images2/38.redis03.jpg differ diff --git a/images2/39.redis04.jpg b/images2/39.redis04.jpg new file mode 100644 index 0000000..e017198 Binary files /dev/null and b/images2/39.redis04.jpg differ