├── .gitignore ├── lucene_demo ├── pom.xml └── src │ ├── .gitignore │ ├── main │ ├── java │ │ └── org │ │ │ └── yyh │ │ │ ├── constant │ │ │ └── LuceneConstants.java │ │ │ ├── lucence │ │ │ ├── Indexer.java │ │ │ └── Searcher.java │ │ │ └── model │ │ │ ├── ItemModel.java │ │ │ └── ResultModel.java │ └── resources │ │ └── application.properties │ ├── mvnw │ ├── mvnw.cmd │ └── test │ └── java │ └── src │ └── LuceneTest.java ├── quartzkearn ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── yy │ ├── job │ └── MyJob.java │ └── test │ └── QuartzSimpleDemo.java ├── springkafka ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── yyh │ ├── Application.java │ ├── config │ └── KafkaConfig.java │ ├── controller │ └── KafkaController.java │ └── service │ └── MyMessageListener.java ├── springkafka2 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── yyh │ │ ├── Application.java │ │ ├── config │ │ ├── KafkaConfig.java │ │ └── TopicConfig.java │ │ ├── controller │ │ └── KafkaController.java │ │ └── listener │ │ └── MyListener.java │ └── resources │ └── application.properties ├── springmybatis ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── yyh │ │ ├── AppDemoMain.java │ │ ├── config │ │ ├── DataSourceConfig.java │ │ └── MybatisConfig.java │ │ ├── controller │ │ └── MyController.java │ │ ├── dao │ │ ├── CourseDao.java │ │ └── StudentDao.java │ │ └── dto │ │ ├── Course.java │ │ └── Student.java │ └── resources │ ├── application.properties │ ├── datasource.properties │ └── logback.xml ├── springsecuritydemo ├── demo │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── yyh │ │ │ ├── MainApp.java │ │ │ ├── config │ │ │ ├── DataScourceConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── controller │ │ │ ├── TestController.java │ │ │ └── UserController.java │ │ │ ├── mapper │ │ │ ├── BaseMapper.java │ │ │ ├── ClResourceMapper.java │ │ │ ├── ClRoleMapper.java │ │ │ ├── ClUserMapper.java │ │ │ └── PermissionMapper.java │ │ │ ├── model │ │ │ ├── ClResource.java │ │ │ ├── ClRole.java │ │ │ ├── ClUser.java │ │ │ └── Permission.java │ │ │ ├── service │ │ │ └── UserService.java │ │ │ └── util │ │ │ └── IDCard.java │ │ └── resources │ │ ├── application.properties │ │ ├── logback.xml │ │ ├── mapper │ │ ├── ClResourceMapper.xml │ │ ├── ClRoleMapper.xml │ │ ├── ClUserMapper.xml │ │ └── PermissionMapper.xml │ │ ├── sql │ │ └── template │ │ ├── accessDenied.ftl │ │ ├── error.ftl │ │ ├── home.ftl │ │ ├── index.ftl │ │ └── loginFail.ftl ├── mybats_generator │ ├── pom.xml │ └── src │ │ └── main │ │ └── resources │ │ └── generatorConfig.xml └── pom.xml ├── springswagger ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── yyh │ ├── Application.java │ ├── config │ └── Swagger2Config.java │ ├── controller │ └── AnimalController.java │ └── dto │ ├── AnimalError.java │ └── Dog.java ├── springtransaction ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── yyh │ │ ├── AppDemoMain.java │ │ ├── config │ │ ├── DataSourceConfig.java │ │ └── MybatisConfig.java │ │ ├── dto │ │ ├── Account.java │ │ └── ClUser.java │ │ ├── mapper │ │ ├── AccountMapper.java │ │ └── ClUserMapper.java │ │ └── service │ │ ├── AccountService.java │ │ └── TransactionService.java │ ├── resources │ ├── application.properties │ ├── datasource.properties │ ├── logback.xml │ └── mapper │ │ ├── AccountMapper.xml │ │ └── ClUserMapper.xml │ └── test │ └── create_data │ ├── IdCardGenerator.java │ └── MyTest.java └── websocketDemo ├── client ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── yyh │ └── client │ ├── MsgWebSocketClient.java │ └── MyWebSocketHandler.java ├── pom.xml └── server ├── pom.xml └── src └── main ├── java └── com │ └── yyh │ └── server │ ├── Application.java │ ├── config │ └── WebSocketConfig.java │ ├── controller │ └── GreetingController.java │ └── message │ ├── Greeting.java │ └── HelloMessage.java └── resources └── static ├── app.js └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | *.iml 3 | target/ 4 | ### Java template 5 | *.class 6 | 7 | # Mobile Tools for Java (J2ME) 8 | .mtj.tmp/ 9 | 10 | # Package Files # 11 | *.jar 12 | *.war 13 | *.ear 14 | 15 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 16 | hs_err_pid* 17 | ### JetBrains template 18 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 19 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 20 | 21 | # User-specific stuff: 22 | .idea/workspace.xml 23 | .idea/tasks.xml 24 | .idea/dictionaries 25 | .idea/vcs.xml 26 | .idea/jsLibraryMappings.xml 27 | 28 | # Sensitive or high-churn files: 29 | .idea/dataSources.ids 30 | .idea/dataSources.xml 31 | .idea/dataSources.local.xml 32 | .idea/sqlDataSources.xml 33 | .idea/dynamic.xml 34 | .idea/uiDesigner.xml 35 | 36 | # Gradle: 37 | .idea/gradle.xml 38 | .idea/libraries 39 | .DS_Store 40 | # Mongo Explorer plugin: 41 | .idea/mongoSettings.xml 42 | 43 | ## File-based project format: 44 | *.iws 45 | 46 | ## Plugin-specific files: 47 | 48 | # IntelliJ 49 | /out/ 50 | .idea 51 | 52 | # mpeltonen/sbt-idea plugin 53 | .idea_modules/ 54 | 55 | # JIRA plugin 56 | atlassian-ide-plugin.xml 57 | 58 | # Crashlytics plugin (for Android Studio and IntelliJ) 59 | com_crashlytics_export_strings.xml 60 | crashlytics.properties 61 | crashlytics-build.properties 62 | fabric.properties 63 | ### Eclipse template 64 | 65 | .metadata 66 | bin/ 67 | tmp/ 68 | *.tmp 69 | *.bak 70 | *.swp 71 | *~.nib 72 | local.properties 73 | .settings/ 74 | .loadpath 75 | .recommenders 76 | 77 | # Eclipse Core 78 | .project 79 | 80 | # External tool builders 81 | .externalToolBuilders/ 82 | 83 | # Locally stored "Eclipse launch configurations" 84 | *.launch 85 | 86 | # PyDev specific (Python IDE for Eclipse) 87 | *.pydevproject 88 | 89 | # CDT-specific (C/C++ Development Tooling) 90 | .cproject 91 | 92 | # JDT-specific (Eclipse Java Development Tools) 93 | .classpath 94 | 95 | # Java annotation processor (APT) 96 | .factorypath 97 | 98 | # PDT-specific (PHP Development Tools) 99 | .buildpath 100 | 101 | # sbteclipse plugin 102 | .target 103 | 104 | # Tern plugin 105 | .tern-project 106 | 107 | # TeXlipse plugin 108 | .texlipse 109 | 110 | # STS (Spring Tool Suite) 111 | .springBeans 112 | 113 | # Code Recommenders 114 | .recommenders/ 115 | 116 | -------------------------------------------------------------------------------- /lucene_demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.yyh 8 | lucene_demo 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 1.8 13 | 7.7.1 14 | 15 | 16 | 17 | 18 | 19 | org.apache.lucene 20 | lucene-core 21 | ${lucene.version} 22 | 23 | 24 | 25 | org.apache.lucene 26 | lucene-queryparser 27 | ${lucene.version} 28 | 29 | 30 | 31 | org.apache.lucene 32 | lucene-highlighter 33 | ${lucene.version} 34 | 35 | 36 | 37 | org.apache.lucene 38 | lucene-analyzers-common 39 | ${lucene.version} 40 | 41 | 42 | 43 | 44 | org.apache.lucene 45 | lucene-queries 46 | ${lucene.version} 47 | 48 | 49 | 50 | org.apache.lucene 51 | lucene-analyzers-smartcn 52 | ${lucene.version} 53 | 54 | 55 | 56 | 57 | org.apache.lucene 58 | lucene-test-framework 59 | ${lucene.version} 60 | test 61 | 62 | 63 | 64 | com.alibaba 65 | fastjson 66 | 1.2.54 67 | 68 | 69 | 70 | commons-io 71 | commons-io 72 | 2.4 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.apache.maven.plugins 82 | maven-compiler-plugin 83 | 3.1 84 | 85 | ${java.version} 86 | ${java.version} 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /lucene_demo/src/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /lucene_demo/src/main/java/org/yyh/constant/LuceneConstants.java: -------------------------------------------------------------------------------- 1 | package org.yyh.constant; 2 | 3 | /** 4 | * @author: lhy 5 | * @description: 6 | * @date: 2019-03-05 11:12 7 | **/ 8 | public class LuceneConstants { 9 | public static final String CONTENTS = "content"; 10 | public static final String ID = "id"; 11 | public static final String FILE_NAME = "filename"; 12 | public static final String FILE_PATH = "filepath"; 13 | public static final String INDEX_PATH = "C:\\Users\\42515\\Desktop\\lucene-test\\index"; 14 | public static final int MAX_SEARCH = 10; 15 | } 16 | -------------------------------------------------------------------------------- /lucene_demo/src/main/java/org/yyh/lucence/Indexer.java: -------------------------------------------------------------------------------- 1 | package org.yyh.lucence; 2 | 3 | import org.apache.commons.io.FileUtils; 4 | import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer; 5 | import org.apache.lucene.document.Document; 6 | import org.apache.lucene.document.Field; 7 | import org.apache.lucene.document.StringField; 8 | import org.apache.lucene.document.TextField; 9 | import org.apache.lucene.index.IndexWriter; 10 | import org.apache.lucene.index.IndexWriterConfig; 11 | import org.apache.lucene.index.IndexableField; 12 | import org.apache.lucene.store.Directory; 13 | import org.apache.lucene.store.FSDirectory; 14 | import org.yyh.constant.LuceneConstants; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.nio.charset.Charset; 19 | import java.nio.file.Paths; 20 | import java.util.concurrent.atomic.AtomicInteger; 21 | 22 | /** 23 | * @author: lhy 24 | * @description: 25 | * @date: 2019-03-05 11:13 26 | **/ 27 | public class Indexer { 28 | private IndexWriter indexWriter; 29 | private static AtomicInteger count = new AtomicInteger(0); 30 | 31 | public Indexer(String indexDirectoryPath) throws IOException{ 32 | Directory indexDirectory = FSDirectory.open(Paths.get(indexDirectoryPath)); 33 | IndexWriterConfig config = new IndexWriterConfig(new SmartChineseAnalyzer()); 34 | indexWriter = new IndexWriter(indexDirectory,config ); 35 | } 36 | 37 | public void close() throws IOException { 38 | indexWriter.close(); 39 | } 40 | 41 | private Document getFileDocument(File file) throws IOException{ 42 | Document document = new Document(); 43 | IndexableField id = new StringField(LuceneConstants.ID,String.valueOf(count.getAndIncrement()),Field.Store.YES); 44 | IndexableField content = new TextField(LuceneConstants.CONTENTS, FileUtils.readFileToString(file, Charset.forName("GBK")),Field.Store.YES); 45 | IndexableField filename = new StringField(LuceneConstants.FILE_NAME,file.getName(),Field.Store.YES); 46 | IndexableField filepath = new StringField(LuceneConstants.FILE_PATH,file.getPath(),Field.Store.YES); 47 | document.add(id); 48 | document.add(content); 49 | document.add(filename); 50 | document.add(filepath); 51 | return document; 52 | } 53 | 54 | public void createIndex(File file) throws IOException { 55 | if (!file.exists() || !file.getName().endsWith(".txt")){ 56 | return; 57 | } 58 | Document document = getFileDocument(file); 59 | indexWriter.addDocument(document); 60 | } 61 | 62 | public void createIndex(String filePath) throws IOException{ 63 | File file = new File(filePath); 64 | if (!file.exists()){ 65 | System.out.println("file path is not right, file : " + file.getAbsolutePath()); 66 | return; 67 | } 68 | if (file.isDirectory()){ 69 | File[] files = file.listFiles(filename -> !filename.getName().contains("index")); 70 | if ((files != null ? files.length : 0) == 0){ 71 | System.out.println("director is empty, directory : " + filePath); 72 | return; 73 | } 74 | for (File file1 : files){ 75 | createIndex(file1.getAbsolutePath()); 76 | } 77 | } 78 | createIndex(file); 79 | } 80 | 81 | 82 | 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /lucene_demo/src/main/java/org/yyh/lucence/Searcher.java: -------------------------------------------------------------------------------- 1 | package org.yyh.lucence; 2 | 3 | import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer; 4 | import org.apache.lucene.document.Document; 5 | import org.apache.lucene.index.DirectoryReader; 6 | import org.apache.lucene.index.IndexReader; 7 | import org.apache.lucene.index.Term; 8 | import org.apache.lucene.queryparser.classic.ParseException; 9 | import org.apache.lucene.queryparser.classic.QueryParser; 10 | import org.apache.lucene.search.*; 11 | import org.apache.lucene.store.Directory; 12 | import org.apache.lucene.store.FSDirectory; 13 | import org.yyh.constant.LuceneConstants; 14 | import org.yyh.model.ItemModel; 15 | import org.yyh.model.ResultModel; 16 | 17 | import java.io.IOException; 18 | import java.nio.file.Paths; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | /** 23 | * @author: lhy 24 | * @description: 25 | * @date: 2019-03-06 11:42 26 | **/ 27 | public class Searcher { 28 | private IndexSearcher indexSearcher; 29 | 30 | public Searcher(String path) throws IOException { 31 | Directory d = FSDirectory.open(Paths.get(path)); 32 | // 通过indexSearcher去检索索引目录 33 | IndexReader indexReader = DirectoryReader.open(d); 34 | indexSearcher = new IndexSearcher(indexReader); 35 | } 36 | 37 | private ResultModel search(Query query) throws IOException { 38 | TopDocs topDocs = indexSearcher.search(query,LuceneConstants.MAX_SEARCH); 39 | 40 | ResultModel resultModel = new ResultModel(); 41 | resultModel.setMaxScore(topDocs.getMaxScore()); 42 | resultModel.setTotalHits(topDocs.totalHits); 43 | 44 | List resultModelList = new ArrayList<>(); 45 | resultModel.setItemModels(resultModelList); 46 | 47 | ScoreDoc[] scoreDocs = topDocs.scoreDocs; 48 | for (ScoreDoc scoreDoc : scoreDocs){ 49 | ItemModel itemModel = new ItemModel(); 50 | itemModel.setScore(scoreDoc.score); 51 | int doc = scoreDoc.doc; 52 | Document document = indexSearcher.doc(doc); 53 | itemModel.setId(Integer.valueOf(document.get(LuceneConstants.ID))); 54 | itemModel.setFilename(document.get(LuceneConstants.FILE_NAME)); 55 | itemModel.setFilepath(document.get(LuceneConstants.FILE_PATH)); 56 | itemModel.setContent(document.get(LuceneConstants.CONTENTS)); 57 | resultModelList.add(itemModel); 58 | } 59 | return resultModel; 60 | } 61 | 62 | 63 | public ResultModel byId(Integer id) throws IOException { 64 | if (id == null ){ 65 | return null; 66 | } 67 | Query query = new TermQuery(new Term(LuceneConstants.ID,String.valueOf(id))); 68 | return search(query); 69 | } 70 | 71 | public ResultModel byFileName(String name) throws IOException { 72 | if ("".equals(name) || null == name){ 73 | return null; 74 | } 75 | Query query = new TermQuery(new Term(LuceneConstants.FILE_NAME,name)); 76 | return search(query); 77 | } 78 | 79 | public ResultModel bywWord(String word) throws IOException, ParseException { 80 | if ("".equals(word) || null == word){ 81 | return null; 82 | } 83 | QueryParser queryParser = new QueryParser(LuceneConstants.CONTENTS,new SmartChineseAnalyzer()); 84 | Query query = queryParser.parse(word); 85 | return search(query); 86 | } 87 | 88 | 89 | } 90 | -------------------------------------------------------------------------------- /lucene_demo/src/main/java/org/yyh/model/ItemModel.java: -------------------------------------------------------------------------------- 1 | package org.yyh.model; 2 | 3 | /** 4 | * @author: lhy 5 | * @description: 6 | * @date: 2019-03-06 11:55 7 | **/ 8 | public class ItemModel { 9 | private Integer id; 10 | private String filename; 11 | private String filepath; 12 | private String content; 13 | private Float score; 14 | 15 | 16 | public Integer getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Integer id) { 21 | this.id = id; 22 | } 23 | 24 | public String getFilename() { 25 | return filename; 26 | } 27 | 28 | public void setFilename(String filename) { 29 | this.filename = filename; 30 | } 31 | 32 | public String getContent() { 33 | return content; 34 | } 35 | 36 | public void setContent(String content) { 37 | this.content = content; 38 | } 39 | 40 | public Float getScore() { 41 | return score; 42 | } 43 | 44 | public void setScore(Float score) { 45 | this.score = score; 46 | } 47 | 48 | public String getFilepath() { 49 | return filepath; 50 | } 51 | 52 | public void setFilepath(String filepath) { 53 | this.filepath = filepath; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lucene_demo/src/main/java/org/yyh/model/ResultModel.java: -------------------------------------------------------------------------------- 1 | package org.yyh.model; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author: lhy 7 | * @description: 8 | * @date: 2019-03-06 14:18 9 | **/ 10 | public class ResultModel { 11 | private Long totalHits; 12 | private Float maxScore; 13 | private List itemModels; 14 | 15 | public Long getTotalHits() { 16 | return totalHits; 17 | } 18 | 19 | public void setTotalHits(Long totalHits) { 20 | this.totalHits = totalHits; 21 | } 22 | 23 | public Float getMaxScore() { 24 | return maxScore; 25 | } 26 | 27 | public void setMaxScore(Float maxScore) { 28 | this.maxScore = maxScore; 29 | } 30 | 31 | public List getItemModels() { 32 | return itemModels; 33 | } 34 | 35 | public void setItemModels(List itemModels) { 36 | this.itemModels = itemModels; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /lucene_demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NapWells/java_framework_learn/288f7a388ab763498313c9416277f6b82c5abb3e/lucene_demo/src/main/resources/application.properties -------------------------------------------------------------------------------- /lucene_demo/src/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /lucene_demo/src/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /lucene_demo/src/test/java/src/LuceneTest.java: -------------------------------------------------------------------------------- 1 | package src; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import org.apache.lucene.queryparser.classic.ParseException; 5 | import org.junit.Test; 6 | import org.yyh.lucence.Indexer; 7 | import org.yyh.lucence.Searcher; 8 | import org.yyh.model.ResultModel; 9 | 10 | import java.io.IOException; 11 | 12 | /** 13 | * @author: lhy 14 | * @description: 15 | * @date: 2019-03-06 14:51 16 | **/ 17 | public class LuceneTest { 18 | private static final String indexPath = "C:\\Users\\42515\\Desktop\\lucene-test\\index"; 19 | private static final String dataPath = "C:\\Users\\42515\\Desktop\\lucene-test"; 20 | 21 | 22 | @Test 23 | public void testCreateIndex() throws IOException { 24 | Indexer indexer = new Indexer(indexPath); 25 | indexer.createIndex(dataPath); 26 | indexer.close(); 27 | } 28 | 29 | @Test 30 | public void testSearch() throws IOException, ParseException { 31 | Searcher searcher = new Searcher(indexPath); 32 | ResultModel resultModel = searcher.bywWord("Java"); 33 | System.out.println(JSONObject.toJSONString(resultModel)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /quartzkearn/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | quartzkearn 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.quartz-scheduler 14 | quartz 15 | 2.2.1 16 | 17 | 18 | 19 | 20 | 21 | 22 | org.apache.maven.plugins 23 | maven-compiler-plugin 24 | 3.0 25 | 26 | 1.8 27 | 1.8 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-maven-plugin 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /quartzkearn/src/main/java/com/yy/job/MyJob.java: -------------------------------------------------------------------------------- 1 | package com.yy.job; 2 | 3 | import org.quartz.*; 4 | 5 | public class MyJob implements Job{ 6 | public void execute(JobExecutionContext context) throws JobExecutionException { 7 | JobDetail jobDetail = context.getJobDetail(); 8 | Trigger trigger = context.getTrigger(); 9 | System.out.println(jobDetail.getJobDataMap().get("name")); 10 | System.out.println(trigger.getJobDataMap().get("hi")); 11 | System.out.println("hello world"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /quartzkearn/src/main/java/com/yy/test/QuartzSimpleDemo.java: -------------------------------------------------------------------------------- 1 | package com.yy.test; 2 | 3 | import com.yy.job.MyJob; 4 | import org.quartz.*; 5 | import org.quartz.impl.StdSchedulerFactory; 6 | 7 | public class QuartzSimpleDemo { 8 | public static void main(String[] args) throws SchedulerException, InterruptedException { 9 | //通过任务调度器工厂创建任务调度器 10 | SchedulerFactory schedulerFactory = new StdSchedulerFactory(); 11 | Scheduler scheduler = schedulerFactory.getScheduler(); 12 | 13 | //创建任务调度模型 14 | ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() 15 | .withIntervalInSeconds(5)//执行时间间隔是5秒 16 | .repeatForever();//一直执行,可以被调度器中断 17 | 18 | //定义触发器,定义触发条件 19 | Trigger trigger = TriggerBuilder.newTrigger() 20 | .withIdentity("trigger1","myGroup1")//设置触发器的id和group 21 | .withSchedule(scheduleBuilder)//设置使用的调度模型 22 | .usingJobData("hi","asasafafsfs") 23 | .startNow()//一加入scheduler就执行 24 | 25 | .build(); 26 | 27 | //定义任务,做任务的是MyJob.execute()方法 28 | JobDetail jobDetail = JobBuilder.newJob(MyJob.class) 29 | .withIdentity("job1","myGroup2")//设置任务的id和group 30 | .usingJobData("name","test my job")//任务中传递参数,底层就是个map 31 | .build(); 32 | 33 | //将任务加入调度器 34 | scheduler.scheduleJob(jobDetail,trigger); 35 | //调度器调度任务 36 | scheduler.start(); 37 | 38 | 39 | Thread.sleep(10000); 40 | //调度器关闭,true表示等待任务全部完成,false反之 41 | scheduler.shutdown(true); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /springkafka/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | spring-kafka 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.5.2.RELEASE 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.kafka 29 | spring-kafka 30 | 2.1.0.RELEASE 31 | 32 | 33 | 34 | 35 | org.springframework.kafka 36 | spring-kafka-test 37 | 1.0.2.RELEASE 38 | test 39 | 40 | 41 | 42 | 43 | 44 | 45 | junit 46 | junit 47 | 4.12 48 | 49 | 50 | 51 | org.projectlombok 52 | lombok 53 | 1.16.10 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-compiler-plugin 63 | 3.0 64 | 65 | 1.8 66 | 1.8 67 | 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-maven-plugin 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /springkafka/src/main/java/com/yyh/Application.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | 8 | 9 | @SpringBootApplication 10 | public class Application{ 11 | 12 | public static Logger logger = LoggerFactory.getLogger(Application.class); 13 | 14 | public static void main(String[] args) throws Exception { 15 | SpringApplication.run(Application.class, args); 16 | } 17 | 18 | 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /springkafka/src/main/java/com/yyh/config/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.yyh.service.MyMessageListener; 4 | import org.apache.kafka.clients.consumer.ConsumerConfig; 5 | import org.apache.kafka.clients.producer.ProducerConfig; 6 | import org.apache.kafka.common.serialization.StringDeserializer; 7 | import org.apache.kafka.common.serialization.StringSerializer; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.kafka.annotation.EnableKafka; 11 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 12 | import org.springframework.kafka.core.*; 13 | import org.springframework.kafka.listener.KafkaMessageListenerContainer; 14 | import org.springframework.kafka.listener.config.ContainerProperties; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | import java.util.regex.Pattern; 19 | 20 | 21 | @Configuration 22 | @EnableKafka 23 | public class KafkaConfig { 24 | 25 | /* --------------producer configuration-----------------**/ 26 | @Bean 27 | public Map producerConfigs() { 28 | Map props = new HashMap<>(); 29 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); 30 | props.put(ProducerConfig.RETRIES_CONFIG, 0); 31 | props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); 32 | props.put(ProducerConfig.LINGER_MS_CONFIG, 1); 33 | props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); 34 | props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 35 | props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 36 | return props; 37 | } 38 | 39 | @Bean 40 | public ProducerFactory producerFactory() { 41 | return new DefaultKafkaProducerFactory<>(producerConfigs()); 42 | } 43 | 44 | /* --------------consumer configuration-----------------**/ 45 | @Bean 46 | public Map consumerConfigs() { 47 | Map props = new HashMap<>(); 48 | props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); 49 | props.put(ConsumerConfig.GROUP_ID_CONFIG, "0"); 50 | props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); 51 | props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 100); 52 | props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); 53 | props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 54 | props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 55 | return props; 56 | } 57 | 58 | @Bean 59 | ConcurrentKafkaListenerContainerFactory 60 | kafkaListenerContainerFactory() { 61 | ConcurrentKafkaListenerContainerFactory factory = 62 | new ConcurrentKafkaListenerContainerFactory<>(); 63 | factory.setConsumerFactory(consumerFactory()); 64 | return factory; 65 | } 66 | 67 | @Bean 68 | public ConsumerFactory consumerFactory() { 69 | return new DefaultKafkaConsumerFactory<>(consumerConfigs()); 70 | } 71 | 72 | 73 | //实际执行消息消费的类 74 | @Bean 75 | public MyMessageListener myMessageListener(){ 76 | return new MyMessageListener(); 77 | } 78 | 79 | //消费者容器配置信息 80 | @Bean 81 | public ContainerProperties containerProperties(){ 82 | Pattern topicPattern = Pattern.compile(".*[tT]opic.*"); 83 | ContainerProperties containerProperties = new ContainerProperties(topicPattern); 84 | containerProperties.setMessageListener(myMessageListener()); 85 | return containerProperties; 86 | } 87 | 88 | @Bean 89 | public KafkaMessageListenerContainer kafkaMessageListenerContainer(){ 90 | return new KafkaMessageListenerContainer<>(consumerFactory(),containerProperties()); 91 | } 92 | 93 | 94 | /* --------------kafka template configuration-----------------**/ 95 | @Bean 96 | public KafkaTemplate kafkaTemplate() { 97 | KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory()); 98 | kafkaTemplate.setDefaultTopic("defaultTopic"); 99 | return kafkaTemplate; 100 | } 101 | 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /springkafka/src/main/java/com/yyh/controller/KafkaController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | import org.springframework.kafka.support.SendResult; 8 | import org.springframework.util.concurrent.ListenableFuture; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | @RestController 12 | public class KafkaController { 13 | private final static Logger logger = LoggerFactory.getLogger(KafkaController.class); 14 | 15 | 16 | @Autowired 17 | private KafkaTemplate kafkaTemplate; 18 | 19 | 20 | @RequestMapping(value = "/{topic}/send",method = RequestMethod.GET) 21 | public void sendMeessage( 22 | @RequestParam(value = "message",defaultValue = "hello world") String message, 23 | @PathVariable final String topic) { 24 | logger.info("start sned message to {}",topic); 25 | ListenableFuture> listenableFuture = kafkaTemplate.send(topic,message); 26 | 27 | listenableFuture.addCallback( 28 | result -> logger.info("send message to {} success",topic), 29 | ex -> logger.info("send message to {} failure,error message:{}",topic,ex.getMessage())); 30 | } 31 | 32 | @RequestMapping(value = "/default/send",method = RequestMethod.GET) 33 | public void sendMeessagedefault() { 34 | logger.info("start send message to default topic"); 35 | kafkaTemplate.sendDefault("你好,世界"); 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /springkafka/src/main/java/com/yyh/service/MyMessageListener.java: -------------------------------------------------------------------------------- 1 | package com.yyh.service; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerRecord; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.kafka.listener.MessageListener; 7 | 8 | public class MyMessageListener implements MessageListener { 9 | public final static Logger logger = LoggerFactory.getLogger(MyMessageListener.class); 10 | 11 | @Override 12 | public void onMessage(ConsumerRecord data) { 13 | String topic = data.topic(); 14 | logger.info("-------------recieve message from {} topic-------------", topic); 15 | logger.info("partition:{}", String.valueOf(data.partition())); 16 | logger.info("offset:{}", String.valueOf(data.offset())); 17 | logger.info("get message from {} topic : {}", topic, data.value()); 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /springkafka2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | con.yyh 8 | springkafka2 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-dependencies 17 | 2.0.0.RELEASE 18 | pom 19 | import 20 | 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | org.springframework.kafka 32 | spring-kafka 33 | 2.1.4.RELEASE 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-compiler-plugin 44 | 3.0 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /springkafka2/src/main/java/com/yyh/Application.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | 8 | 9 | @SpringBootApplication 10 | public class Application{ 11 | 12 | public static Logger logger = LoggerFactory.getLogger(Application.class); 13 | 14 | 15 | 16 | public static void main(String[] args) throws Exception { 17 | 18 | SpringApplication.run(Application.class, args); 19 | 20 | } 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /springkafka2/src/main/java/com/yyh/config/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.yyh.listener.MyListener; 4 | import org.apache.kafka.clients.consumer.ConsumerConfig; 5 | import org.apache.kafka.clients.producer.ProducerConfig; 6 | import org.apache.kafka.common.serialization.StringDeserializer; 7 | import org.apache.kafka.common.serialization.StringSerializer; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.kafka.annotation.EnableKafka; 11 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 12 | import org.springframework.kafka.config.KafkaListenerContainerFactory; 13 | import org.springframework.kafka.core.*; 14 | import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | @Configuration 20 | @EnableKafka 21 | public class KafkaConfig { 22 | 23 | /* --------------producer configuration-----------------**/ 24 | @Bean 25 | public Map producerConfigs() { 26 | Map props = new HashMap<>(); 27 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093"); 28 | props.put(ProducerConfig.RETRIES_CONFIG, 0); 29 | props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); 30 | props.put(ProducerConfig.LINGER_MS_CONFIG, 1); 31 | props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); 32 | props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 33 | props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 34 | return props; 35 | } 36 | 37 | @Bean 38 | public ProducerFactory producerFactory() { 39 | return new DefaultKafkaProducerFactory<>(producerConfigs()); 40 | } 41 | 42 | /* --------------consumer configuration-----------------**/ 43 | @Bean 44 | public Map consumerConfigs() { 45 | Map props = new HashMap<>(); 46 | props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093"); 47 | props.put(ConsumerConfig.GROUP_ID_CONFIG, "0"); 48 | props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); 49 | props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 100); 50 | props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); 51 | props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 52 | props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 53 | return props; 54 | } 55 | 56 | 57 | @Bean 58 | ConcurrentKafkaListenerContainerFactory 59 | kafkaListenerContainerFactory() { 60 | ConcurrentKafkaListenerContainerFactory factory = 61 | new ConcurrentKafkaListenerContainerFactory<>(); 62 | factory.setConsumerFactory(consumerFactory()); 63 | return factory; 64 | } 65 | 66 | @Bean 67 | public ConsumerFactory consumerFactory() { 68 | return new DefaultKafkaConsumerFactory<>(consumerConfigs()); 69 | } 70 | 71 | @Bean 72 | public MyListener myListener() { 73 | return new MyListener(); 74 | } 75 | 76 | 77 | /* --------------kafka template configuration-----------------**/ 78 | @Bean 79 | public KafkaTemplate kafkaTemplate() { 80 | KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory()); 81 | return kafkaTemplate; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /springkafka2/src/main/java/com/yyh/config/TopicConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import org.apache.kafka.clients.admin.AdminClientConfig; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.kafka.annotation.EnableKafka; 8 | import org.springframework.kafka.core.KafkaAdmin; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | @Configuration 14 | @EnableKafka 15 | public class TopicConfig { 16 | @Bean 17 | public KafkaAdmin kafkaAdmin() { 18 | Map configs = new HashMap<>(); 19 | configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093"); 20 | return new KafkaAdmin(configs); 21 | } 22 | 23 | @Bean 24 | public NewTopic foo() { 25 | //第一个是参数是topic名字,第二个参数是分区个数,第三个是topic的复制因子个数 26 | //当broker个数为1个时会创建topic失败, 27 | //提示:replication factor: 2 larger than available brokers: 1 28 | //只有在集群中才能使用kafka的备份功能 29 | return new NewTopic("foo", 10, (short) 2); 30 | } 31 | 32 | @Bean 33 | public NewTopic bar() { 34 | return new NewTopic("bar", 10, (short) 2); 35 | } 36 | 37 | @Bean 38 | public NewTopic topic1(){ 39 | return new NewTopic("topic1", 10, (short) 2); 40 | } 41 | 42 | @Bean 43 | public NewTopic topic2(){ 44 | return new NewTopic("topic2", 10, (short) 4); 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /springkafka2/src/main/java/com/yyh/controller/KafkaController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | @RestController 10 | public class KafkaController { 11 | private final static Logger logger = LoggerFactory.getLogger(KafkaController.class); 12 | 13 | @Autowired 14 | private KafkaTemplate kafkaTemplate; 15 | 16 | @RequestMapping(value = "/{topic}/send",method = RequestMethod.GET) 17 | public void sendMeessageTotopic1(@PathVariable String topic,@RequestParam(value = "partition",defaultValue = "0") int partition) { 18 | logger.info("start send message to {}",topic); 19 | kafkaTemplate.send(topic,partition,"你","好"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /springkafka2/src/main/java/com/yyh/listener/MyListener.java: -------------------------------------------------------------------------------- 1 | package com.yyh.listener; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerRecord; 4 | import org.springframework.kafka.annotation.KafkaListener; 5 | import org.springframework.kafka.annotation.PartitionOffset; 6 | import org.springframework.kafka.annotation.TopicPartition; 7 | 8 | 9 | public class MyListener { 10 | @KafkaListener(id = "myContainer1",//id是消费者监听容器 11 | topicPartitions =//配置topic和分区:监听两个topic,分别为topic1、topic2,topic1只接收分区0,3的消息, 12 | //topic2接收分区0和分区1的消息,但是分区1的消费者初始位置为5 13 | { @TopicPartition(topic = "topic1", partitions = { "0", "3" }), 14 | @TopicPartition(topic = "topic2", partitions = "0", 15 | partitionOffsets = @PartitionOffset(partition = "1", initialOffset = "4")) 16 | }) 17 | public void listen(ConsumerRecord, ?> record) { 18 | System.out.println("topic" + record.topic()); 19 | System.out.println("key:" + record.key()); 20 | System.out.println("value:"+record.value()); 21 | } 22 | 23 | @KafkaListener(id = "myContainer2",topics = {"foo","bar"}) 24 | public void listen2(ConsumerRecord, ?> record){ 25 | System.out.println("topic:" + record.topic()); 26 | System.out.println("key:" + record.key()); 27 | System.out.println("value:"+record.value()); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /springkafka2/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /springmybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | springmybatis 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-dependencies 17 | 2.0.0.RELEASE 18 | pom 19 | import 20 | 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | 32 | org.mybatis.spring.boot 33 | mybatis-spring-boot-starter 34 | 1.3.2 35 | 36 | 37 | 38 | 39 | com.mchange 40 | c3p0 41 | 0.9.5.2 42 | 43 | 44 | 45 | 46 | mysql 47 | mysql-connector-java 48 | 8.0.9-rc 49 | 50 | 51 | 52 | org.projectlombok 53 | lombok 54 | 1.16.10 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-compiler-plugin 65 | 3.0 66 | 67 | 1.8 68 | 1.8 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-maven-plugin 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/AppDemoMain.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class AppDemoMain{ 8 | 9 | public static void main(String[] args) throws Exception { 10 | 11 | SpringApplication.run(AppDemoMain.class, args); 12 | 13 | 14 | } 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/config/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.mchange.v2.c3p0.ComboPooledDataSource; 4 | import lombok.Data; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.PropertySource; 9 | 10 | @Data 11 | @Configuration 12 | @PropertySource("classpath:datasource.properties") 13 | @ConfigurationProperties(prefix = "connection") 14 | public class DataSourceConfig { 15 | private String username; 16 | private String password; 17 | private String url; 18 | private String driverClassName; 19 | private int acquireIncrement; 20 | private int acquireRetryAttempts; 21 | private int acquireRetryDelay; 22 | private int maxPoolSize; 23 | private int minPoolSize; 24 | private int initialPoolSize; 25 | 26 | @Bean 27 | public ComboPooledDataSource getDataSource() throws Exception { 28 | ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); 29 | comboPooledDataSource.setUser(username); 30 | comboPooledDataSource.setPassword(password); 31 | comboPooledDataSource.setJdbcUrl(url); 32 | comboPooledDataSource.setDriverClass(driverClassName); 33 | comboPooledDataSource.setMinPoolSize(minPoolSize); 34 | comboPooledDataSource.setMaxPoolSize(maxPoolSize); 35 | comboPooledDataSource.setInitialPoolSize(initialPoolSize); 36 | comboPooledDataSource.setAcquireIncrement(acquireIncrement); 37 | comboPooledDataSource.setAcquireRetryDelay(acquireRetryDelay); 38 | comboPooledDataSource.setAcquireRetryAttempts(acquireRetryAttempts); 39 | return comboPooledDataSource; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/config/MybatisConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.mchange.v2.c3p0.ComboPooledDataSource; 4 | import lombok.Data; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 10 | import org.springframework.boot.context.properties.ConfigurationProperties; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.PropertySource; 14 | 15 | @Data 16 | @EnableAutoConfiguration 17 | public class MybatisConfig { 18 | @Autowired 19 | private ComboPooledDataSource dataSource; 20 | 21 | @Bean 22 | public SqlSessionFactory getSqlSessionFactory(){ 23 | try { 24 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 25 | sqlSessionFactoryBean.setDataSource(dataSource); 26 | return sqlSessionFactoryBean.getObject(); 27 | }catch (Exception e){ 28 | e.printStackTrace(); 29 | return null; 30 | } 31 | } 32 | 33 | @Bean 34 | public SqlSessionTemplate getSqlSessionTemplate() { 35 | return new SqlSessionTemplate(getSqlSessionFactory()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/controller/MyController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import com.yyh.dao.CourseDao; 4 | import com.yyh.dto.Course; 5 | import com.yyh.dto.Student; 6 | import com.yyh.dao.StudentDao; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | public class MyController { 15 | @Autowired 16 | private StudentDao studentDao; 17 | @Autowired 18 | private CourseDao courseDao; 19 | 20 | @RequestMapping("/query/student/{id}") 21 | public Student queryStudentById(@PathVariable int id){ 22 | return studentDao.findStudentById(id); 23 | } 24 | 25 | @RequestMapping("/query/student/all") 26 | public List queryAllStudent(){ 27 | return studentDao.findAllStudent(); 28 | } 29 | 30 | @RequestMapping(value = "/add/course",method= RequestMethod.POST) 31 | public int addCurse(@RequestBody Course course){ 32 | return courseDao.insertCourse(course); 33 | } 34 | 35 | @RequestMapping(value = "/query/course") 36 | public List queryCourse(@RequestParam int studentId){ 37 | return courseDao.selectCoursesByStudentId(studentId); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/dao/CourseDao.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dao; 2 | 3 | import com.yyh.dto.Course; 4 | import org.apache.ibatis.annotations.Insert; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.Select; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.List; 11 | 12 | @Mapper 13 | @Component 14 | public interface CourseDao { 15 | @Insert("INSERT INTO course (`name`,`teacher`) VALUES (#{name},#{teacher})") 16 | int insertCourse(Course course); 17 | 18 | 19 | @Select("SELECT * FROM course WHERE id IN (SELECT course_id FROM score WHERE student_id = #{studentId})") 20 | List selectCoursesByStudentId(@Param("studentId") int studentId); 21 | } 22 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/dao/StudentDao.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dao; 2 | 3 | ; 4 | import com.yyh.dto.Student; 5 | import org.apache.ibatis.annotations.*; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.List; 9 | 10 | @Mapper 11 | @Component 12 | public interface StudentDao { 13 | //注意#和$的区别,mybatis 在对sql语句进行预编译之前,会对 sql 进行动态解析。 14 | // #{}预编译之后是一个占位符? 15 | // ${}预编译以后直接是替换作用 16 | 17 | @Select({"SELECT * FROM student WHERE id = #{id}"}) 18 | @Results(id ="id", 19 | value = {@Result(property = "courseList", column = "id", many = @Many(select = "com.yyh.dao.CourseDao.selectCoursesByStudentId")), 20 | @Result(property = "id",column = "id") 21 | } 22 | ) 23 | Student findStudentById(int id); 24 | 25 | @Select("SELECT * FROM student") 26 | List findAllStudent(); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/dto/Course.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class Course { 9 | private int id; 10 | private String name; 11 | private String teacher; 12 | private List studentList; 13 | } 14 | -------------------------------------------------------------------------------- /springmybatis/src/main/java/com/yyh/dto/Student.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class Student { 9 | private int id; 10 | private String code; 11 | private String name; 12 | private String age; 13 | private String phoneNo; 14 | private List courseList; 15 | } 16 | -------------------------------------------------------------------------------- /springmybatis/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.com.yyh=debug 2 | 3 | #为空的属性在转换时忽略掉 4 | spring.jackson.default-property-inclusion=non_empty 5 | 6 | #将数据库中下划线命名风格自动转换为驼峰式命名风格 7 | mybatis.configuration.map-underscore-to-camel-case=true 8 | mybatis.configuration.default-fetch-size=100 9 | mybatis.configuration.default-statement-timeout=30 10 | mybatis.configuration.auto-mapping-unknown-column-behavior=WARNING -------------------------------------------------------------------------------- /springmybatis/src/main/resources/datasource.properties: -------------------------------------------------------------------------------- 1 | #=============data source============= 2 | connection.username=root 3 | connection.password=123456 4 | connection.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8 5 | connection.driverClassName =com.mysql.cj.jdbc.Driver 6 | #初始连接数 default=3 7 | connection.initialPoolSize=5 8 | #连接池获取增量 default=3 9 | connection.acquireIncrement=2 10 | #获取连接失败重试次数 default=30 11 | connection.acquireRetryAttempts=10 12 | #获取连接延迟时间 单位毫秒 default=1000 13 | connection.acquireRetryDelay=500 14 | #连接关闭时不自动提交 default=false ,需要手动commit 15 | connection.autoCommitOnClose=false 16 | #连接池最大连接数 default=15 17 | connection.maxPoolSize=30 18 | #连接池最小连接数 default=3 19 | connection.minPoolSize=5 20 | #ps:还有更多,请查看官网文档:http://www.mchange.com/projects/c3p0/#configuration 21 | #默认配置看com.mchange.v2.c3p0.impl.C3P0Defaults这个类 22 | -------------------------------------------------------------------------------- /springmybatis/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | %d{MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | /Users/lhy/java-study/java_framework_learn/springmybatis/log/warn.%d{yyyy-MM-dd}.log 21 | 22 | 99 23 | true 24 | 25 | 26 | 27 | 28 | INFO 29 | ACCEPT 30 | DENY 31 | 32 | 33 | %d{HH:mm:ss.SSS} %-5level %logger{35} - %msg%n 34 | 35 | 36 | 37 | 38 | 39 | 40 | /Users/lhy/java-study/java_framework_learn/springmybatis/log/error.%d{yyyy-MM-dd}.log 41 | 99 42 | true 43 | 44 | 45 | 46 | 47 | 48 | ERROR 49 | 50 | 51 | %d{HH:mm:ss.SSS} %-5level %logger{35} - %msg%n 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | springsecuritydemo 7 | com.yyh 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | demo 13 | 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-freemarker 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-security 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-jdbc 49 | 50 | 51 | 52 | org.mybatis.spring.boot 53 | mybatis-spring-boot-starter 54 | 1.3.2 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-test 60 | test 61 | 62 | 63 | 64 | 65 | com.alibaba 66 | druid 67 | 1.1.9 68 | 69 | 70 | mysql 71 | mysql-connector-java 72 | 8.0.9-rc 73 | 74 | 75 | 76 | com.alibaba 77 | fastjson 78 | 1.2.47 79 | 80 | 81 | 82 | 83 | org.projectlombok 84 | lombok 85 | 1.16.10 86 | 87 | 88 | 89 | 90 | org.slf4j 91 | log4j-over-slf4j 92 | 93 | 94 | 95 | org.webjars 96 | bootstrap 97 | 3.3.7 98 | 99 | 100 | 101 | org.webjars 102 | jquery 103 | 3.1.0 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | org.apache.maven.plugins 116 | maven-compiler-plugin 117 | 3.0 118 | 119 | UTF-8 120 | 1.8 121 | 1.8 122 | 123 | 124 | 125 | 126 | org.springframework.boot 127 | spring-boot-maven-plugin 128 | 129 | true 130 | com.yyh.CrawlerApp 131 | 132 | 133 | 134 | 135 | repackage 136 | 137 | 138 | 139 | 140 | 141 | 142 | org.jacoco 143 | jacoco-maven-plugin 144 | 145 | 146 | jacoco-initialize 147 | 148 | prepare-agent 149 | 150 | 151 | 152 | jacoco-site 153 | verify 154 | 155 | report 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/MainApp.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.context.ApplicationContext; 8 | 9 | /** 10 | * @author lhy 11 | * @Date 2018/10/19 17:18 12 | * @JDK 1.7 13 | * @Description TODO 14 | */ 15 | @SpringBootApplication 16 | @MapperScan("com.yyh.mapper") 17 | @Slf4j 18 | public class MainApp { 19 | public static void main(String[] args) { 20 | ApplicationContext ctx = SpringApplication.run(MainApp.class,args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/config/DataScourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.jdbc.core.JdbcTemplate; 12 | 13 | import javax.sql.DataSource; 14 | import java.sql.SQLException; 15 | 16 | /** 17 | * @author lhy 18 | * @Date 2018/10/19 14:39 19 | * @JDK 1.7 20 | * @Description TODO 21 | */ 22 | @Slf4j 23 | @Configuration 24 | public class DataScourceConfig { 25 | @Value("${spring.datasource.url}") 26 | private String dbUrl; 27 | 28 | @Value("${spring.datasource.username}") 29 | private String username; 30 | 31 | @Value("${spring.datasource.password}") 32 | private String password; 33 | 34 | @Value("${spring.datasource.driver-class-name}") 35 | private String driverClassName; 36 | 37 | @Value("${spring.datasource.initialSize}") 38 | private int initialSize; 39 | 40 | @Value("${spring.datasource.minIdle}") 41 | private int minIdle; 42 | 43 | @Value("${spring.datasource.maxActive}") 44 | private int maxActive; 45 | 46 | @Value("${spring.datasource.maxWait}") 47 | private int maxWait; 48 | 49 | @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") 50 | private int timeBetweenEvictionRunsMillis; 51 | 52 | @Value("${spring.datasource.minEvictableIdleTimeMillis}") 53 | private int minEvictableIdleTimeMillis; 54 | 55 | @Value("${spring.datasource.validationQuery}") 56 | private String validationQuery; 57 | 58 | @Value("${spring.datasource.testWhileIdle}") 59 | private boolean testWhileIdle; 60 | 61 | @Value("${spring.datasource.testOnBorrow}") 62 | private boolean testOnBorrow; 63 | 64 | @Value("${spring.datasource.testOnReturn}") 65 | private boolean testOnReturn; 66 | 67 | @Value("${spring.datasource.poolPreparedStatements}") 68 | private boolean poolPreparedStatements; 69 | 70 | @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") 71 | private int maxPoolPreparedStatementPerConnectionSize; 72 | 73 | @Value("${spring.datasource.filters}") 74 | private String filters; 75 | 76 | @Value("{spring.datasource.connectionProperties}") 77 | private String connectionProperties; 78 | 79 | 80 | @Bean 81 | public DataSource dataSource(){ 82 | DruidDataSource datasource = new DruidDataSource(); 83 | 84 | datasource.setUrl(this.dbUrl); 85 | datasource.setUsername(username); 86 | datasource.setPassword(password); 87 | datasource.setDriverClassName(driverClassName); 88 | 89 | //configuration 90 | datasource.setInitialSize(initialSize); 91 | datasource.setMinIdle(minIdle); 92 | datasource.setMaxActive(maxActive); 93 | datasource.setMaxWait(maxWait); 94 | datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 95 | datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 96 | datasource.setValidationQuery(validationQuery); 97 | datasource.setTestWhileIdle(testWhileIdle); 98 | datasource.setTestOnBorrow(testOnBorrow); 99 | datasource.setTestOnReturn(testOnReturn); 100 | datasource.setPoolPreparedStatements(poolPreparedStatements); 101 | datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); 102 | try { 103 | datasource.setFilters(filters); 104 | } catch (SQLException e) { 105 | log.error("druid configuration Exception", e); 106 | e.printStackTrace(); 107 | } 108 | 109 | datasource.setConnectionProperties(connectionProperties); 110 | 111 | return datasource; 112 | } 113 | 114 | @Bean 115 | public JdbcTemplate jdbcTemplate() { 116 | return new JdbcTemplate(dataSource()); 117 | } 118 | 119 | // 120 | // @Bean 121 | // public SqlSessionFactory getSqlSessionFactory(){ 122 | // 123 | // try { 124 | // SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 125 | // sqlSessionFactoryBean.setDataSource(dataSource()); 126 | // return sqlSessionFactoryBean.getObject(); 127 | // }catch (Exception e){ 128 | // log.error("config sqlSessionFactory Exception", e); 129 | // return null; 130 | // } 131 | // } 132 | // 133 | // @Bean 134 | // public SqlSessionTemplate getSqlSessionTemplate() { 135 | // return new SqlSessionTemplate(getSqlSessionFactory()); 136 | // } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.alibaba.druid.util.StringUtils; 4 | import com.yyh.mapper.ClResourceMapper; 5 | import com.yyh.mapper.PermissionMapper; 6 | import com.yyh.model.ClResource; 7 | import com.yyh.model.Permission; 8 | import com.yyh.service.UserService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.security.access.*; 13 | import org.springframework.security.authentication.InsufficientAuthenticationException; 14 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 15 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 16 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 17 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 18 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 19 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 20 | import org.springframework.security.core.Authentication; 21 | import org.springframework.security.core.GrantedAuthority; 22 | import org.springframework.security.crypto.password.PasswordEncoder; 23 | import org.springframework.security.web.FilterInvocation; 24 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 25 | import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; 26 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 27 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 28 | 29 | import javax.annotation.Resource; 30 | import java.util.*; 31 | 32 | /** 33 | * @author lhy 34 | * @Date 2018/11/14 10:59 35 | * @JDK 1.7 36 | * @Description TODO 37 | */ 38 | @EnableWebSecurity 39 | @Configuration 40 | @Slf4j 41 | @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true) 42 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer { 43 | 44 | @Resource 45 | private UserService userService; 46 | 47 | 48 | @Override 49 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 50 | auth.userDetailsService(userService); 51 | } 52 | 53 | @Override 54 | public void configure(WebSecurity web) throws Exception { 55 | web.securityInterceptor(filterSecurityInterceptor()); 56 | } 57 | 58 | @Override 59 | protected void configure(HttpSecurity http) throws Exception { 60 | 61 | http 62 | .authorizeRequests() 63 | .anyRequest().authenticated() 64 | //.accessDecisionManager(accessDecisionManager()) 此方法注册一个url的拦截器 65 | .and() 66 | .formLogin()//登陆拦截器 67 | .loginPage("/index")//自定义登陆页面 68 | .loginProcessingUrl("/login")//此处用的默认的处理登陆 69 | .successForwardUrl("/loginSuccess")//登陆成功跳转页面,不要任何权限 70 | .defaultSuccessUrl("/loginSuccess")//登陆成功跳转页面,有权的跳转到此页面 71 | .failureUrl("/loginFailure")//登陆失败跳转页面 72 | .permitAll()//权限配置 73 | .and() 74 | .logout().permitAll() 75 | .and() 76 | .csrf().disable() 77 | .exceptionHandling().accessDeniedPage("/accessDenied")//权限拒绝url 78 | 79 | ; 80 | 81 | } 82 | 83 | @Bean//设置密码加密方式 84 | public PasswordEncoder passwordEncoder(){ 85 | return new PasswordEncoder() { 86 | @Override 87 | public String encode(CharSequence rawPassword) { 88 | return rawPassword.toString(); 89 | } 90 | 91 | @Override 92 | public boolean matches(CharSequence rawPassword, String encodedPassword) { 93 | return StringUtils.equals(rawPassword.toString(),encodedPassword); 94 | } 95 | }; 96 | } 97 | 98 | @Bean 99 | public AccessDecisionManager accessDecisionManager(){ 100 | return new AccessDecisionManager() { 101 | @Override 102 | public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { 103 | if(null== configAttributes || configAttributes.size() <=0) {//没有相关资源不做权限校验 104 | return; 105 | } 106 | 107 | //遍历资源,如果拥有权限,安全校验通过 108 | for (ConfigAttribute configAttribute : configAttributes){ 109 | for (GrantedAuthority grantedAuthority : authentication.getAuthorities()){ 110 | if (StringUtils.equals(configAttribute.getAttribute(),grantedAuthority.getAuthority())){ 111 | return; 112 | } 113 | } 114 | } 115 | throw new AccessDeniedException("denied no right"); 116 | } 117 | @Override 118 | public boolean supports(ConfigAttribute attribute) { 119 | return true; 120 | } 121 | 122 | @Override 123 | public boolean supports(Class> clazz) { 124 | return true; 125 | } 126 | }; 127 | } 128 | 129 | 130 | @Resource 131 | private PermissionMapper permissionMapper; 132 | @Resource 133 | private ClResourceMapper resourceMapper; 134 | 135 | @Bean 136 | public FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource(){ 137 | //加载所有资源 138 | HashMap> map =new HashMap<>(); 139 | List resources = resourceMapper.findAll(); 140 | for(ClResource resource : resources){ 141 | List configAttributes = new ArrayList<>(); 142 | List permissions = permissionMapper.findByResourceId(resource.getId()); 143 | for (Permission permission : permissions){ 144 | ConfigAttribute configAttribute = new SecurityConfig(permission.getName()); 145 | configAttributes.add(configAttribute); 146 | } 147 | map.put(resource.getPattern(),configAttributes); 148 | } 149 | 150 | return new FilterInvocationSecurityMetadataSource() { 151 | @Override 152 | public Collection getAttributes(Object object) throws IllegalArgumentException { 153 | if (object instanceof FilterInvocation){ 154 | FilterInvocation fi = (FilterInvocation) object; 155 | for (String pattern : map.keySet()){ 156 | AntPathRequestMatcher matcher = new AntPathRequestMatcher(pattern); 157 | if (matcher.matches(fi.getHttpRequest())){ 158 | return map.get(pattern);//返回url匹配的资源 159 | } 160 | } 161 | } 162 | return null; 163 | } 164 | 165 | @Override 166 | public Collection getAllConfigAttributes() { 167 | return null; 168 | } 169 | 170 | @Override 171 | public boolean supports(Class> clazz) { 172 | return true; 173 | } 174 | }; 175 | } 176 | 177 | @Bean//配置FilterSecurityInterceptor 178 | public FilterSecurityInterceptor filterSecurityInterceptor(){ 179 | FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor(); 180 | filterSecurityInterceptor.setAccessDecisionManager(accessDecisionManager()); 181 | filterSecurityInterceptor.setSecurityMetadataSource(filterInvocationSecurityMetadataSource()); 182 | filterSecurityInterceptor.setObserveOncePerRequest(false); 183 | return filterSecurityInterceptor; 184 | } 185 | 186 | } 187 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import com.yyh.mapper.PermissionMapper; 4 | import com.yyh.model.Permission; 5 | import org.springframework.context.annotation.ComponentScan; 6 | import org.springframework.security.access.annotation.Secured; 7 | import org.springframework.security.access.prepost.PostAuthorize; 8 | import org.springframework.security.access.prepost.PreAuthorize; 9 | import org.springframework.security.access.prepost.PreFilter; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | import javax.annotation.Resource; 15 | import javax.annotation.security.DenyAll; 16 | import javax.annotation.security.PermitAll; 17 | import javax.annotation.security.RolesAllowed; 18 | import java.util.List; 19 | 20 | /** 21 | * @author lhy 22 | * @Date 2018/10/22 9:46 23 | * @JDK 1.7 24 | * @Description TODO 25 | */ 26 | @RestController 27 | public class TestController { 28 | @Resource 29 | private PermissionMapper permissionMapper; 30 | 31 | @GetMapping("api/allPermission") 32 | public List allPermission(){ 33 | return permissionMapper.findAll(); 34 | } 35 | 36 | @GetMapping("/hi/world") 37 | public String hi(){ 38 | return "hello world"; 39 | } 40 | 41 | @GetMapping("/test/test") 42 | public String test(){ 43 | return "test"; 44 | } 45 | 46 | @PreAuthorize("permitAll()") 47 | @PermitAll 48 | @GetMapping("/study/study") 49 | public String study(){ 50 | return "study"; 51 | } 52 | 53 | @RolesAllowed("ADMIN") 54 | // @PreAuthorize("hasRole('ADMIN')") 55 | @GetMapping("/learn/learn") 56 | public String learn(){ 57 | return "learn"; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import org.springframework.security.authentication.AnonymousAuthenticationToken; 4 | import org.springframework.security.core.Authentication; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | 9 | 10 | /** 11 | * @author lhy 12 | * @Date 2018/11/14 9:39 13 | * @JDK 1.7 14 | * @Description TODO 15 | */ 16 | @Controller 17 | public class UserController { 18 | 19 | @GetMapping("/loginSuccess") 20 | public String loginSuccess(){ 21 | return "home"; 22 | } 23 | 24 | @GetMapping("/loginFailure") 25 | public String loginFailure(){ 26 | return "loginFail"; 27 | } 28 | 29 | @GetMapping({"/","/index"}) 30 | public String index(){ 31 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 32 | if (authentication instanceof AnonymousAuthenticationToken){ 33 | return "index"; 34 | }else { 35 | return "home"; 36 | } 37 | } 38 | 39 | @GetMapping("/accessDenied") 40 | public String accessDenied(){ 41 | return "accessDenied"; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/mapper/BaseMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | import com.yyh.model.Permission; 4 | 5 | /** 6 | * @author lhy 7 | * @Date 2018/10/22 10:59 8 | * @JDK 1.7 9 | * @Description TODO 10 | */ 11 | public interface BaseMapper { 12 | int deleteByPrimaryKey(Long id); 13 | 14 | int insert(Permission record); 15 | 16 | int insertSelective(T record); 17 | 18 | T selectByPrimaryKey(Long id); 19 | 20 | int updateByPrimaryKeySelective(T record); 21 | 22 | int updateByPrimaryKey(T record); 23 | } 24 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/mapper/ClResourceMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | 4 | import com.yyh.model.ClResource; 5 | 6 | import java.util.List; 7 | 8 | public interface ClResourceMapper { 9 | int deleteByPrimaryKey(Integer id); 10 | 11 | int insert(ClResource record); 12 | 13 | int insertSelective(ClResource record); 14 | 15 | ClResource selectByPrimaryKey(Integer id); 16 | 17 | int updateByPrimaryKeySelective(ClResource record); 18 | 19 | int updateByPrimaryKey(ClResource record); 20 | 21 | List selectResourceByPermissionId(Integer permissionId); 22 | 23 | List findAll(); 24 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/mapper/ClRoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | 4 | import com.yyh.model.ClRole; 5 | 6 | import java.util.List; 7 | 8 | public interface ClRoleMapper { 9 | int deleteByPrimaryKey(Long id); 10 | 11 | int insert(ClRole record); 12 | 13 | int insertSelective(ClRole record); 14 | 15 | ClRole selectByPrimaryKey(Long id); 16 | 17 | int updateByPrimaryKeySelective(ClRole record); 18 | 19 | int updateByPrimaryKey(ClRole record); 20 | 21 | List selectAllRole(); 22 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/mapper/ClUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | import com.yyh.model.ClUser; 4 | 5 | import java.util.List; 6 | 7 | public interface ClUserMapper { 8 | int deleteByPrimaryKey(Long id); 9 | 10 | int insert(ClUser record); 11 | 12 | int insertSelective(ClUser record); 13 | 14 | ClUser selectByPrimaryKey(Long id); 15 | 16 | int updateByPrimaryKeySelective(ClUser record); 17 | 18 | int updateByPrimaryKey(ClUser record); 19 | 20 | ClUser findClUser(ClUser record); 21 | 22 | List findAll(); 23 | 24 | ClUser findByUsername(String username); 25 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/mapper/PermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | import com.yyh.model.Permission; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @author lhy 9 | * @Date 2018/10/19 15:31 10 | * @JDK 1.7 11 | * @Description TODO 12 | */ 13 | 14 | public interface PermissionMapper{ 15 | 16 | int deleteByPrimaryKey(Long id); 17 | 18 | int insert(Permission record); 19 | 20 | int insertSelective(Permission record); 21 | 22 | Permission selectByPrimaryKey(Long id); 23 | 24 | int updateByPrimaryKeySelective(Permission record); 25 | 26 | int updateByPrimaryKey(Permission record); 27 | 28 | List findAll(); 29 | 30 | List findByAdminUserId(int userId); 31 | 32 | int countPermission(); 33 | 34 | List findByResourceId(int resourceId); 35 | } 36 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/model/ClResource.java: -------------------------------------------------------------------------------- 1 | package com.yyh.model; 2 | 3 | public class ClResource { 4 | private Integer id; 5 | 6 | private String name; 7 | 8 | private String pattern; 9 | 10 | public Integer getId() { 11 | return id; 12 | } 13 | 14 | public void setId(Integer id) { 15 | this.id = id; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public String getPattern() { 27 | return pattern; 28 | } 29 | 30 | public void setPattern(String pattern) { 31 | this.pattern = pattern; 32 | } 33 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/model/ClRole.java: -------------------------------------------------------------------------------- 1 | package com.yyh.model; 2 | 3 | public class ClRole { 4 | private Long id; 5 | 6 | private String name; 7 | 8 | public Long getId() { 9 | return id; 10 | } 11 | 12 | public void setId(Long id) { 13 | this.id = id; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/model/ClUser.java: -------------------------------------------------------------------------------- 1 | package com.yyh.model; 2 | 3 | 4 | 5 | 6 | public class ClUser { 7 | private Long id; 8 | 9 | private String username; 10 | 11 | private String password; 12 | 13 | 14 | public Long getId() { 15 | return id; 16 | } 17 | 18 | public void setId(Long id) { 19 | this.id = id; 20 | } 21 | 22 | public String getUsername() { 23 | return username; 24 | } 25 | 26 | public void setUsername(String username) { 27 | this.username = username; 28 | } 29 | 30 | public String getPassword() { 31 | return password; 32 | } 33 | 34 | public void setPassword(String password) { 35 | this.password = password; 36 | } 37 | } -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/model/Permission.java: -------------------------------------------------------------------------------- 1 | package com.yyh.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author lhy 7 | * @Date 2018/10/19 15:29 8 | * @JDK 1.7 9 | * @Description TODO 10 | */ 11 | @Data 12 | public class Permission { 13 | private Integer id; 14 | //权限名称 15 | private String name; 16 | 17 | //权限描述 18 | private String description; 19 | 20 | //授权链接 21 | private String url; 22 | 23 | //父节点id 24 | private Integer pid; 25 | } 26 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.yyh.service; 2 | 3 | 4 | import com.yyh.mapper.ClUserMapper; 5 | import com.yyh.mapper.PermissionMapper; 6 | import com.yyh.model.ClUser; 7 | import com.yyh.model.Permission; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.User; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 14 | import org.springframework.stereotype.Service; 15 | 16 | import javax.annotation.Resource; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | 21 | /** 22 | * @author lhy 23 | * @Date 2018/11/14 13:46 24 | * @JDK 1.7 25 | * @Description TODO 26 | */ 27 | @Service 28 | public class UserService extends InMemoryUserDetailsManager { 29 | @Resource 30 | private ClUserMapper clUserMapper; 31 | 32 | @Resource 33 | private PermissionMapper permissionMapper; 34 | 35 | //加载用户和相关权限 36 | @Override 37 | public UserDetails loadUserByUsername(String username) { 38 | ClUser clUser = clUserMapper.findByUsername(username); 39 | if (clUser == null){ 40 | throw new UsernameNotFoundException("用户不存在"); 41 | } 42 | List permissions = permissionMapper.findByAdminUserId(clUser.getId().intValue()); 43 | List authorities = new ArrayList<>(); 44 | if (permissions != null && permissions.size() > 0){ 45 | for (Permission permission : permissions){ 46 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName()); 47 | authorities.add(grantedAuthority); 48 | } 49 | } 50 | return new User(clUser.getUsername(),clUser.getPassword(),authorities) ; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/java/com/yyh/util/IDCard.java: -------------------------------------------------------------------------------- 1 | package com.yyh.util; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.text.SimpleDateFormat; 7 | import java.util.Calendar; 8 | import java.util.GregorianCalendar; 9 | import java.util.Hashtable; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | public class IDCard { 14 | private String idCardNo; 15 | private boolean isValid; 16 | private String birthday; 17 | private String gender; 18 | private String province; 19 | // private String city; 20 | // private String district; 21 | private String errorInfo; 22 | /*********************************** 身份证验证开始 ****************************************/ 23 | /** 24 | * 身份证号码验证 1、号码的结构 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码, 25 | * 八位数字出生日期码,三位数字顺序码和一位数字校验码。 2、地址码(前六位数) 26 | * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。 3、出生日期码(第七位至十四位) 27 | * 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 4、顺序码(第十五位至十七位) 28 | * 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号, 顺序码的奇数分配给男性,偶数分配给女性。 5、校验码(第十八位数) 29 | * (1)十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和 30 | * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 31 | * 2 (2)计算模 Y = mod(S, 11) (3)通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 32 | * X 9 8 7 6 5 4 3 2 33 | */ 34 | 35 | public IDCard(String idStr){ 36 | this.idCardNo = idStr; 37 | idStr = idStr.toLowerCase(); 38 | String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4", 39 | "3", "2" }; 40 | String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", 41 | "9", "10", "5", "8", "4", "2" }; 42 | String Ai = ""; 43 | // ================ 号码的长度 15位或18位 ================ 44 | if (idStr.length() != 15 && idStr.length() != 18) { 45 | this.errorInfo = "身份证号码长度应该为15位或18位。"; 46 | this.isValid = false; 47 | return; 48 | } 49 | // =======================(end)======================== 50 | 51 | // ================ 数字 除最后以为都为数字 ================ 52 | if (idStr.length() == 18) { 53 | Ai = idStr.substring(0, 17); 54 | } else { 55 | Ai = idStr.substring(0, 6) + "19" + idStr.substring(6, 15); 56 | } 57 | if (!isNumeric(Ai)) { 58 | this.errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。"; 59 | this.isValid = false; 60 | return; 61 | } 62 | // =======================(end)======================== 63 | 64 | // ================ 出生年月是否有效 ================ 65 | String strYear = Ai.substring(6, 10);// 年份 66 | String strMonth = Ai.substring(10, 12);// 月份 67 | String strDay = Ai.substring(12, 14);// 月份 68 | if (!isDate(strYear + "-" + strMonth + "-" + strDay)) { 69 | this.errorInfo = "身份证生日无效。"; 70 | this.isValid = false; 71 | return; 72 | } 73 | GregorianCalendar gc = new GregorianCalendar(); 74 | SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); 75 | try { 76 | if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 77 | || (gc.getTime().getTime() - s.parse( 78 | strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) { 79 | this.errorInfo = "身份证生日不在有效范围。"; 80 | this.isValid = false; 81 | return; 82 | } 83 | } catch (NumberFormatException | java.text.ParseException e) { 84 | this.errorInfo = e.getMessage(); 85 | this.isValid = false; 86 | e.printStackTrace(); 87 | return; 88 | } 89 | if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) { 90 | this.errorInfo = "身份证月份无效"; 91 | this.isValid = false; 92 | return; 93 | 94 | } 95 | if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) { 96 | this.errorInfo = "身份证日期无效"; 97 | this.isValid = false; 98 | return; 99 | } 100 | // =====================(end)===================== 101 | 102 | // ================ 地区码时候有效 ================ 103 | Hashtable h = GetAreaCode(); 104 | String areaCode = Ai.substring(0, 2); 105 | if (h.get(areaCode) == null) { 106 | this.errorInfo = "身份证地区编码错误。"; 107 | this.isValid = false; 108 | return; 109 | } 110 | // ============================================== 111 | 112 | // ================ 判断最后一位的值 ================ 113 | int TotalmulAiWi = 0; 114 | for (int i = 0; i < 17; i++) { 115 | TotalmulAiWi = TotalmulAiWi 116 | + Integer.parseInt(String.valueOf(Ai.charAt(i))) 117 | * Integer.parseInt(Wi[i]); 118 | } 119 | int modValue = TotalmulAiWi % 11; 120 | String strVerifyCode = ValCodeArr[modValue]; 121 | Ai = Ai + strVerifyCode; 122 | 123 | if (idStr.length() == 18) { 124 | if (!Ai.equals(idStr)) { 125 | this.errorInfo = "身份证无效,不是合法的身份证号码"; 126 | this.isValid = false; 127 | return; 128 | } 129 | } 130 | this.province = h.get(areaCode); 131 | this.birthday = strYear + "-" + strMonth + "-" + strDay; 132 | this.gender = getGender(idCardNo); 133 | this.isValid = true; 134 | // =====================(end)===================== 135 | } 136 | 137 | private static String getGender(String idCardNo){ 138 | try { 139 | String n = idCardNo.substring(idCardNo.length()-2,idCardNo.length()-1); 140 | return Integer.valueOf(n)%2 == 0 ? "女" : "男"; 141 | }catch (Exception e){ 142 | e.printStackTrace(); 143 | return null; 144 | } 145 | } 146 | 147 | 148 | 149 | /** 150 | * 功能:身份证的有效验证 151 | * 152 | * @param idStr 153 | * 身份证号 154 | * @return 有效:返回"" 无效:返回String信息 155 | */ 156 | public static String idCardValidate(String idStr) { 157 | 158 | idStr = idStr.toLowerCase(); 159 | String errorInfo = "";// 记录错误信息 160 | String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4", 161 | "3", "2" }; 162 | String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", 163 | "9", "10", "5", "8", "4", "2" }; 164 | String Ai = ""; 165 | // ================ 号码的长度 15位或18位 ================ 166 | if (idStr.length() != 15 && idStr.length() != 18) { 167 | errorInfo = "身份证号码长度应该为15位或18位。"; 168 | return errorInfo; 169 | } 170 | // =======================(end)======================== 171 | 172 | // ================ 数字 除最后以为都为数字 ================ 173 | if (idStr.length() == 18) { 174 | Ai = idStr.substring(0, 17); 175 | } else { 176 | Ai = idStr.substring(0, 6) + "19" + idStr.substring(6, 15); 177 | } 178 | if (!isNumeric(Ai)) { 179 | errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。"; 180 | return errorInfo; 181 | } 182 | // =======================(end)======================== 183 | 184 | // ================ 出生年月是否有效 ================ 185 | String strYear = Ai.substring(6, 10);// 年份 186 | String strMonth = Ai.substring(10, 12);// 月份 187 | String strDay = Ai.substring(12, 14);// 月份 188 | if (!isDate(strYear + "-" + strMonth + "-" + strDay)) { 189 | errorInfo = "身份证生日无效。"; 190 | return errorInfo; 191 | } 192 | GregorianCalendar gc = new GregorianCalendar(); 193 | SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); 194 | try { 195 | if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 196 | || (gc.getTime().getTime() - s.parse( 197 | strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) { 198 | errorInfo = "身份证生日不在有效范围。"; 199 | return errorInfo; 200 | } 201 | } catch (NumberFormatException | java.text.ParseException e) { 202 | e.printStackTrace(); 203 | } 204 | if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) { 205 | errorInfo = "身份证月份无效"; 206 | return errorInfo; 207 | } 208 | if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) { 209 | errorInfo = "身份证日期无效"; 210 | return errorInfo; 211 | } 212 | // =====================(end)===================== 213 | 214 | // ================ 地区码时候有效 ================ 215 | Hashtable, ?> h = GetAreaCode(); 216 | if (h.get(Ai.substring(0, 2)) == null) { 217 | errorInfo = "身份证地区编码错误。"; 218 | return errorInfo; 219 | } 220 | // ============================================== 221 | 222 | // ================ 判断最后一位的值 ================ 223 | int TotalmulAiWi = 0; 224 | for (int i = 0; i < 17; i++) { 225 | TotalmulAiWi = TotalmulAiWi 226 | + Integer.parseInt(String.valueOf(Ai.charAt(i))) 227 | * Integer.parseInt(Wi[i]); 228 | } 229 | int modValue = TotalmulAiWi % 11; 230 | String strVerifyCode = ValCodeArr[modValue]; 231 | Ai = Ai + strVerifyCode; 232 | 233 | if (idStr.length() == 18) { 234 | if (!Ai.equals(idStr)) { 235 | errorInfo = "身份证无效,不是合法的身份证号码"; 236 | return errorInfo; 237 | } 238 | } else { 239 | return "YES"; 240 | } 241 | // =====================(end)===================== 242 | return "YES"; 243 | } 244 | 245 | /** 246 | * 功能:设置地区编码 247 | * 248 | * @return Hashtable 对象 249 | */ 250 | private static Hashtable GetAreaCode() { 251 | Hashtable hashtable = new Hashtable(); 252 | hashtable.put("11", "北京"); 253 | hashtable.put("12", "天津"); 254 | hashtable.put("13", "河北"); 255 | hashtable.put("14", "山西"); 256 | hashtable.put("15", "内蒙古"); 257 | hashtable.put("21", "辽宁"); 258 | hashtable.put("22", "吉林"); 259 | hashtable.put("23", "黑龙江"); 260 | hashtable.put("31", "上海"); 261 | hashtable.put("32", "江苏"); 262 | hashtable.put("33", "浙江"); 263 | hashtable.put("34", "安徽"); 264 | hashtable.put("35", "福建"); 265 | hashtable.put("36", "江西"); 266 | hashtable.put("37", "山东"); 267 | hashtable.put("41", "河南"); 268 | hashtable.put("42", "湖北"); 269 | hashtable.put("43", "湖南"); 270 | hashtable.put("44", "广东"); 271 | hashtable.put("45", "广西"); 272 | hashtable.put("46", "海南"); 273 | hashtable.put("50", "重庆"); 274 | hashtable.put("51", "四川"); 275 | hashtable.put("52", "贵州"); 276 | hashtable.put("53", "云南"); 277 | hashtable.put("54", "西藏"); 278 | hashtable.put("61", "陕西"); 279 | hashtable.put("62", "甘肃"); 280 | hashtable.put("63", "青海"); 281 | hashtable.put("64", "宁夏"); 282 | hashtable.put("65", "新疆"); 283 | hashtable.put("71", "台湾"); 284 | hashtable.put("81", "香港"); 285 | hashtable.put("82", "澳门"); 286 | hashtable.put("91", "国外"); 287 | return hashtable; 288 | } 289 | 290 | /** 291 | * 功能:判断字符串是否为数字 292 | * 293 | * @param str 294 | * @return 295 | */ 296 | private static boolean isNumeric(String str) { 297 | Pattern pattern = Pattern.compile("[0-9]*"); 298 | Matcher isNum = pattern.matcher(str); 299 | return isNum.matches(); 300 | } 301 | 302 | /** 303 | * 功能:判断字符串是否为日期格式 304 | * 305 | * @param strDate 306 | * @return 307 | */ 308 | private static boolean isDate(String strDate) { 309 | Pattern pattern = Pattern 310 | .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); 311 | Matcher m = pattern.matcher(strDate); 312 | if (m.matches()) { 313 | return true; 314 | } else { 315 | return false; 316 | } 317 | } 318 | 319 | public static void main(String[] args) throws JsonProcessingException { 320 | IDCard idCard = new IDCard("622322199502091530"); 321 | System.out.println(new ObjectMapper().writeValueAsString(idCard)); 322 | 323 | } 324 | 325 | public String getIdCardNo() { 326 | return idCardNo; 327 | } 328 | 329 | public void setIdCardNo(String idCardNo) { 330 | this.idCardNo = idCardNo; 331 | } 332 | 333 | public boolean isValid() { 334 | return isValid; 335 | } 336 | 337 | public void setValid(boolean valid) { 338 | isValid = valid; 339 | } 340 | 341 | public String getBirthday() { 342 | return birthday; 343 | } 344 | 345 | public void setBirthday(String birthday) { 346 | this.birthday = birthday; 347 | } 348 | 349 | public String getGender() { 350 | return gender; 351 | } 352 | 353 | public void setGender(String gender) { 354 | this.gender = gender; 355 | } 356 | 357 | public String getProvince() { 358 | return province; 359 | } 360 | 361 | public void setProvince(String province) { 362 | this.province = province; 363 | } 364 | 365 | public String getErrorInfo() { 366 | return errorInfo; 367 | } 368 | 369 | public void setErrorInfo(String errorInfo) { 370 | this.errorInfo = errorInfo; 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NapWells/java_framework_learn/288f7a388ab763498313c9416277f6b82c5abb3e/springsecuritydemo/demo/src/main/resources/application.properties -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | /logs/warn.%d{yyyy-MM-dd}.log 20 | 21 | 10 22 | true 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{35} - %msg%n 33 | 34 | 35 | 36 | 37 | 38 | 39 | /tmp/taobao-crawler/error.%d{yyyy-MM-dd}.log 40 | 10 41 | true 42 | 43 | 44 | 45 | 46 | 47 | ERROR 48 | 49 | 50 | %d{yyy-MM-dd HH:mm:ss} %-5level %logger{35} - %msg%n 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/mapper/ClResourceMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | id, name, pattern 11 | 12 | 13 | select 14 | 15 | from sys_resource 16 | where id = #{id,jdbcType=INTEGER} 17 | 18 | 19 | delete from sys_resource 20 | where id = #{id,jdbcType=INTEGER} 21 | 22 | 23 | insert into sys_resource (id, name, pattern 24 | ) 25 | values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{pattern,jdbcType=VARCHAR} 26 | ) 27 | 28 | 29 | insert into sys_resource 30 | 31 | 32 | id, 33 | 34 | 35 | name, 36 | 37 | 38 | pattern, 39 | 40 | 41 | 42 | 43 | #{id,jdbcType=INTEGER}, 44 | 45 | 46 | #{name,jdbcType=VARCHAR}, 47 | 48 | 49 | #{pattern,jdbcType=VARCHAR}, 50 | 51 | 52 | 53 | 54 | update sys_resource 55 | 56 | 57 | name = #{name,jdbcType=VARCHAR}, 58 | 59 | 60 | pattern = #{pattern,jdbcType=VARCHAR}, 61 | 62 | 63 | where id = #{id,jdbcType=INTEGER} 64 | 65 | 66 | update sys_resource 67 | set name = #{name,jdbcType=VARCHAR}, 68 | pattern = #{pattern,jdbcType=VARCHAR} 69 | where id = #{id,jdbcType=INTEGER} 70 | 71 | 72 | 73 | SELECT 74 | sys_resource.* 75 | FROM 76 | sys_permission 77 | LEFT JOIN 78 | sys_permission_resource ON sys_permission.id = sys_permission_resource.permission_id 79 | LEFT JOIN 80 | sys_resource ON sys_permission_resource.resource_id = sys_resource.id 81 | where sys_permission.id = #{permissionId,jdbcType=INTEGER}; 82 | 83 | 84 | 85 | select * from sys_resource; 86 | 87 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/mapper/ClRoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | id, name 10 | 11 | 12 | select 13 | 14 | from sys_role 15 | where id = #{id,jdbcType=BIGINT} 16 | 17 | 18 | delete from sys_role 19 | where id = #{id,jdbcType=BIGINT} 20 | 21 | 22 | insert into sys_role (id, name) 23 | values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}) 24 | 25 | 26 | insert into sys_role 27 | 28 | 29 | id, 30 | 31 | 32 | name, 33 | 34 | 35 | 36 | 37 | #{id,jdbcType=BIGINT}, 38 | 39 | 40 | #{name,jdbcType=VARCHAR}, 41 | 42 | 43 | 44 | 45 | update sys_role 46 | 47 | 48 | name = #{name,jdbcType=VARCHAR}, 49 | 50 | 51 | where id = #{id,jdbcType=BIGINT} 52 | 53 | 54 | update sys_role 55 | set name = #{name,jdbcType=VARCHAR} 56 | where id = #{id,jdbcType=BIGINT} 57 | 58 | 59 | select * from sys_role; 60 | 61 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/mapper/ClUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | id, username, password 11 | 12 | 13 | select 14 | 15 | from sys_user 16 | where id = #{id,jdbcType=BIGINT} 17 | 18 | 19 | delete from sys_user 20 | where id = #{id,jdbcType=BIGINT} 21 | 22 | 23 | insert into sys_user (id, username, password 24 | ) 25 | values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR} 26 | ) 27 | 28 | 29 | insert into sys_user 30 | 31 | 32 | id, 33 | 34 | 35 | username, 36 | 37 | 38 | password, 39 | 40 | 41 | 42 | 43 | #{id,jdbcType=BIGINT}, 44 | 45 | 46 | #{username,jdbcType=VARCHAR}, 47 | 48 | 49 | #{password,jdbcType=VARCHAR}, 50 | 51 | 52 | 53 | 54 | update sys_user 55 | 56 | 57 | username = #{username,jdbcType=VARCHAR}, 58 | 59 | 60 | password = #{password,jdbcType=VARCHAR}, 61 | 62 | 63 | where id = #{id,jdbcType=BIGINT} 64 | 65 | 66 | update sys_user 67 | set username = #{username,jdbcType=VARCHAR}, 68 | password = #{password,jdbcType=VARCHAR} 69 | where id = #{id,jdbcType=BIGINT} 70 | 71 | 72 | 73 | select * from sys_user where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}; 74 | 75 | 76 | 77 | select * from sys_user ; 78 | 79 | 80 | 81 | select * from sys_user where username = #{username,jdbcType=VARCHAR}; 82 | 83 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/mapper/PermissionMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | id, name, description, url, pid 14 | 15 | 16 | 17 | select 18 | 19 | from sys_permission 20 | where id = #{id,jdbcType=BIGINT} 21 | 22 | 23 | 24 | delete from sys_permission 25 | where id = #{id,jdbcType=BIGINT} 26 | 27 | 28 | 29 | insert into sys_permission (name, description, 30 | url, pid) 31 | values (#{name,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, 32 | #{url,jdbcType=VARCHAR}, #{pid,jdbcType=BIGINT}) 33 | 34 | 35 | 36 | insert into sys_permission 37 | 38 | 39 | id, 40 | 41 | 42 | name, 43 | 44 | 45 | description, 46 | 47 | 48 | url, 49 | 50 | 51 | pid, 52 | 53 | 54 | 55 | 56 | #{id,jdbcType=BIGINT}, 57 | 58 | 59 | #{name,jdbcType=VARCHAR}, 60 | 61 | 62 | #{description,jdbcType=VARCHAR}, 63 | 64 | 65 | #{url,jdbcType=VARCHAR}, 66 | 67 | 68 | #{pid,jdbcType=BIGINT}, 69 | 70 | 71 | 72 | 73 | 74 | update sys_permission 75 | 76 | 77 | name = #{name,jdbcType=VARCHAR}, 78 | 79 | 80 | description = #{description,jdbcType=VARCHAR}, 81 | 82 | 83 | url = #{url,jdbcType=VARCHAR}, 84 | 85 | 86 | pid = #{pid,jdbcType=BIGINT}, 87 | 88 | 89 | where id = #{id,jdbcType=BIGINT} 90 | 91 | 92 | 93 | update sys_permission 94 | set name = #{name,jdbcType=VARCHAR}, 95 | description = #{description,jdbcType=VARCHAR}, 96 | url = #{url,jdbcType=VARCHAR}, 97 | pid = #{pid,jdbcType=BIGINT} 98 | where id = #{id,jdbcType=BIGINT} 99 | 100 | 101 | 102 | SELECT * from Sys_permission ; 103 | 104 | 105 | 106 | SELECT 107 | sys_permission.* 108 | FROM 109 | sys_user 110 | LEFT JOIN 111 | sys_role_user ON sys_user.id = sys_role_user.sys_user_id 112 | LEFT JOIN 113 | sys_role ON sys_role_user.sys_role_id = sys_role.id 114 | LEFT JOIN 115 | sys_permission_role ON sys_permission_role.role_id = sys_role.id 116 | LEFT JOIN 117 | sys_permission ON sys_permission_role.permission_id = sys_permission.id 118 | WHERE 119 | sys_user.id = #{id,jdbcType=BIGINT} and sys_permission.id is not null 120 | 121 | 122 | 123 | select count(*) from sys_permission; 124 | 125 | 126 | 127 | SELECT 128 | sys_permission.* 129 | FROM 130 | sys_permission 131 | LEFT JOIN 132 | sys_permission_resource ON sys_permission.id = sys_permission_resource.permission_id 133 | LEFT JOIN 134 | sys_resource ON sys_permission_resource.resource_id = sys_resource.id 135 | where sys_resource.id = #{resourceId,jdbcType=BIGINT}; 136 | 137 | 138 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `sys_permission` ( 2 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 3 | `name` varchar(200) COLLATE utf8mb4_general_ci NOT NULL, 4 | `description` varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL, 5 | `url` varchar(200) COLLATE utf8mb4_general_ci NOT NULL, 6 | `pid` bigint(20) DEFAULT NULL, 7 | PRIMARY KEY (`id`) 8 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 9 | 10 | CREATE TABLE `sys_permission_resource` ( 11 | `id` int(11) NOT NULL, 12 | `permission_id` int(11) DEFAULT NULL, 13 | `resource_id` int(11) DEFAULT NULL, 14 | PRIMARY KEY (`id`) 15 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; 16 | 17 | CREATE TABLE `sys_permission_role` ( 18 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 19 | `role_id` bigint(20) unsigned NOT NULL, 20 | `permission_id` bigint(20) unsigned NOT NULL, 21 | PRIMARY KEY (`id`) 22 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 23 | 24 | CREATE TABLE `sys_resource` ( 25 | `id` int(11) NOT NULL, 26 | `name` varchar(45) DEFAULT NULL, 27 | `pattern` varchar(45) DEFAULT NULL, 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; 30 | 31 | 32 | CREATE TABLE `sys_role` ( 33 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 34 | `name` varchar(200) COLLATE utf8mb4_general_ci NOT NULL, 35 | PRIMARY KEY (`id`) 36 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 37 | 38 | 39 | CREATE TABLE `sys_role_user` ( 40 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 41 | `sys_user_id` bigint(20) unsigned NOT NULL, 42 | `sys_role_id` bigint(20) unsigned NOT NULL, 43 | PRIMARY KEY (`id`) 44 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 45 | 46 | 47 | CREATE TABLE `sys_user` ( 48 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 49 | `username` varchar(200) COLLATE utf8mb4_general_ci NOT NULL, 50 | `password` varchar(200) COLLATE utf8mb4_general_ci NOT NULL, 51 | PRIMARY KEY (`id`) 52 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; 53 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/template/accessDenied.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | home page 6 | 7 | 8 | 9 | 无访问权限 10 | 11 | 12 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/template/error.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | home page 6 | 7 | 8 | 9 | error page 10 | 11 | 12 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/template/home.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | home page 6 | 7 | 8 | 9 | 10 | 11 | 12 | 欢迎你! 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/template/index.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | home page 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 请登录 17 | 用户名 18 | 19 | 密码 20 | 21 | 22 | 23 | 24 | 记住我 25 | 26 | 27 | 登录 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /springsecuritydemo/demo/src/main/resources/template/loginFail.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | home page 6 | 7 | 8 | 9 | 登陆失败,账号或密码错误 10 | 11 | 12 | -------------------------------------------------------------------------------- /springsecuritydemo/mybats_generator/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | springsecuritydemo 7 | com.yyh 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | mybats_generator 13 | 14 | 15 | 16 | 17 | org.mybatis.generator 18 | mybatis-generator-maven-plugin 19 | 1.3.2 20 | 21 | src/main/resources/generatorConfig.xml 22 | true 23 | true 24 | 25 | 26 | 27 | Generate MyBatis Artifacts 28 | 29 | generate 30 | 31 | 32 | 33 | 34 | 35 | org.mybatis.generator 36 | mybatis-generator-core 37 | 1.3.5 38 | 39 | 40 | 41 | org.mybatis 42 | mybatis 43 | 3.4.2 44 | 45 | 46 | 47 | mysql 48 | mysql-connector-java 49 | 8.0.9-rc 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /springsecuritydemo/mybats_generator/src/main/resources/generatorConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 20 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | 38 | 39 | 41 | 42 | 43 | 44 | 45 | 46 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /springsecuritydemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | springsecuritydemo 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | demo 13 | mybats_generator 14 | 15 | 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-dependencies 22 | 2.0.0.RELEASE 23 | pom 24 | import 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /springswagger/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | springmvcswagger 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.5.2.RELEASE 15 | 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-logging 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-tomcat 33 | 34 | 35 | 36 | 37 | io.springfox 38 | springfox-swagger2 39 | 2.6.1 40 | 41 | 42 | 43 | io.springfox 44 | springfox-swagger-ui 45 | 2.6.1 46 | 47 | 48 | org.projectlombok 49 | lombok 50 | 1.16.10 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.apache.maven.plugins 58 | maven-compiler-plugin 59 | 3.0 60 | 61 | 1.8 62 | 1.8 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-maven-plugin 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /springswagger/src/main/java/com/yyh/Application.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /springswagger/src/main/java/com/yyh/config/Swagger2Config.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.spi.DocumentationType; 11 | import springfox.documentation.spring.web.plugins.Docket; 12 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 | 14 | 15 | @Configuration 16 | @EnableSwagger2 17 | public class Swagger2Config { 18 | @Bean 19 | public Docket createRestfulApi() { 20 | return new Docket(DocumentationType.SWAGGER_2) 21 | .apiInfo(apiInfo()) 22 | .select() 23 | .apis(RequestHandlerSelectors.basePackage("com.yyh.controller")) 24 | .paths(PathSelectors.any()) 25 | .build(); 26 | } 27 | 28 | private ApiInfo apiInfo() { 29 | return new ApiInfoBuilder() 30 | .title("Spring Boot中使用Swagger2构建RESTful接口") 31 | .description("接口描述") 32 | .termsOfServiceUrl("termsOfServiceUrl") 33 | .contact("new Contact") 34 | .version("1.0") 35 | .license("http://springfox.github.io/springfox/docs/current/") 36 | .licenseUrl("http://springfox.github.io/springfox/docs/current/") 37 | .build(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /springswagger/src/main/java/com/yyh/controller/AnimalController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.controller; 2 | 3 | import com.yyh.dto.AnimalError; 4 | import com.yyh.dto.Dog; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | import io.swagger.annotations.*; 8 | 9 | @RestController 10 | @Api(value="用户接口",tags={"dogAPi"}) 11 | @RequestMapping(value = "/swagger") 12 | public class AnimalController { 13 | 14 | @ApiImplicitParams({ 15 | @ApiImplicitParam(paramType = "header", name = "Token", value = "token", dataType = "String", required = true,defaultValue = "123")}) 16 | @ApiOperation(value = "获取一只狗") 17 | @ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证.", response = AnimalError.class) }) 18 | @RequestMapping(value="/onedog", method = RequestMethod.GET) 19 | public Dog oneDog(){ 20 | return new Dog(); 21 | } 22 | 23 | @ApiImplicitParams({ 24 | @ApiImplicitParam(paramType = "header", name = "Token", value = "token", dataType = "String", required = true,defaultValue = "123")}) 25 | @ApiOperation(value = "创建一只狗") 26 | @ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证.", response = AnimalError.class) }) 27 | @RequestMapping(value="/dog/{name}", method = RequestMethod.GET) 28 | public Dog createDog( 29 | @ApiParam(defaultValue = "二哈") 30 | @PathVariable("name") String name){ 31 | Dog dog = new Dog(); 32 | dog.setName(name); 33 | return dog; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /springswagger/src/main/java/com/yyh/dto/AnimalError.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class AnimalError { 7 | private int status; 8 | private String message; 9 | private boolean result; 10 | } 11 | -------------------------------------------------------------------------------- /springswagger/src/main/java/com/yyh/dto/Dog.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | 4 | import lombok.Data; 5 | 6 | 7 | @Data 8 | public class Dog { 9 | private String name = "旺财"; 10 | private String age = "12"; 11 | private String breed = "拉布拉多"; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springtransaction/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | springtransaction 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-dependencies 16 | 2.0.0.RELEASE 17 | pom 18 | import 19 | 20 | 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | 31 | org.mybatis.spring.boot 32 | mybatis-spring-boot-starter 33 | 1.3.2 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | 44 | com.mchange 45 | c3p0 46 | 0.9.5.2 47 | 48 | 49 | 50 | 51 | mysql 52 | mysql-connector-java 53 | 8.0.9-rc 54 | 55 | 56 | 57 | org.projectlombok 58 | lombok 59 | 1.16.10 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | org.apache.maven.plugins 70 | maven-compiler-plugin 71 | 3.0 72 | 73 | 1.8 74 | 1.8 75 | 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-maven-plugin 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/AppDemoMain.java: -------------------------------------------------------------------------------- 1 | package com.yyh; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.transaction.annotation.EnableTransactionManagement; 7 | 8 | @SpringBootApplication 9 | @MapperScan("com.yyh.mapper") 10 | @EnableTransactionManagement 11 | public class AppDemoMain { 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | SpringApplication.run(AppDemoMain.class, args); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/config/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.mchange.v2.c3p0.ComboPooledDataSource; 4 | import lombok.Data; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.PropertySource; 9 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 10 | 11 | @Data 12 | @Configuration 13 | @PropertySource("classpath:datasource.properties") 14 | @ConfigurationProperties(prefix = "connection") 15 | public class DataSourceConfig { 16 | private String username; 17 | private String password; 18 | private String url; 19 | private String driverClassName; 20 | private int acquireIncrement; 21 | private int acquireRetryAttempts; 22 | private int acquireRetryDelay; 23 | private int maxPoolSize; 24 | private int minPoolSize; 25 | private int initialPoolSize; 26 | 27 | @Bean 28 | public ComboPooledDataSource getDataSource() throws Exception { 29 | ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); 30 | comboPooledDataSource.setUser(username); 31 | comboPooledDataSource.setPassword(password); 32 | comboPooledDataSource.setJdbcUrl(url); 33 | comboPooledDataSource.setDriverClass(driverClassName); 34 | comboPooledDataSource.setMinPoolSize(minPoolSize); 35 | comboPooledDataSource.setMaxPoolSize(maxPoolSize); 36 | comboPooledDataSource.setInitialPoolSize(initialPoolSize); 37 | comboPooledDataSource.setAcquireIncrement(acquireIncrement); 38 | comboPooledDataSource.setAcquireRetryDelay(acquireRetryDelay); 39 | comboPooledDataSource.setAcquireRetryAttempts(acquireRetryAttempts); 40 | System.err.println(comboPooledDataSource); 41 | return comboPooledDataSource; 42 | } 43 | 44 | @Bean 45 | public DataSourceTransactionManager dataSourceTransactionManager() throws Exception { 46 | DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); 47 | dataSourceTransactionManager.setDataSource(getDataSource()); 48 | return dataSourceTransactionManager; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/config/MybatisConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.config; 2 | 3 | import com.mchange.v2.c3p0.ComboPooledDataSource; 4 | import lombok.Data; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 10 | import org.springframework.context.annotation.Bean; 11 | 12 | @Data 13 | @EnableAutoConfiguration 14 | public class MybatisConfig { 15 | @Autowired 16 | private ComboPooledDataSource dataSource; 17 | 18 | @Bean 19 | public SqlSessionFactory getSqlSessionFactory(){ 20 | try { 21 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 22 | sqlSessionFactoryBean.setDataSource(dataSource); 23 | return sqlSessionFactoryBean.getObject(); 24 | }catch (Exception e){ 25 | e.printStackTrace(); 26 | return null; 27 | } 28 | } 29 | 30 | @Bean 31 | public SqlSessionTemplate getSqlSessionTemplate() { 32 | return new SqlSessionTemplate(getSqlSessionFactory()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/dto/Account.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Account { 6 | private Integer id; 7 | private Integer userId; 8 | private String name; 9 | private BigDecimal balance; 10 | 11 | public Integer getId() { 12 | return id; 13 | } 14 | 15 | public void setId(Integer id) { 16 | this.id = id; 17 | } 18 | 19 | public Integer getUserId() { 20 | return userId; 21 | } 22 | 23 | public void setUserId(Integer userId) { 24 | this.userId = userId; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public BigDecimal getBalance() { 36 | return balance; 37 | } 38 | 39 | public void setBalance(BigDecimal balance) { 40 | this.balance = balance; 41 | } 42 | } -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/dto/ClUser.java: -------------------------------------------------------------------------------- 1 | package com.yyh.dto; 2 | 3 | import java.util.Date; 4 | 5 | public class ClUser { 6 | private Integer id; 7 | 8 | private String name; 9 | 10 | private Integer age; 11 | 12 | private String phone; 13 | 14 | private Date modifyTime; 15 | 16 | public Integer getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Integer id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public Integer getAge() { 33 | return age; 34 | } 35 | 36 | public void setAge(Integer age) { 37 | this.age = age; 38 | } 39 | 40 | public String getPhone() { 41 | return phone; 42 | } 43 | 44 | public void setPhone(String phone) { 45 | this.phone = phone; 46 | } 47 | 48 | public Date getModifyTime() { 49 | return modifyTime; 50 | } 51 | 52 | public void setModifyTime(Date modifyTime) { 53 | this.modifyTime = modifyTime; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "ClUser{" + 59 | "id=" + id + 60 | ", name='" + name + '\'' + 61 | ", age=" + age + 62 | ", phone='" + phone + '\'' + 63 | ", modifyTime=" + modifyTime + 64 | '}'; 65 | } 66 | } -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/mapper/AccountMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | import com.yyh.dto.Account; 4 | 5 | public interface AccountMapper { 6 | int deleteByPrimaryKey(Integer id); 7 | 8 | int insert(Account record); 9 | 10 | int insertSelective(Account record); 11 | 12 | Account selectByPrimaryKey(Integer id); 13 | 14 | int updateByPrimaryKeySelective(Account record); 15 | 16 | int updateByPrimaryKey(Account record); 17 | } -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/mapper/ClUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.yyh.mapper; 2 | 3 | 4 | import com.yyh.dto.ClUser; 5 | 6 | public interface ClUserMapper { 7 | int deleteByPrimaryKey(Integer id); 8 | 9 | int insert(ClUser record); 10 | 11 | int insertSelective(ClUser record); 12 | 13 | ClUser selectByPrimaryKey(Integer id); 14 | 15 | int updateByPrimaryKeySelective(ClUser record); 16 | 17 | int updateByPrimaryKey(ClUser record); 18 | } -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/service/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.yyh.service; 2 | 3 | import com.yyh.dto.Account; 4 | import com.yyh.mapper.AccountMapper; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Isolation; 7 | import org.springframework.transaction.annotation.Propagation; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import javax.annotation.Resource; 11 | 12 | @Service 13 | public class AccountService { 14 | 15 | @Resource 16 | private AccountMapper accountMapper; 17 | 18 | @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE) 19 | public boolean updateAccout(Account account){ 20 | int result = accountMapper.updateByPrimaryKey(account); 21 | return result == 1; 22 | } 23 | 24 | @Transactional(propagation = Propagation.SUPPORTS) 25 | public boolean createAccount(Account account){ 26 | int result = accountMapper.insertSelective(account); 27 | return result == 1; 28 | } 29 | 30 | public Account getAccount(int id){ 31 | return accountMapper.selectByPrimaryKey(id); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /springtransaction/src/main/java/com/yyh/service/TransactionService.java: -------------------------------------------------------------------------------- 1 | package com.yyh.service; 2 | 3 | import com.yyh.dto.Account; 4 | import org.springframework.stereotype.Service; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | import javax.annotation.Resource; 8 | import java.math.BigDecimal; 9 | 10 | @Service 11 | public class TransactionService { 12 | @Resource 13 | private AccountService accountService; 14 | 15 | @Transactional 16 | public boolean transfer(int fromId, int toId, double value){ 17 | Account from = accountService.getAccount(fromId); 18 | from.setBalance(from.getBalance().subtract(BigDecimal.valueOf(value))); 19 | accountService.updateAccout(from); 20 | Account to = accountService.getAccount(toId); 21 | to.setBalance(to.getBalance().add(BigDecimal.valueOf(value))); 22 | accountService.updateAccout(to); 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /springtransaction/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.com.yyh=debug 2 | 3 | #为空的属性在转换时忽略掉 4 | spring.jackson.default-property-inclusion=non_empty 5 | 6 | #将数据库中下划线命名风格自动转换为驼峰式命名风格 7 | mybatis.configuration.map-underscore-to-camel-case=true 8 | mybatis.configuration.default-fetch-size=100 9 | mybatis.configuration.default-statement-timeout=30 10 | mybatis.configuration.auto-mapping-unknown-column-behavior=WARNING 11 | mybatis.mapper-locations=classpath:mapper/*Mapper.xml 12 | mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl -------------------------------------------------------------------------------- /springtransaction/src/main/resources/datasource.properties: -------------------------------------------------------------------------------- 1 | #=============data source============= 2 | connection.username=root 3 | connection.password=123456 4 | connection.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC 5 | connection.driverClassName =com.mysql.cj.jdbc.Driver 6 | #初始连接数 default=3 7 | connection.initialPoolSize=5 8 | #连接池获取增量 default=3 9 | connection.acquireIncrement=2 10 | #获取连接失败重试次数 default=30 11 | connection.acquireRetryAttempts=10 12 | #获取连接延迟时间 单位毫秒 default=1000 13 | connection.acquireRetryDelay=500 14 | #连接关闭时不自动提交 default=false ,需要手动commit 15 | connection.autoCommitOnClose=false 16 | #连接池最大连接数 default=15 17 | connection.maxPoolSize=30 18 | #连接池最小连接数 default=3 19 | connection.minPoolSize=5 20 | #ps:还有更多,请查看官网文档:http://www.mchange.com/projects/c3p0/#configuration 21 | #默认配置看com.mchange.v2.c3p0.impl.C3P0Defaults这个类 22 | -------------------------------------------------------------------------------- /springtransaction/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | %d{MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | /Users/lhy/java-study/java_framework_learn/springmybatis/log/warn.%d{yyyy-MM-dd}.log 21 | 22 | 99 23 | true 24 | 25 | 26 | 27 | 28 | INFO 29 | ACCEPT 30 | DENY 31 | 32 | 33 | %d{HH:mm:ss.SSS} %-5level %logger{35} - %msg%n 34 | 35 | 36 | 37 | 38 | 39 | 40 | /Users/lhy/java-study/java_framework_learn/springmybatis/log/error.%d{yyyy-MM-dd}.log 41 | 99 42 | true 43 | 44 | 45 | 46 | 47 | 48 | ERROR 49 | 50 | 51 | %d{HH:mm:ss.SSS} %-5level %logger{35} - %msg%n 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /springtransaction/src/main/resources/mapper/AccountMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | id, user_id, name, balance 12 | 13 | 14 | select 15 | 16 | from account 17 | where id = #{id,jdbcType=INTEGER} 18 | 19 | 20 | delete from account 21 | where id = #{id,jdbcType=INTEGER} 22 | 23 | 24 | insert into account (id, user_id, name, 25 | balance) 26 | values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 27 | #{balance,jdbcType=DECIMAL}) 28 | 29 | 30 | insert into account 31 | 32 | 33 | id, 34 | 35 | 36 | user_id, 37 | 38 | 39 | name, 40 | 41 | 42 | balance, 43 | 44 | 45 | 46 | 47 | #{id,jdbcType=INTEGER}, 48 | 49 | 50 | #{userId,jdbcType=INTEGER}, 51 | 52 | 53 | #{name,jdbcType=VARCHAR}, 54 | 55 | 56 | #{balance,jdbcType=DECIMAL}, 57 | 58 | 59 | 60 | 61 | update account 62 | 63 | 64 | user_id = #{userId,jdbcType=INTEGER}, 65 | 66 | 67 | name = #{name,jdbcType=VARCHAR}, 68 | 69 | 70 | balance = #{balance,jdbcType=DECIMAL}, 71 | 72 | 73 | where id = #{id,jdbcType=INTEGER} 74 | 75 | 76 | update account 77 | set user_id = #{userId,jdbcType=INTEGER}, 78 | name = #{name,jdbcType=VARCHAR}, 79 | balance = #{balance,jdbcType=DECIMAL} 80 | where id = #{id,jdbcType=INTEGER} 81 | 82 | -------------------------------------------------------------------------------- /springtransaction/src/main/resources/mapper/ClUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | id, " name", age, phone, modify_time 13 | 14 | 15 | select 16 | 17 | from cl_user 18 | where id = #{id,jdbcType=INTEGER} 19 | 20 | 21 | delete from cl_user 22 | where id = #{id,jdbcType=INTEGER} 23 | 24 | 25 | insert into cl_user (id, " name", age, 26 | phone, modify_time) 27 | values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 28 | #{phone,jdbcType=VARCHAR}, #{modifyTime,jdbcType=TIMESTAMP}) 29 | 30 | 31 | insert into cl_user 32 | 33 | 34 | id, 35 | 36 | 37 | " name", 38 | 39 | 40 | age, 41 | 42 | 43 | phone, 44 | 45 | 46 | modify_time, 47 | 48 | 49 | 50 | 51 | #{id,jdbcType=INTEGER}, 52 | 53 | 54 | #{name,jdbcType=VARCHAR}, 55 | 56 | 57 | #{age,jdbcType=INTEGER}, 58 | 59 | 60 | #{phone,jdbcType=VARCHAR}, 61 | 62 | 63 | #{modifyTime,jdbcType=TIMESTAMP}, 64 | 65 | 66 | 67 | 68 | update cl_user 69 | 70 | 71 | " name" = #{name,jdbcType=VARCHAR}, 72 | 73 | 74 | age = #{age,jdbcType=INTEGER}, 75 | 76 | 77 | phone = #{phone,jdbcType=VARCHAR}, 78 | 79 | 80 | modify_time = #{modifyTime,jdbcType=TIMESTAMP}, 81 | 82 | 83 | where id = #{id,jdbcType=INTEGER} 84 | 85 | 86 | update cl_user 87 | set " name" = #{name,jdbcType=VARCHAR}, 88 | age = #{age,jdbcType=INTEGER}, 89 | phone = #{phone,jdbcType=VARCHAR}, 90 | modify_time = #{modifyTime,jdbcType=TIMESTAMP} 91 | where id = #{id,jdbcType=INTEGER} 92 | 93 | -------------------------------------------------------------------------------- /springtransaction/src/main/test/create_data/MyTest.java: -------------------------------------------------------------------------------- 1 | package create_data; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.sql.Connection; 5 | import java.sql.DriverManager; 6 | import java.sql.PreparedStatement; 7 | import java.sql.SQLException; 8 | import java.util.Date; 9 | import java.util.Random; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | public class MyTest { 14 | public static void main(String[] args) throws ClassNotFoundException, SQLException { 15 | final String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; 16 | final String name = "com.mysql.cj.jdbc.Driver"; 17 | final String user = "root"; 18 | final String password = "123456"; 19 | Connection conn = null; 20 | Class z = Class.forName(name);//指定连接类型 21 | conn = DriverManager.getConnection(url, user, password);//获取连接 22 | if (conn!=null) { 23 | System.out.println("获取连接成功"); 24 | insert(conn); 25 | }else { 26 | System.out.println("获取连接失败"); 27 | } 28 | } 29 | 30 | public static void insert(Connection conn) { 31 | // 开始时间 32 | Long begin = new Date().getTime(); 33 | // sql前缀 34 | 35 | 36 | String prefix = "INSERT INTO user_info (`phone`,`name`,`eduction`,`age`,`sex`,`id_no`) VALUES "; 37 | String sql = null; 38 | try { 39 | // 保存sql后缀 40 | StringBuffer suffix = new StringBuffer(); 41 | // 设置事务为非自动提交 42 | conn.setAutoCommit(false); 43 | // 比起st,pst会更好些 44 | // 外层循环,总提交事务次数 45 | PreparedStatement pst = null; 46 | String value = "('%s','%s','%s',%d,'%s','%s'),"; 47 | IdCardGenerator g = new IdCardGenerator(); 48 | for (int i = 1; i <= 100; i++) { 49 | // 第j次提交步长 50 | for (int j = 1; j <= 50000; j++) { 51 | // 构建SQL后缀 52 | String phone = getTel(); 53 | String name = getName(); 54 | String eduction = getEduction(); 55 | String sex = random.nextBoolean() ? "男" : "女"; 56 | String id_no = g.generate(); 57 | int age = g.getAgeByCertId(id_no); 58 | suffix.append(String.format(value,phone,name,eduction,age,sex,id_no)); 59 | } 60 | // 构建完整SQL 61 | sql = prefix + suffix.substring(0, suffix.length() - 1); 62 | pst = (PreparedStatement) conn.prepareStatement(sql);//准备执行语句 63 | // 添加执行SQL 64 | pst.addBatch(sql); 65 | // 执行操作 66 | pst.executeBatch(); 67 | // 提交事务 68 | conn.commit(); 69 | // 清空上一次添加的数据 70 | suffix = new StringBuffer(); 71 | } 72 | // 头等连接 73 | pst.close(); 74 | conn.close(); 75 | } catch (SQLException e) { 76 | System.out.println(sql); 77 | e.printStackTrace(); 78 | } 79 | // 结束时间 80 | Long end = new Date().getTime(); 81 | // 耗时 82 | System.out.println("1000万条数据插入花费时间 : " + (end - begin) / 1000 + " s"); 83 | System.out.println("插入完成"); 84 | } 85 | 86 | /** 87 | * 返回手机号码 88 | */ 89 | private static String[] telFirst="134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(","); 90 | private static String getTel() { 91 | int index=getNum(0,telFirst.length-1); 92 | String first=telFirst[index]; 93 | String second=String.valueOf(getNum(1,888)+10000).substring(1); 94 | String third=String.valueOf(getNum(1,9100)+10000).substring(1); 95 | return first+second+third; 96 | } 97 | public static int getNum(int start,int end) { 98 | return (int)(Math.random()*(end-start+1)+start); 99 | } 100 | 101 | private final static Random random = new Random(); 102 | 103 | private static String[] firstNames= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许", 104 | "何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎", 105 | "鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷", 106 | "罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和", 107 | "穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒", 108 | "屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟", 109 | "徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应", 110 | "宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀", 111 | "羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山", 112 | "谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景", 113 | "詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠", 114 | "蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却", 115 | "璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习", 116 | "宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄", 117 | "阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空", 118 | "曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉", 119 | "督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨", 120 | "哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼", 121 | "疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨", 122 | "木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾", 123 | "闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正", 124 | "濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇", 125 | "南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生", 126 | "梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门", 127 | "毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"}; 128 | 129 | 130 | public static String getName(){ 131 | int length = 1 + random.nextInt(2); 132 | StringBuilder sb = new StringBuilder(); 133 | sb.append(firstNames[random.nextInt(firstNames.length)]); 134 | for (int i = 0 ; i < length ; i++){ 135 | sb.append(getChinese()); 136 | } 137 | return sb.toString() ; 138 | } 139 | 140 | public static String getChinese() { 141 | String str = null; 142 | int highPos, lowPos; 143 | Random random = new Random(); 144 | highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字 145 | random = new Random(); 146 | lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列 147 | 148 | byte[] bArr = new byte[2]; 149 | bArr[0] = (new Integer(highPos)).byteValue(); 150 | bArr[1] = (new Integer(lowPos)).byteValue(); 151 | try { 152 | str = new String(bArr, "GB2312"); //区位码组合成汉字 153 | } catch (UnsupportedEncodingException e) { 154 | e.printStackTrace(); 155 | } 156 | return str; 157 | } 158 | 159 | 160 | 161 | private static String []eductions = "小学|初级中学|高级中学|大学专科|大学本科|硕士研究生|博士研究生|其他".split("\\|"); 162 | public static String getEduction(){ 163 | return eductions[random.nextInt(eductions.length-1)]; 164 | } 165 | 166 | public static String stringToUnicode(String s) { 167 | try { 168 | StringBuffer out = new StringBuffer(""); 169 | //直接获取字符串的unicode二进制 170 | byte[] bytes = s.getBytes("unicode"); 171 | //然后将其byte转换成对应的16进制表示即可 172 | for (int i = 0; i < bytes.length - 1; i += 2) { 173 | out.append("\\u"); 174 | String str = Integer.toHexString(bytes[i + 1] & 0xff); 175 | for (int j = str.length(); j < 2; j++) { 176 | out.append("0"); 177 | } 178 | String str1 = Integer.toHexString(bytes[i] & 0xff); 179 | out.append(str1); 180 | out.append(str); 181 | } 182 | return out.toString(); 183 | } catch (UnsupportedEncodingException e) { 184 | e.printStackTrace(); 185 | return null; 186 | } 187 | } 188 | 189 | 190 | public static String unicodeToString(String str) { 191 | 192 | Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))"); 193 | Matcher matcher = pattern.matcher(str); 194 | char ch; 195 | while (matcher.find()) { 196 | //group 6728 197 | String group = matcher.group(2); 198 | //ch:'木' 26408 199 | ch = (char) Integer.parseInt(group, 16); 200 | //group1 \u6728 201 | String group1 = matcher.group(1); 202 | str = str.replace(group1, ch + ""); 203 | } 204 | return str; 205 | 206 | } 207 | } 208 | 209 | -------------------------------------------------------------------------------- /websocketDemo/client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | websocketDemo 7 | com.yyh 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | client 13 | 14 | 15 | com.yyh 16 | server 17 | 1.0-SNAPSHOT 18 | compile 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /websocketDemo/client/src/main/java/com/yyh/client/MsgWebSocketClient.java: -------------------------------------------------------------------------------- 1 | package com.yyh.client; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.yyh.server.message.Greeting; 6 | import com.yyh.server.message.HelloMessage; 7 | import org.springframework.messaging.converter.MappingJackson2MessageConverter; 8 | import org.springframework.messaging.converter.StringMessageConverter; 9 | import org.springframework.messaging.simp.stomp.StompFrameHandler; 10 | import org.springframework.messaging.simp.stomp.StompHeaders; 11 | import org.springframework.messaging.simp.stomp.StompSession; 12 | import org.springframework.messaging.simp.stomp.StompSessionHandler; 13 | import org.springframework.scheduling.TaskScheduler; 14 | import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; 15 | import org.springframework.util.concurrent.ListenableFuture; 16 | import org.springframework.web.socket.client.standard.StandardWebSocketClient; 17 | import org.springframework.web.socket.messaging.WebSocketStompClient; 18 | import org.springframework.web.socket.sockjs.client.SockJsClient; 19 | import org.springframework.web.socket.sockjs.client.Transport; 20 | import org.springframework.web.socket.sockjs.client.WebSocketTransport; 21 | import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec; 22 | 23 | 24 | import java.util.Collections; 25 | import java.util.List; 26 | import java.util.concurrent.ExecutionException; 27 | 28 | /** 29 | * @author lhy 30 | * @Date 2018/10/10 14:53 31 | * @JDK 1.7 32 | * @Description TODO 33 | */ 34 | public class MsgWebSocketClient { 35 | public static void main(String[] args) throws ExecutionException, InterruptedException, JsonProcessingException { 36 | 37 | Transport webSocketTransport = new WebSocketTransport(new StandardWebSocketClient()); 38 | List transports = Collections.singletonList(webSocketTransport); 39 | 40 | SockJsClient sockJsClient = new SockJsClient(transports); 41 | sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec()); 42 | 43 | WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient); 44 | stompClient.setMessageConverter(new MappingJackson2MessageConverter()); 45 | String url = "ws://127.0.0.1:8080/gs-guide-websocket"; 46 | 47 | TaskScheduler taskScheduler = new ConcurrentTaskScheduler(); 48 | stompClient.setTaskScheduler(taskScheduler); 49 | 50 | StompSessionHandler stompFrameHandler = new MyWebSocketHandler(); 51 | ListenableFuture f = stompClient.connect(url, stompFrameHandler, "localhost", 8080); 52 | 53 | StompSession stompSession = f.get(); 54 | stompSession.setAutoReceipt(true); 55 | 56 | HelloMessage helloMessage = new HelloMessage(); 57 | helloMessage.setName("cc"); 58 | 59 | System.out.println("Subscribing to greeting topic using session " + stompSession); 60 | 61 | stompSession.send("/app/hello",helloMessage); 62 | 63 | stompSession.subscribe("/topic/greetings", stompFrameHandler); 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /websocketDemo/client/src/main/java/com/yyh/client/MyWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package com.yyh.client; 2 | 3 | import com.yyh.server.message.Greeting; 4 | import org.springframework.messaging.simp.stomp.StompCommand; 5 | import org.springframework.messaging.simp.stomp.StompHeaders; 6 | import org.springframework.messaging.simp.stomp.StompSession; 7 | import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; 8 | 9 | import java.lang.reflect.Type; 10 | 11 | 12 | /** 13 | * @author lhy 14 | * @Date 2018/10/8 9:53 15 | * @JDK 1.7 16 | * @Description TODO 17 | */ 18 | public class MyWebSocketHandler extends StompSessionHandlerAdapter { 19 | public MyWebSocketHandler() { 20 | super(); 21 | } 22 | 23 | @Override 24 | public Type getPayloadType(StompHeaders headers) { 25 | return Greeting.class; 26 | } 27 | 28 | @Override 29 | public void handleFrame(StompHeaders headers, Object payload) { 30 | Greeting greeting = (Greeting) payload; 31 | System.out.println("来自服务器得到消息 : " + greeting.getContent()); 32 | } 33 | 34 | @Override 35 | public void afterConnected(StompSession session, StompHeaders connectedHeaders) { 36 | super.afterConnected(session, connectedHeaders); 37 | } 38 | 39 | @Override 40 | public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) { 41 | exception.printStackTrace(); 42 | } 43 | 44 | @Override 45 | public void handleTransportError(StompSession session, Throwable exception) { 46 | super.handleTransportError(session, exception); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /websocketDemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.yyh 8 | websocketDemo 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | server 13 | client 14 | 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-dependencies 21 | 2.0.0.RELEASE 22 | pom 23 | import 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-websocket 37 | 38 | 39 | 40 | org.webjars 41 | webjars-locator-core 42 | 43 | 44 | org.webjars 45 | sockjs-client 46 | 1.0.2 47 | 48 | 49 | org.webjars 50 | stomp-websocket 51 | 2.3.3 52 | 53 | 54 | org.webjars 55 | bootstrap 56 | 3.3.7 57 | 58 | 59 | org.webjars 60 | jquery 61 | 3.1.0 62 | 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-starter-test 67 | test 68 | 69 | 70 | 71 | org.projectlombok 72 | lombok 73 | 1.18.0 74 | 75 | 76 | 77 | 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-compiler-plugin 82 | 3.0 83 | 84 | 1.8 85 | 1.8 86 | 87 | 88 | 89 | 90 | org.springframework.boot 91 | spring-boot-maven-plugin 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /websocketDemo/server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | websocketDemo 7 | com.yyh 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | server 13 | 14 | 15 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/java/com/yyh/server/Application.java: -------------------------------------------------------------------------------- 1 | package com.yyh.server; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author lhy 8 | * @Date 2018/9/30 15:29 9 | * @JDK 1.7 10 | * @Description TODO 11 | */ 12 | @SpringBootApplication 13 | public class Application { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(Application.class, args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/java/com/yyh/server/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.yyh.server.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 9 | 10 | /** 11 | * @author lhy 12 | * @Date 2018/9/30 15:14 13 | * @JDK 1.7 14 | * @Description TODO 15 | */ 16 | @Configuration 17 | @EnableWebSocketMessageBroker 18 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 19 | 20 | @Override 21 | public void configureMessageBroker(MessageBrokerRegistry config) { 22 | config.enableSimpleBroker("/topic"); 23 | config.setApplicationDestinationPrefixes("/app"); 24 | } 25 | 26 | @Override 27 | public void registerStompEndpoints(StompEndpointRegistry registry) { 28 | registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*") 29 | .withSockJS() 30 | ; 31 | } 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/java/com/yyh/server/controller/GreetingController.java: -------------------------------------------------------------------------------- 1 | package com.yyh.server.controller; 2 | 3 | import com.yyh.server.message.Greeting; 4 | import com.yyh.server.message.HelloMessage; 5 | import org.springframework.messaging.handler.annotation.MessageMapping; 6 | import org.springframework.messaging.handler.annotation.SendTo; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.util.HtmlUtils; 9 | 10 | /** 11 | * @author lhy 12 | * @Date 2018/9/30 15:22 13 | * @JDK 1.7 14 | * @Description TODO 15 | */ 16 | @Controller 17 | public class GreetingController { 18 | 19 | @MessageMapping("/hello") 20 | @SendTo("/topic/greetings") 21 | public Greeting greeting(HelloMessage message) throws Exception { 22 | Thread.sleep(1000); // simulated delay 23 | System.out.println(message); 24 | return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/java/com/yyh/server/message/Greeting.java: -------------------------------------------------------------------------------- 1 | package com.yyh.server.message; 2 | 3 | /** 4 | * @author lhy 5 | * @Date 2018/9/30 15:21 6 | * @JDK 1.7 7 | * @Description TODO 8 | */ 9 | public class Greeting { 10 | private String content; 11 | 12 | public Greeting() { 13 | } 14 | 15 | public Greeting(String content) { 16 | this.content = content; 17 | } 18 | 19 | public String getContent() { 20 | return content; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/java/com/yyh/server/message/HelloMessage.java: -------------------------------------------------------------------------------- 1 | package com.yyh.server.message; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author lhy 7 | * @Date 2018/9/30 15:18 8 | * @JDK 1.7 9 | * @Description TODO 10 | */ 11 | public class HelloMessage implements Serializable { 12 | 13 | private String name; 14 | 15 | public HelloMessage() { 16 | } 17 | 18 | public HelloMessage(String name) { 19 | this.name = name; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /websocketDemo/server/src/main/resources/static/app.js: -------------------------------------------------------------------------------- 1 | var stompClient = null; 2 | 3 | function setConnected(connected) { 4 | $("#connect").prop("disabled", connected); 5 | $("#disconnect").prop("disabled", !connected); 6 | if (connected) { 7 | $("#conversation").show(); 8 | } 9 | else { 10 | $("#conversation").hide(); 11 | } 12 | $("#greetings").html(""); 13 | } 14 | 15 | function connect() { 16 | var socket = new SockJS('/gs-guide-websocket'); 17 | stompClient = Stomp.over(socket); 18 | stompClient.connect({}, function (frame) { 19 | setConnected(true); 20 | console.log('Connected: ' + frame); 21 | stompClient.subscribe('/topic/greetings', function (greeting) { 22 | showGreeting(JSON.parse(greeting.body).content); 23 | }); 24 | }); 25 | } 26 | 27 | function disconnect() { 28 | if (stompClient !== null) { 29 | stompClient.disconnect(); 30 | } 31 | setConnected(false); 32 | console.log("Disconnected"); 33 | } 34 | 35 | function sendName() { 36 | stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()})); 37 | } 38 | 39 | function showGreeting(message) { 40 | $("#greetings").append("" + message + ""); 41 | } 42 | 43 | $(function () { 44 | $("form").on('submit', function (e) { 45 | e.preventDefault(); 46 | }); 47 | $( "#connect" ).click(function() { connect(); }); 48 | $( "#disconnect" ).click(function() { disconnect(); }); 49 | $( "#send" ).click(function() { sendName(); }); 50 | }); -------------------------------------------------------------------------------- /websocketDemo/server/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello WebSocket 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Seems your browser doesn't support Javascript! Websocket relies on Javascript being 14 | enabled. Please enable 15 | Javascript and reload this page! 16 | 17 | 18 | 19 | 20 | 21 | WebSocket connection: 22 | Connect 23 | Disconnect 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | What is your name? 32 | 33 | 34 | Send 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | Greetings 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | --------------------------------------------------------------------------------
12 | 欢迎你! 13 |