├── .gitignore ├── ActivemqDemo2 ├── .gitignore ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── activemq │ │ │ └── activemq │ │ │ ├── ActivemqApplication.java │ │ │ ├── Queue │ │ │ ├── Consumer.java │ │ │ ├── Consumer2.java │ │ │ ├── MqConfig.java │ │ │ └── ProducerPoint.java │ │ │ ├── QueueAndTopic │ │ │ ├── ActiveMQConfig.java │ │ │ └── Consumer5.java │ │ │ └── Topic │ │ │ ├── Consumer3.java │ │ │ ├── Consumer4.java │ │ │ └── ProducerTopic.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── activemq │ └── activemq │ └── ActivemqApplicationTests.java ├── README.md ├── SpringBoot-RabbitMq ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ ├── one2one │ │ │ ├── Receiving.java │ │ │ └── Send.java │ │ │ ├── publish │ │ │ ├── Rece1.java │ │ │ ├── Rece2.java │ │ │ └── Send.java │ │ │ ├── route │ │ │ ├── Rece1.java │ │ │ ├── Rece2.java │ │ │ └── Send.java │ │ │ ├── topic │ │ │ ├── Rece1.java │ │ │ ├── Rece2.java │ │ │ ├── Rece3.java │ │ │ └── Send.java │ │ │ └── work │ │ │ ├── Rece1.java │ │ │ ├── Rece2.java │ │ │ └── Send.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── DemoApplicationTests.java ├── SpringBoot-Redis ├── SpringBoot-Redisson │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── demo │ │ │ │ └── redisson │ │ │ │ ├── RedissonApplication.java │ │ │ │ ├── config │ │ │ │ ├── DistributedLocker.java │ │ │ │ ├── RedisDistributedLocker.java │ │ │ │ ├── RedisLockUtil.java │ │ │ │ └── RedissonConfig.java │ │ │ │ └── controller │ │ │ │ └── RedissonController.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── demo │ │ └── redisson │ │ └── RedissonApplicationTests.java ├── Springboot-Redis-SETEX │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── demo │ │ │ │ ├── DemoApplication.java │ │ │ │ ├── controller │ │ │ │ ├── RedisRedLockContoller.java │ │ │ │ └── RedisSetexContoller.java │ │ │ │ └── redis │ │ │ │ ├── config │ │ │ │ └── DistributedLockConfig.java │ │ │ │ ├── pojo │ │ │ │ └── Lock.java │ │ │ │ └── redlock │ │ │ │ ├── AquiredLockWorker.java │ │ │ │ ├── DistributedLocker.java │ │ │ │ ├── RedisLocker.java │ │ │ │ ├── RedissonConnector.java │ │ │ │ └── UnableToAquireLockException.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── example │ │ └── demo │ │ └── DemoApplicationTests.java └── springBoot-redis │ └── SpringBoot-Redis │ ├── redis-cluster │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── rediscluster │ │ │ │ └── RedisClusterApplication.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── example │ │ └── rediscluster │ │ └── RedisClusterApplicationTests.java │ └── sentinel-redis │ ├── pom.xml │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── sentinelredis │ │ │ ├── RedisCacheConfig.java │ │ │ └── SentinelRedisApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── sentinelredis │ └── SentinelRedisApplicationTests.java ├── SpringBoot-dubbo └── 代码示例 ├── SpringBoot-quartz ├── .gitignore ├── HELP.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ ├── cifg │ │ │ ├── Job.java │ │ │ ├── QuartzConfig.java │ │ │ └── TestJob.java │ │ │ └── controller │ │ │ └── QuartzController.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── DemoApplicationTests.java ├── SpringBoot-vue-crud ├── .gitignore ├── HELP.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── vue │ │ │ └── demo │ │ │ └── vuedemo │ │ │ ├── VuedemoApplication.java │ │ │ ├── common │ │ │ ├── PageQuery.java │ │ │ └── ReturnMessage.java │ │ │ ├── controller │ │ │ ├── LoginController.java │ │ │ └── StudentController.java │ │ │ ├── dao │ │ │ └── StudentDao.java │ │ │ ├── pojo │ │ │ └── Student.java │ │ │ └── service │ │ │ ├── StudentService.java │ │ │ └── StudentServiceImpl.java │ └── resources │ │ ├── application.yml │ │ ├── mapper │ │ └── StudentMapper.xml │ │ └── sql │ │ └── student.sql │ └── test │ └── java │ └── com │ └── vue │ └── demo │ └── vuedemo │ └── VuedemoApplicationTests.java ├── SpringBootDuridDemo ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── MysqlConfig2Databases │ │ │ ├── MultiDataSourceConfig.java │ │ │ ├── OneDataSourceConfig.java │ │ │ └── SecondDataSourceConfig.java │ │ │ ├── SpringBootDemoApplication.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── mapper │ │ │ ├── one │ │ │ │ └── User1Mapper.java │ │ │ └── second │ │ │ │ └── User2Mapper.java │ │ │ └── pojo │ │ │ └── User.java │ └── resources │ │ ├── application.properties │ │ ├── mapper │ │ ├── config │ │ │ └── mybatis-config.xml │ │ ├── one │ │ │ └── User1Mapper.xml │ │ └── second │ │ │ └── User2Mapper.xml │ │ └── sql │ │ └── user.sql │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── SpringBootDemoApplicationTests.java ├── Springboot-MongodbDemo ├── .gitignore ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── mongodbdemo │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ ├── m1dao │ │ │ └── MongoDao1.java │ │ │ ├── m2dao │ │ │ └── MongoDao2.java │ │ │ └── test │ │ │ ├── MongoConfig1.java │ │ │ ├── MongoConfig2.java │ │ │ ├── MultipleMongoConfig.java │ │ │ ├── MultipleMongoProperties.java │ │ │ └── User.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── mongodbdemo │ └── demo │ └── DemoApplicationTests.java ├── Springboot-Redis-SETEX ├── .gitignore └── mvnw.cmd ├── spring-session ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springsession │ │ │ └── demo │ │ │ ├── Config │ │ │ └── SessionConfig.java │ │ │ ├── DemoApplication.java │ │ │ └── jpa │ │ │ └── StudentController.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── springsession │ └── demo │ └── DemoApplicationTests.java ├── springBoot-redis └── SpringBoot-Redis │ ├── README.md │ ├── redis-cluster │ └── .gitignore │ └── sentinel-redis │ └── .gitignore ├── springboot-atomikos ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootatomikos │ │ │ ├── SpringbootatomikosApplication.java │ │ │ ├── config │ │ │ ├── one │ │ │ │ └── MyBatisConfig1.java │ │ │ ├── pojo │ │ │ │ ├── DBConfig1.java │ │ │ │ └── DBConfig2.java │ │ │ └── two │ │ │ │ └── MyBatisConfig2.java │ │ │ ├── mapper │ │ │ ├── one │ │ │ │ └── UserMapper1.java │ │ │ └── two │ │ │ │ └── UserMapper2.java │ │ │ ├── pojo │ │ │ └── User.java │ │ │ └── service │ │ │ └── UserService.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── springbootatomikos │ └── SpringbootatomikosApplicationTests.java ├── springboot-handlerinterceptor ├── .gitignore ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springboothandlerinterceptor │ │ │ ├── SpringbootHandlerinterceptorApplication.java │ │ │ ├── config │ │ │ ├── MyHandlerInterceptor.java │ │ │ ├── MyInterceptorConfig.java │ │ │ └── MyInterceptorConfig2.java │ │ │ ├── controller │ │ │ └── TestController.java │ │ │ └── other │ │ │ └── User.java │ └── resources │ │ ├── application.properties │ │ └── static │ │ ├── a.txt │ │ ├── css │ │ └── a.css │ │ └── index.html │ └── test │ └── java │ └── com │ └── example │ └── springboothandlerinterceptor │ └── SpringbootHandlerinterceptorApplicationTests.java ├── springboot-listener-demo ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootlistenerdemo │ │ │ ├── SpringbootListenerDemoApplication.java │ │ │ ├── bean │ │ │ └── User.java │ │ │ ├── controller │ │ │ └── TestController.java │ │ │ ├── listener │ │ │ ├── MyEvent.java │ │ │ ├── MyEventListener.java │ │ │ ├── MyHttpSessionListener.java │ │ │ ├── MyServletContextListener.java │ │ │ └── MyServletRequestListener.java │ │ │ └── services │ │ │ └── UserService.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── springbootlistenerdemo │ └── SpringbootListenerDemoApplicationTests.java ├── springbootCrudDemo ├── README.md └── springBootDemo │ ├── mvnw │ ├── mvnw.cmd │ ├── pom.xml │ ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── demo │ │ │ │ ├── SpringBootDemoApplication.java │ │ │ │ ├── common │ │ │ │ └── beans.java │ │ │ │ ├── controller │ │ │ │ └── userController.java │ │ │ │ ├── fiflter │ │ │ │ └── fiflterTest.java │ │ │ │ ├── mapper │ │ │ │ └── userMapper.java │ │ │ │ ├── pojo │ │ │ │ └── User.java │ │ │ │ ├── service │ │ │ │ └── userService.java │ │ │ │ └── serviceImp │ │ │ │ └── userServiceImp.java │ │ └── resources │ │ │ ├── NewFile.xml │ │ │ ├── application.properties │ │ │ ├── mapper │ │ │ ├── config │ │ │ │ └── mybatis-config.xml │ │ │ └── userMapper.xml │ │ │ └── sql │ │ │ └── user.sql │ └── test │ │ └── java │ │ └── com │ │ └── example │ │ └── demo │ │ └── SpringBootDemoApplicationTests.java │ └── target │ ├── classes │ ├── NewFile.xml │ ├── application.properties │ ├── mapper │ │ ├── config │ │ │ └── mybatis-config.xml │ │ └── userMapper.xml │ └── sql │ │ └── user.sql │ └── m2e-wtp │ └── web-resources │ └── META-INF │ ├── MANIFEST.MF │ └── maven │ └── com.example │ └── springBootDemo │ ├── pom.properties │ └── pom.xml └── springsecuritydemo ├── .gitignore ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── springsecuritydemo │ │ ├── SpringsecuritydemoApplication.java │ │ ├── config │ │ └── SecurityConfig.java │ │ └── controller │ │ └── SecurityController.java └── resources │ ├── application.properties │ ├── static │ ├── a.css │ └── css │ │ └── main.css │ └── templates │ ├── admin.html │ ├── content.html │ ├── index.html │ └── login.html └── test └── java └── com └── example └── springsecuritydemo └── SpringsecuritydemoApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /ActivemqDemo2/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /ActivemqDemo2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.example.Activemq 12 | activemq 13 | 0.0.1-SNAPSHOT 14 | activemq 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-activemq 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-devtools 36 | runtime 37 | true 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | true 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-maven-plugin 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/ActivemqApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ActivemqApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ActivemqApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Queue/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Queue; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * 创建消费者 8 | *

9 | * 使用注解 @JmsListener(destination = "neo.queue"), 10 | * 表示此方法监控了名为 neo.queue 的队列。 11 | * 当队列 neo.queue 中有消息发送时会触发此方法的执行,text 为消息内容。 12 | **/ 13 | @Component 14 | public class Consumer { 15 | 16 | @JmsListener(destination = "neo.queue") 17 | public void receiveQueue(String text) { 18 | System.out.println(" Consumer 接受到的消息是 : " + text); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Queue/Consumer2.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Queue; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * 创建消费者 8 | *

9 | * 使用注解 @JmsListener(destination = "neo.queue"), 10 | * 表示此方法监控了名为 neo.queue 的队列。 11 | * 当队列 neo.queue 中有消息发送时会触发此方法的执行,text 为消息内容。 12 | **/ 13 | @Component 14 | public class Consumer2 { 15 | 16 | @JmsListener(destination = "neo.queue") 17 | public void receiveQueue(String text) { 18 | System.out.println(" Consumer2 接受到的消息是 : " + text); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Queue/MqConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Queue; 2 | 3 | 4 | import org.apache.activemq.command.ActiveMQQueue; 5 | import org.apache.activemq.command.ActiveMQTopic; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import javax.jms.Queue; 10 | import javax.jms.Topic; 11 | 12 | 13 | /** 14 | * 创建队列 15 | * 队列发送的消息,只能被一个消费者接收。 16 | */ 17 | 18 | @Configuration 19 | public class MqConfig { 20 | @Bean 21 | public Queue queue() { 22 | return new ActiveMQQueue("neo.queue"); 23 | } 24 | 25 | @Bean 26 | public Topic topic() { 27 | return new ActiveMQTopic("topic1"); 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Queue/ProducerPoint.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Queue; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jms.core.JmsMessagingTemplate; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.jms.Queue; 8 | 9 | /** 10 | * @description: 11 | * @author: 消息生产者 12 | * @create: 创建一个消息的生产者: 13 | **/ 14 | 15 | @Component 16 | public class ProducerPoint { 17 | 18 | //JmsMessagingTemplate 是 Spring 提供发送消息的工具类,使用 JmsMessagingTemplate 和创建好的 queue 对消息进行发送。 19 | @Autowired 20 | private JmsMessagingTemplate jmsMessagingTemplate; 21 | 22 | @Autowired 23 | private Queue queue; 24 | 25 | public void sendQueue(String msg) { 26 | System.out.println(" 发送消息为 :" + msg); 27 | this.jmsMessagingTemplate.convertAndSend(this.queue, msg); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/QueueAndTopic/ActiveMQConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.QueueAndTopic; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.jms.annotation.EnableJms; 6 | import org.springframework.jms.config.DefaultJmsListenerContainerFactory; 7 | import org.springframework.jms.config.JmsListenerContainerFactory; 8 | 9 | import javax.jms.ConnectionFactory; 10 | 11 | /** 12 | * 在同一项目中既支持队列模式也支持广播模式, 13 | * 可以通过 DefaultJmsListenerContainerFactory 创建自定义的 JmsListenerContainerFactory 实例, 14 | * 之后在 @JmsListener 注解中通过 containerFactory 属性引用它。 15 | **/ 16 | 17 | @Configuration 18 | @EnableJms 19 | public class ActiveMQConfig { 20 | 21 | @Bean("queueListenerFactory") 22 | public JmsListenerContainerFactory queueListenerFactory(ConnectionFactory connectionFactory) { 23 | DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); 24 | factory.setConnectionFactory(connectionFactory); 25 | factory.setPubSubDomain(false); 26 | return factory; 27 | } 28 | 29 | @Bean("topicListenerFactory") 30 | public JmsListenerContainerFactory topicListenerFactory(ConnectionFactory connectionFactory) { 31 | DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); 32 | factory.setConnectionFactory(connectionFactory); 33 | factory.setPubSubDomain(true); 34 | return factory; 35 | } 36 | } -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/QueueAndTopic/Consumer5.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.QueueAndTopic; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jms.annotation.JmsListener; 5 | import org.springframework.jms.core.JmsMessagingTemplate; 6 | import org.springframework.messaging.Message; 7 | import org.springframework.messaging.MessageHeaders; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.jms.Queue; 11 | 12 | /** 13 | * 14 | **/ 15 | @Component 16 | public class Consumer5 { 17 | 18 | @JmsListener(destination = "neo.queue", containerFactory = "queueListenerFactory") 19 | public void receiveQueue(String text) { 20 | System.out.println("Consumer5 queue msg : " + text); 21 | } 22 | 23 | @JmsListener(destination = "topic1", containerFactory = "topicListenerFactory") 24 | public void receiveTopic1(String text) { 25 | System.out.println("Consumer5 receiveTopic1 msg : " + text); 26 | } 27 | 28 | @JmsListener(destination = "topic1", containerFactory = "topicListenerFactory") 29 | public void receiveTopic2(String text) { 30 | System.out.println("Consumer5 receiveTopic2 msg : " + text); 31 | } 32 | } -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Topic/Consumer3.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Topic; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * 创建消费者 8 | *

9 | * 使用注解 @JmsListener(destination = "neo.queue"), 10 | * 表示此方法监控了名为 neo.queue 的队列。 11 | * 当队列 neo.queue 中有消息发送时会触发此方法的执行,text 为消息内容。 12 | **/ 13 | @Component 14 | public class Consumer3 { 15 | 16 | @JmsListener(destination = "topic1") 17 | public void receiveTopic(String text) { 18 | System.out.println(" Consumer3 接受到的消息是 : " + text); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Topic/Consumer4.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Topic; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * 创建消费者 8 | *

9 | * 使用注解 @JmsListener(destination = "neo.queue"), 10 | * 表示此方法监控了名为 neo.queue 的队列。 11 | * 当队列 neo.queue 中有消息发送时会触发此方法的执行,text 为消息内容。 12 | **/ 13 | @Component 14 | public class Consumer4 { 15 | 16 | 17 | @JmsListener(destination = "topic1") 18 | public void receiveTopic(String text) { 19 | System.out.println(" Consumer4 接受到的消息是: " + text); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/java/com/example/activemq/activemq/Topic/ProducerTopic.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq.Topic; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.jms.core.JmsMessagingTemplate; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.jms.Topic; 9 | 10 | @Component 11 | public class ProducerTopic { 12 | 13 | @Autowired 14 | private JmsMessagingTemplate jmsMessagingTemplate; 15 | @Autowired 16 | private Topic topic; 17 | 18 | public void sendTopic(String msg) { 19 | System.out.println(" 发送的消息是 :" + msg); 20 | this.jmsMessagingTemplate.convertAndSend(this.topic, msg); 21 | } 22 | } -------------------------------------------------------------------------------- /ActivemqDemo2/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # 基于内存的 ActiveMQ 2 | #spring.activemq.in-memory=true 3 | # 独立安装的 ActiveMQ 4 | spring.activemq.broker-url=tcp://127.0.0.1:61616 5 | spring.activemq.user=admin 6 | spring.activemq.password=admin 7 | # 不使用连接池 8 | #spring.activemq.pool.enabled=false 9 | 10 | -------------------------------------------------------------------------------- /ActivemqDemo2/src/test/java/com/example/activemq/activemq/ActivemqApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.activemq.activemq; 2 | 3 | import com.example.activemq.activemq.Queue.ProducerPoint; 4 | import com.example.activemq.activemq.Topic.ProducerTopic; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | @RunWith(SpringRunner.class) 12 | @SpringBootTest 13 | public class ActivemqApplicationTests { 14 | 15 | @Test 16 | public void contextLoads() { 17 | } 18 | 19 | 20 | @Autowired 21 | private ProducerPoint producer; 22 | 23 | @Autowired 24 | private ProducerTopic topic; 25 | 26 | 27 | // 生产者- 消费者 p2p 一个消息只能被一个消费者消费 28 | 29 | //当有多个消费者监听一个队列时,消费者会自动均衡负载的接收消息,并且每个消息只能有一个消费者所接收。 30 | @Test 31 | public void test1() { 32 | for (int i = 0; i < 3; i++) { 33 | producer.sendQueue(" 你好。。。"); 34 | } 35 | 36 | /* 37 | 38 | 发送消息为 : 你好。。。 39 | 发送消息为 : 你好。。。 40 | Consumer2 接受到的消息是 : 你好。。。 41 | Consumer 接受到的消息是 : 你好。。。 42 | 发送消息为 : 你好。。。 43 | Consumer2 接受到的消息是 : 你好。。。 44 | 45 | 46 | 47 | */ 48 | } 49 | 50 | // 生产者- 消费者 topic 51 | @Test 52 | public void test2() { 53 | producer.sendQueue(" 你好。。。"); 54 | topic.sendTopic(" 你们好。。。"); 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## SpringBoot 代码整合 (麻烦给个start,谢谢) 2 | 3 | SpringBoot coding 4 | 5 | 6 | ## 1 ActivemqDemo2 消息队列 : 同时支持 p2p 和 topic 7 | ## 2 springBootDuridDemo 多数据源 : mybatis + mysql + srpingboot + durid(连接池) 8 | ## 3 spring-session 分布式 session : spring session + springboot 9 | ## 4 springbootCrudDemo 简单的crud项目 : mysql + springboot 10 | ## 5 springboot-MongodbDemo mongodb 多数据源 11 | ## 6 springsecuritydemo springsecuritydemo security项目(不带数据库) 12 | ## 7 springBoot-quartz 整合quartz定时器 手动控制启动暂停任务 13 | ## 8 springboot-Redis-SETEX redis setex 和 redis redlock 分布式锁 14 | ## 9 springboot-atomikos atomikos 分布式事务 15 | ## 10 springBoot-redis 整合redis主从和集群模式 16 | ## 11 SpringBoot-RabbitMq 整合Rabbit五种消息队列类型 17 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.6.RELEASE 9 | 10 | 11 | com.example 12 | demo 13 | 0.0.1-SNAPSHOT 14 | rabbitmq 15 | SpringBoot整合RabbitMq 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | com.github.luues 36 | spring-boot-starter-rabbitmq 37 | 1.2.9.1.RELEASE 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-maven-plugin 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/one2one/Receiving.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.one2one; 2 | 3 | import com.rabbitmq.client.*; 4 | 5 | import java.io.IOException; 6 | 7 | import static com.example.demo.one2one.Send.QUEUE_NAME; 8 | 9 | 10 | /** 11 | * @description: 点对点 消息生产消费 12 | * @author: Administrator 13 | * @create: 2020-07-11 21:57 14 | **/ 15 | public class Receiving { 16 | 17 | public static void main(String[] argv) throws Exception { 18 | 19 | ConnectionFactory factory = new ConnectionFactory(); 20 | factory.setHost("localhost"); 21 | Connection connection = factory.newConnection(); 22 | Channel channel = connection.createChannel(); 23 | 24 | channel.queueDeclare(QUEUE_NAME, false, false, false, null); 25 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 26 | 27 | 28 | while (true) { 29 | 30 | Consumer consumer = new DefaultConsumer(channel) { 31 | @Override 32 | public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 33 | String message = new String(body, "UTF-8"); 34 | System.out.println(" [x] Received '" + message + "'"); 35 | channel.basicAck(envelope.getDeliveryTag(), false); 36 | } 37 | }; 38 | //true 监听队列 有消息就获取 没有就阻塞 true表示自动确认消息 39 | channel.basicConsume(QUEUE_NAME, false, consumer); 40 | 41 | } 42 | 43 | 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/one2one/Send.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.one2one; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | 7 | import java.io.IOException; 8 | 9 | 10 | /** 11 | * @description: 发送消息 12 | * @author: Administrator 13 | * @create: 2020-07-11 21:58 14 | **/ 15 | public class Send { 16 | 17 | public static final String QUEUE_NAME = "test_queue1"; 18 | 19 | 20 | public static void main(String[] args) { 21 | 22 | ConnectionFactory factory = new ConnectionFactory(); 23 | Channel channel = null; 24 | Connection connection = null; 25 | factory.setHost("localhost"); 26 | //factory.setPort(5671); 27 | 28 | try { 29 | connection = factory.newConnection(); 30 | channel = connection.createChannel(); 31 | //创建生命队列 32 | channel.queueDeclare(QUEUE_NAME, false, false, false, null); 33 | String message = "Hello World! 111 "; 34 | //发送消息 35 | channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 36 | System.out.println(" [x] Sent '" + message + "'"); 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | } finally { 40 | factory.clone(); 41 | if (connection != null) { 42 | try { 43 | connection.close(); 44 | } catch (IOException e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | } 49 | 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/publish/Rece1.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.publish; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece1 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_logs"; 20 | //队列 21 | public static final String QUEUE_NAME = "test_queue1_name"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | ConnectionFactory factory = new ConnectionFactory(); 25 | factory.setHost("localhost"); 26 | factory.setVirtualHost("/test"); 27 | factory.setUsername("test"); 28 | factory.setPassword("test"); 29 | 30 | Connection connection = factory.newConnection(); 31 | Channel channel = connection.createChannel(); 32 | //声明队列 33 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 34 | 35 | //绑定交换机 36 | channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); 37 | 38 | //绑定队列到交换机 39 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ""); 40 | 41 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 42 | 43 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 44 | String message = new String(delivery.getBody(), "UTF-8"); 45 | System.out.println(" [x] Received1 '" + message + "'"); 46 | }; 47 | 48 | //自动确认消息 49 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/publish/Rece2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.publish; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece2 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_logs"; 20 | //队列 21 | public static final String QUEUE_NAME = "test_queue2_name"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | 25 | ConnectionFactory factory = new ConnectionFactory(); 26 | 27 | factory.setHost("localhost"); 28 | factory.setVirtualHost("/test"); 29 | factory.setUsername("test"); 30 | factory.setPassword("test"); 31 | 32 | Connection connection = factory.newConnection(); 33 | Channel channel = connection.createChannel(); 34 | //声明队列 35 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 36 | 37 | //绑定交换机 38 | channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); 39 | 40 | //绑定队列到交换机 41 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ""); 42 | 43 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 44 | 45 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 46 | String message = new String(delivery.getBody(), "UTF-8"); 47 | System.out.println(" [x] Received2 '" + message + "'"); 48 | }; 49 | 50 | //自动确认消息 51 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 52 | }); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/publish/Send.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.publish; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2020-07-12 17:53 12 | **/ 13 | public class Send { 14 | //交换机 15 | private static final String EXCHANGE_NAME = "exchange_logs"; 16 | 17 | 18 | public static void main(String[] argv) throws Exception { 19 | ConnectionFactory factory = new ConnectionFactory(); 20 | factory.setHost("localhost"); 21 | factory.setVirtualHost("/test"); 22 | factory.setUsername("test"); 23 | factory.setPassword("test"); 24 | 25 | 26 | Connection connection = factory.newConnection(); 27 | Channel channel = connection.createChannel(); 28 | 29 | //绑定交换机 30 | channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); 31 | 32 | //消息 33 | String msg = "订单更新..... "; 34 | channel.basicPublish(EXCHANGE_NAME,"",null,msg.getBytes()); 35 | System.out.println("发送的消息 : " + msg); 36 | 37 | channel.close(); 38 | connection.close(); 39 | } 40 | } -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/route/Rece1.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.route; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece1 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_router"; 20 | //队列 21 | public static final String QUEUE_NAME = "router_queue_add"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | ConnectionFactory factory = new ConnectionFactory(); 25 | factory.setHost("localhost"); 26 | factory.setVirtualHost("/test"); 27 | factory.setUsername("test"); 28 | factory.setPassword("test"); 29 | 30 | Connection connection = factory.newConnection(); 31 | Channel channel = connection.createChannel(); 32 | //声明队列 33 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 34 | 35 | //绑定交换机 36 | channel.exchangeDeclare(EXCHANGE_NAME, "direct"); 37 | 38 | //绑定队列到交换机 39 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "add"); 40 | 41 | //同一时刻只接受一条消息 42 | channel.basicQos(1); 43 | 44 | 45 | 46 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 47 | 48 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 49 | String message = new String(delivery.getBody(), "UTF-8"); 50 | System.out.println(" [x] 新增商品 '" + message + "'"); 51 | }; 52 | 53 | //自动确认消息 54 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 55 | }); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/route/Rece2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.route; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece2 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_router"; 20 | //队列 21 | public static final String QUEUE_NAME = "router_queue_del"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | 25 | ConnectionFactory factory = new ConnectionFactory(); 26 | 27 | factory.setHost("localhost"); 28 | factory.setVirtualHost("/test"); 29 | factory.setUsername("test"); 30 | factory.setPassword("test"); 31 | 32 | Connection connection = factory.newConnection(); 33 | Channel channel = connection.createChannel(); 34 | //声明队列 35 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 36 | 37 | //绑定交换机 38 | channel.exchangeDeclare(EXCHANGE_NAME, "direct"); 39 | 40 | 41 | //绑定队列到交换机 绑定del路由 key 42 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "del"); 43 | 44 | 45 | //同一时刻只接受一条消息 46 | channel.basicQos(1); 47 | 48 | 49 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 50 | 51 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 52 | String message = new String(delivery.getBody(), "UTF-8"); 53 | System.out.println(" [x] 删除redis缓存 '" + message + "'"); 54 | }; 55 | 56 | //自动确认消息 57 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/route/Send.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.route; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2020-07-12 17:53 12 | **/ 13 | public class Send { 14 | //交换机 15 | private static final String EXCHANGE_NAME = "exchange_router"; 16 | 17 | 18 | public static void main(String[] argv) throws Exception { 19 | ConnectionFactory factory = new ConnectionFactory(); 20 | factory.setHost("localhost"); 21 | factory.setVirtualHost("/test"); 22 | factory.setUsername("test"); 23 | factory.setPassword("test"); 24 | 25 | 26 | Connection connection = factory.newConnection(); 27 | Channel channel = connection.createChannel(); 28 | 29 | //绑定交换机 30 | channel.exchangeDeclare(EXCHANGE_NAME, "direct"); 31 | 32 | //消息 33 | /* String msg = "新增商品..... "; 34 | channel.basicPublish(EXCHANGE_NAME,"add",null,msg.getBytes());*/ 35 | String msg = "删除商品..... "; 36 | channel.basicPublish(EXCHANGE_NAME,"del",null,msg.getBytes()); 37 | System.out.println("发送的消息 : " + msg); 38 | 39 | channel.close(); 40 | connection.close(); 41 | } 42 | } -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/topic/Rece1.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.topic; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece1 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_topic"; 20 | //队列 21 | public static final String QUEUE_NAME = "router_queue_topic_add"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | ConnectionFactory factory = new ConnectionFactory(); 25 | factory.setHost("localhost"); 26 | factory.setVirtualHost("/test"); 27 | factory.setUsername("test"); 28 | factory.setPassword("test"); 29 | 30 | Connection connection = factory.newConnection(); 31 | Channel channel = connection.createChannel(); 32 | //声明队列 33 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 34 | 35 | //绑定交换机 36 | channel.exchangeDeclare(EXCHANGE_NAME, "topic"); 37 | 38 | //绑定队列到交换机 39 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "iteme.add"); 40 | 41 | //同一时刻只接受一条消息 42 | channel.basicQos(1); 43 | 44 | 45 | 46 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 47 | 48 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 49 | String message = new String(delivery.getBody(), "UTF-8"); 50 | System.out.println(" [x] 新增商品 '" + message + "'"); 51 | }; 52 | 53 | //自动确认消息 54 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 55 | }); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/topic/Rece2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.topic; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece2 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_topic"; 20 | //队列 21 | public static final String QUEUE_NAME = "router_queue_topic_del"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | 25 | ConnectionFactory factory = new ConnectionFactory(); 26 | 27 | factory.setHost("localhost"); 28 | factory.setVirtualHost("/test"); 29 | factory.setUsername("test"); 30 | factory.setPassword("test"); 31 | 32 | Connection connection = factory.newConnection(); 33 | Channel channel = connection.createChannel(); 34 | //声明队列 35 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 36 | 37 | //绑定交换机 38 | channel.exchangeDeclare(EXCHANGE_NAME, "topic"); 39 | 40 | 41 | //绑定队列到交换机 绑定del路由 key 42 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "iteme.del"); 43 | 44 | 45 | //同一时刻只接受一条消息 46 | channel.basicQos(1); 47 | 48 | 49 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 50 | 51 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 52 | String message = new String(delivery.getBody(), "UTF-8"); 53 | System.out.println(" [x] 删除redis缓存 '" + message + "'"); 54 | }; 55 | 56 | //自动确认消息 57 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/topic/Rece3.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.topic; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | import com.rabbitmq.client.DeliverCallback; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.TimeoutException; 10 | 11 | /** 12 | * @description: 13 | * @author: Administrator 14 | * @create: 2020-07-12 17:55 15 | **/ 16 | public class Rece3 { 17 | 18 | //交换机 19 | private static final String EXCHANGE_NAME = "exchange_topic"; 20 | //队列 21 | public static final String QUEUE_NAME = "router_queue_topic_all"; 22 | 23 | public static void main(String[] args) throws IOException, TimeoutException { 24 | 25 | ConnectionFactory factory = new ConnectionFactory(); 26 | 27 | factory.setHost("localhost"); 28 | factory.setVirtualHost("/test"); 29 | factory.setUsername("test"); 30 | factory.setPassword("test"); 31 | 32 | Connection connection = factory.newConnection(); 33 | Channel channel = connection.createChannel(); 34 | //声明队列 35 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 36 | 37 | //绑定交换机 38 | channel.exchangeDeclare(EXCHANGE_NAME, "topic"); 39 | 40 | 41 | //绑定队列到交换机 绑定del路由 key 42 | channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "iteme.#"); 43 | 44 | 45 | //同一时刻只接受一条消息 46 | channel.basicQos(1); 47 | 48 | 49 | System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); 50 | 51 | DeliverCallback deliverCallback = (consumerTag, delivery) -> { 52 | String message = new String(delivery.getBody(), "UTF-8"); 53 | System.out.println(" 获取所有消息 '" + message + "'"); 54 | }; 55 | 56 | //自动确认消息 57 | channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/topic/Send.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.topic; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2020-07-12 17:53 12 | **/ 13 | public class Send { 14 | //交换机 15 | private static final String EXCHANGE_NAME = "exchange_topic"; 16 | 17 | 18 | public static void main(String[] argv) throws Exception { 19 | ConnectionFactory factory = new ConnectionFactory(); 20 | factory.setHost("localhost"); 21 | factory.setVirtualHost("/test"); 22 | factory.setUsername("test"); 23 | factory.setPassword("test"); 24 | 25 | 26 | Connection connection = factory.newConnection(); 27 | Channel channel = connection.createChannel(); 28 | 29 | //绑定交换机 30 | channel.exchangeDeclare(EXCHANGE_NAME, "topic"); 31 | 32 | //消息 33 | String msg = "新增消息接收..... "; 34 | channel.basicPublish(EXCHANGE_NAME,"iteme.add",null,msg.getBytes()); 35 | 36 | 37 | //String msg = "删除消息接收..... "; 38 | //channel.basicPublish(EXCHANGE_NAME,"iteme.del",null,msg.getBytes()); 39 | System.out.println("发送的消息 : " + msg); 40 | 41 | channel.close(); 42 | connection.close(); 43 | } 44 | } -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/work/Rece1.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.work; 2 | 3 | import com.rabbitmq.client.*; 4 | 5 | import java.io.IOException; 6 | import java.util.concurrent.TimeoutException; 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2020-07-12 16:19 12 | **/ 13 | public class Rece1 { 14 | 15 | 16 | public static String QUEUE_NAME = "test_queue"; 17 | 18 | public static void main(String[] args) throws IOException, TimeoutException { 19 | 20 | ConnectionFactory factory = new ConnectionFactory(); 21 | factory.setHost("localhost"); 22 | factory.setVirtualHost("/test"); 23 | factory.setUsername("test"); 24 | factory.setPassword("test"); 25 | Connection connection = factory.newConnection(); 26 | Channel channel = connection.createChannel(); 27 | 28 | //同一时刻只能发送一个消息给消费者 那个消费者早消费完 早可以拿消息进行消费 能者多劳 29 | channel.basicQos(1); 30 | 31 | 32 | channel.queueDeclare( 33 | QUEUE_NAME, false, false, 34 | false, null 35 | ); 36 | 37 | 38 | DefaultConsumer consumer = new DefaultConsumer(channel) { 39 | @Override 40 | public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 41 | String message = new String(body, "UTF-8"); 42 | System.out.println(" [x] Received '" + message + "'"); 43 | try { 44 | Thread.sleep(1 * 1000); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | //反馈消息 49 | channel.basicAck(envelope.getDeliveryTag(), false); 50 | } 51 | }; 52 | 53 | //false 表示不自动确认消息 需要手动反馈消息 54 | channel.basicConsume(QUEUE_NAME, false, consumer); 55 | } 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/work/Rece2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.work; 2 | 3 | import com.rabbitmq.client.*; 4 | 5 | import java.io.IOException; 6 | import java.util.concurrent.TimeoutException; 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2020-07-12 16:19 12 | **/ 13 | public class Rece2 { 14 | 15 | 16 | public static String QUEUE_NAME = "test_queue"; 17 | 18 | public static void main(String[] args) throws IOException, TimeoutException { 19 | 20 | ConnectionFactory factory = new ConnectionFactory(); 21 | 22 | factory.setHost("localhost"); 23 | factory.setVirtualHost("/test"); 24 | factory.setUsername("test"); 25 | factory.setPassword("test"); 26 | Connection connection = factory.newConnection(); 27 | Channel channel = connection.createChannel(); 28 | 29 | //同一时刻只能发送一个消息给消费者 30 | channel.basicQos(1); 31 | 32 | channel.queueDeclare( 33 | QUEUE_NAME, false, false, 34 | false, null 35 | ); 36 | 37 | 38 | DefaultConsumer consumer = new DefaultConsumer(channel) { 39 | @Override 40 | public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 41 | String message = new String(body, "UTF-8"); 42 | System.out.println(" [x] Received '" + message + "'"); 43 | try { 44 | Thread.sleep(2 * 1000); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | channel.basicAck(envelope.getDeliveryTag(), false); 49 | } 50 | }; 51 | 52 | 53 | 54 | channel.basicConsume(QUEUE_NAME, false, consumer); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/java/com/example/demo/work/Send.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.work; 2 | 3 | import com.rabbitmq.client.Channel; 4 | import com.rabbitmq.client.Connection; 5 | import com.rabbitmq.client.ConnectionFactory; 6 | 7 | import java.io.IOException; 8 | import java.util.concurrent.TimeoutException; 9 | 10 | /** 11 | * @description: 12 | * @author: Administrator 13 | * @create: 2020-07-12 16:19 14 | **/ 15 | public class Send { 16 | 17 | 18 | public static String QUEUE_NAME = "test_queue"; 19 | 20 | public static void main(String[] args) throws IOException, TimeoutException { 21 | ConnectionFactory factory = new ConnectionFactory(); 22 | factory.setHost("localhost"); 23 | factory.setVirtualHost("/test"); 24 | factory.setUsername("test"); 25 | factory.setPassword("test"); 26 | Connection connection = factory.newConnection(); 27 | Channel channel = connection.createChannel(); 28 | channel.queueDeclare( 29 | QUEUE_NAME, false, false, 30 | false, null 31 | ); 32 | 33 | //发送消息 34 | for (int i = 0; i < 50; i++) { 35 | String message = "message: " + i; 36 | channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 37 | System.out.println(message); 38 | try { 39 | Thread.sleep(i * 10); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | 46 | channel.close(); 47 | connection.close(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SpringBoot-RabbitMq/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.demo 12 | redisson 13 | 0.0.1-SNAPSHOT 14 | redisson 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-data-redis 33 | 34 | 35 | 36 | org.redisson 37 | redisson-spring-boot-starter 38 | 3.10.6 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-test 44 | test 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/java/com/demo/redisson/RedissonApplication.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RedissonApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RedissonApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/java/com/demo/redisson/config/DistributedLocker.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson.config; 2 | 3 | /** 4 | * @description: 5 | * @author: Administrator 6 | * @create: 2020-06-30 22:30 7 | **/ 8 | 9 | import org.redisson.api.RLock; 10 | 11 | import java.util.concurrent.TimeUnit; 12 | 13 | /** 14 | * @author gourd 15 | */ 16 | public interface DistributedLocker { 17 | 18 | RLock lock(String lockKey); 19 | 20 | RLock lock(String lockKey, int timeout); 21 | 22 | RLock lock(String lockKey, TimeUnit unit, int timeout); 23 | 24 | boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime); 25 | 26 | void unlock(String lockKey); 27 | 28 | void unlock(RLock lock); 29 | } 30 | 31 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/java/com/demo/redisson/config/RedisDistributedLocker.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson.config; 2 | 3 | /** 4 | * @description: 实现类 5 | * @author: Administrator 6 | * @create: 2020-06-30 22:30 7 | **/ 8 | 9 | import org.redisson.api.RLock; 10 | import org.redisson.api.RedissonClient; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.util.concurrent.TimeUnit; 15 | 16 | /** 17 | * @author gourd 18 | */ 19 | @Component 20 | public class RedisDistributedLocker implements DistributedLocker { 21 | 22 | @Autowired 23 | private RedissonClient redissonClient; 24 | 25 | @Override 26 | public RLock lock(String lockKey) { 27 | RLock lock = redissonClient.getLock(lockKey); 28 | lock.lock(); 29 | return lock; 30 | } 31 | 32 | @Override 33 | public RLock lock(String lockKey, int leaseTime) { 34 | RLock lock = redissonClient.getLock(lockKey); 35 | lock.lock(leaseTime, TimeUnit.SECONDS); 36 | return lock; 37 | } 38 | 39 | @Override 40 | public RLock lock(String lockKey, TimeUnit unit ,int timeout) { 41 | RLock lock = redissonClient.getLock(lockKey); 42 | lock.lock(timeout, unit); 43 | return lock; 44 | } 45 | 46 | @Override 47 | public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) { 48 | RLock lock = redissonClient.getLock(lockKey); 49 | try { 50 | return lock.tryLock(waitTime, leaseTime, unit); 51 | } catch (InterruptedException e) { 52 | return false; 53 | } 54 | } 55 | 56 | @Override 57 | public void unlock(String lockKey) { 58 | RLock lock = redissonClient.getLock(lockKey); 59 | lock.unlock(); 60 | } 61 | 62 | @Override 63 | public void unlock(RLock lock) { 64 | lock.unlock(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/java/com/demo/redisson/config/RedisLockUtil.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson.config; 2 | 3 | /** 4 | * @description: redis分布式锁帮助类 5 | * @author: Administrator 6 | * @create: 2020-06-30 22:29 7 | **/ 8 | 9 | import org.redisson.api.RLock; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Component; 12 | 13 | import javax.annotation.PostConstruct; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | /** 17 | * redis分布式锁帮助类 18 | * @author yangzhilong 19 | * 20 | */ 21 | @Component 22 | public class RedisLockUtil { 23 | 24 | 25 | @Autowired 26 | private DistributedLocker locker; 27 | 28 | private static DistributedLocker distributedLocker; 29 | 30 | 31 | @PostConstruct 32 | private void init() { 33 | distributedLocker = locker; 34 | } 35 | 36 | /** 37 | * 加锁 38 | * @param lockKey 39 | * @return 40 | */ 41 | public static RLock lock(String lockKey) { 42 | return distributedLocker.lock(lockKey); 43 | } 44 | 45 | /** 46 | * 释放锁 47 | * @param lockKey 48 | */ 49 | public static void unlock(String lockKey) { 50 | distributedLocker.unlock(lockKey); 51 | } 52 | 53 | /** 54 | * 释放锁 55 | * @param lock 56 | */ 57 | public static void unlock(RLock lock) { 58 | distributedLocker.unlock(lock); 59 | } 60 | 61 | /** 62 | * 带超时的锁 63 | * @param lockKey 64 | * @param timeout 超时时间 单位:秒 65 | */ 66 | public static RLock lock(String lockKey, int timeout) { 67 | return distributedLocker.lock(lockKey, timeout); 68 | } 69 | 70 | /** 71 | * 带超时的锁 72 | * @param lockKey 73 | * @param unit 时间单位 74 | * @param timeout 超时时间 75 | */ 76 | public static RLock lock(String lockKey, int timeout,TimeUnit unit ) { 77 | return distributedLocker.lock(lockKey, unit, timeout); 78 | } 79 | 80 | /** 81 | * 尝试获取锁 82 | * @param lockKey 83 | * @param waitTime 最多等待时间 84 | * @param leaseTime 上锁后自动释放锁时间 85 | * @return 86 | */ 87 | public static boolean tryLock(String lockKey, int waitTime, int leaseTime) { 88 | return distributedLocker.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime); 89 | } 90 | 91 | /** 92 | * 尝试获取锁 93 | * @param lockKey 94 | * @param unit 时间单位 95 | * @param waitTime 最多等待时间 96 | * @param leaseTime 上锁后自动释放锁时间 97 | * @return 98 | */ 99 | public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) { 100 | return distributedLocker.tryLock(lockKey, unit, waitTime, leaseTime); 101 | } 102 | } -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/java/com/demo/redisson/config/RedissonConfig.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson.config; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.api.RedissonClient; 5 | import org.redisson.config.Config; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | /** 11 | * @description: 配置类 12 | * @author: Administrator 13 | * @create: 2020-06-30 22:41 14 | **/ 15 | @Configuration 16 | public class RedissonConfig { 17 | 18 | @Value("${spring.redis.host}") 19 | private String host; 20 | 21 | @Value("${spring.redis.port}") 22 | private String port; 23 | 24 | @Bean 25 | public RedissonClient redissonClient(){ 26 | Config config = new Config(); 27 | //单机配置 28 | config.useSingleServer().setAddress("redis://"+host+":"+port); 29 | 30 | 31 | 32 | //集群配置 33 | //config.useClusterServers().addNodeAddress(".... 可变参数 ."); 34 | 35 | /* 36 | //主从 37 | config.useMasterSlaveServers() 38 | .setMasterAddress("主节点配置") 39 | .addSlaveAddress("从节点配置 可变参数"); 40 | //哨兵配置 41 | config.useSentinelServers().addSentinelAddress("哨兵配置地址 可变参数") 42 | .setMasterName("主库地址") 43 | .setTimeout(50000) 44 | .setMasterConnectionPoolSize(10) 45 | .setSlaveConnectionPoolSize(5); 46 | 47 | */ 48 | 49 | 50 | RedissonClient redisson = Redisson.create(config); 51 | return redisson; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | # redis 3 | redis: 4 | host: 127.0.0.1 5 | port: 6379 6 | -------------------------------------------------------------------------------- /SpringBoot-Redis/SpringBoot-Redisson/src/test/java/com/demo/redisson/RedissonApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.demo.redisson; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RedissonApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.example 12 | redis-setnx 13 | 0.0.1-SNAPSHOT 14 | redis-setnx 15 | redis 分布式锁 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-redis 38 | 39 | 40 | 41 | 42 | redis.clients 43 | jedis 44 | 2.6.2 45 | 46 | 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | 1.16.10 52 | provided 53 | 54 | 55 | 56 | 57 | org.redisson 58 | redisson 59 | 3.7.0 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/controller/RedisRedLockContoller.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | 4 | import com.example.demo.redis.redlock.AquiredLockWorker; 5 | import com.example.demo.redis.redlock.RedisLocker; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.time.LocalDateTime; 12 | import java.util.Random; 13 | import java.util.concurrent.Executors; 14 | import java.util.concurrent.ScheduledExecutorService; 15 | 16 | /** 17 | * @description: Redlock 分布式锁 18 | * @author: Administrator 19 | * @create: 2020-05-01 22:28 20 | **/ 21 | @RestController 22 | public class RedisRedLockContoller { 23 | 24 | 25 | @Autowired 26 | RedisLocker redisLocker; 27 | 28 | 29 | @RequestMapping("redLock") 30 | public String index() throws Exception { 31 | 32 | redisLocker.lock("test", new AquiredLockWorker() { 33 | @Override 34 | public Object invokeAfterLockAquire() { 35 | try { 36 | System.out.println("执行方法! ----- " + LocalDateTime.now()); 37 | //Thread.sleep(1000); 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | return null; 42 | } 43 | 44 | }); 45 | 46 | return "hello world!"; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/pojo/Lock.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.pojo; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @description: 全局锁,包括锁的名称 7 | * @author: Administrator 8 | * @create: 2020-05-01 22:00 9 | **/ 10 | @Data 11 | public class Lock { 12 | /** 13 | * key名 14 | */ 15 | private String name; 16 | /** 17 | * value值 18 | */ 19 | private String value; 20 | 21 | public Lock(String name, String value) { 22 | this.name = name; 23 | this.value = value; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/redlock/AquiredLockWorker.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.redlock; 2 | 3 | /** 4 | * @description: 获取锁后需要处理的逻辑 5 | * @author: Administrator 6 | * @create: 2020-05-02 10:41 7 | **/ 8 | public interface AquiredLockWorker { 9 | T invokeAfterLockAquire() throws Exception; 10 | } 11 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/redlock/DistributedLocker.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.redlock; 2 | 3 | /** 4 | * @description: 获取锁管理类 5 | * @author: Administrator 6 | * @create: 2020-05-02 10:42 7 | **/ 8 | public interface DistributedLocker { 9 | 10 | /** 11 | * 获取锁 12 | * @param resourceName 锁的名称 13 | * @param worker 获取锁后的处理类 14 | * @param 15 | * @return 处理完具体的业务逻辑要返回的数据 16 | * @throws UnableToAquireLockException 17 | * @throws Exception 18 | */ 19 | T lock(String resourceName, AquiredLockWorker worker) throws UnableToAquireLockException, Exception; 20 | 21 | /** 22 | * 一般使用获取锁时 使用超时时间,防止死锁 23 | * @param resourceName 24 | * @param worker 25 | * @param lockTime 26 | * @param 27 | * @return 28 | * @throws UnableToAquireLockException 29 | * @throws Exception 30 | */ 31 | T lock(String resourceName, AquiredLockWorker worker, int lockTime) throws UnableToAquireLockException, Exception; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/redlock/RedisLocker.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.redlock; 2 | 3 | import org.redisson.api.RLock; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * @description: 红锁实现类 12 | * @author: Administrator 13 | * @create: 2020-05-02 10:43 14 | **/ 15 | @Component 16 | public class RedisLocker implements DistributedLocker{ 17 | 18 | /** 19 | * 前缀 20 | */ 21 | private final static String LOCKER_PREFIX = "lock:"; 22 | 23 | @Autowired 24 | RedissonConnector redissonConnector; 25 | 26 | @Override 27 | public T lock(String resourceName, AquiredLockWorker worker) throws InterruptedException, UnableToAquireLockException, Exception { 28 | 29 | return lock(resourceName, worker, 100); 30 | } 31 | 32 | @Override 33 | public T lock(String resourceName, AquiredLockWorker worker, int lockTime) throws UnableToAquireLockException, Exception { 34 | RedissonClient redisson= redissonConnector.getClient(); 35 | RLock lock = redisson.getLock(LOCKER_PREFIX + resourceName); 36 | // Wait for 100 seconds seconds and automatically unlock it after lockTime seconds 37 | boolean success = lock.tryLock(100, lockTime, TimeUnit.SECONDS); 38 | if (success) { 39 | try { 40 | return worker.invokeAfterLockAquire(); 41 | } finally { 42 | lock.unlock(); 43 | } 44 | } 45 | throw new UnableToAquireLockException(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/redlock/RedissonConnector.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.redlock; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.annotation.PostConstruct; 8 | 9 | /** 10 | * @description: 获取RedissonClient连接类 11 | * @author: Administrator 12 | * @create: 2020-05-02 10:43 13 | **/ 14 | @Component 15 | public class RedissonConnector { 16 | RedissonClient redisson; 17 | @PostConstruct 18 | public void init(){ 19 | redisson = Redisson.create(); 20 | } 21 | 22 | public RedissonClient getClient(){ 23 | return redisson; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/java/com/example/demo/redis/redlock/UnableToAquireLockException.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.redis.redlock; 2 | 3 | /** 4 | * @description: 异常类 5 | * @author: Administrator 6 | * @create: 2020-05-02 10:43 7 | **/ 8 | public class UnableToAquireLockException extends RuntimeException { 9 | 10 | public UnableToAquireLockException() { 11 | } 12 | 13 | public UnableToAquireLockException(String message) { 14 | super(message); 15 | } 16 | 17 | public UnableToAquireLockException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | server: 3 | port: 8080 4 | 5 | 6 | spring: 7 | profiles: dev 8 | data: 9 | redis: 10 | # Redis数据库索引(默认为0) 11 | database: 0 12 | # Redis服务器地址 13 | host: 127.0.0.1 14 | # Redis服务器连接端口 15 | port: 6379 16 | # Redis服务器连接密码(默认为空) 17 | password: -------------------------------------------------------------------------------- /SpringBoot-Redis/Springboot-Redis-SETEX/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/redis-cluster/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 1.5.22.RELEASE 9 | 10 | 11 | com.example 12 | redis-cluster 13 | 0.0.1-SNAPSHOT 14 | redis-cluster 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-redis 38 | 1.4.7.RELEASE 39 | 40 | 41 | 42 | 43 | 44 | redis.clients 45 | jedis 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-maven-plugin 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/redis-cluster/src/main/java/com/example/rediscluster/RedisClusterApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.rediscluster; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | 9 | @SpringBootApplication 10 | public class RedisClusterApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(RedisClusterApplication.class, args); 14 | } 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/redis-cluster/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 2.x默认连接池 4 | 5 | spring: 6 | redis: 7 | cluster: 8 | nodes: 9 | - 127.0.1.1:7001 10 | - 127.0.1.1:7002 11 | - 127.0.1.1:7003 12 | - 127.0.1.1:7004 13 | - 127.0.1.1:7005 14 | - 127.0.1.1:7006 15 | max-redirects: 3 # 获取失败 最大重定向次数 16 | pool: 17 | max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) 18 | max-idle: 10 # 连接池中的最大空闲连接 19 | max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 20 | min-idle: 5 # 连接池中的最小空闲连接 21 | timeout: 6000 # 连接超时时长(毫秒) 22 | 23 | # 使用jedis连接池 24 | # 25 | #spring: 26 | # redis: 27 | # password: # 密码(默认为空) 28 | # timeout: 6000ms # 连接超时时长(毫秒) 29 | # cluster: 30 | # nodes: 31 | # - 127.0.1.1:7001 32 | # - 127.0.1.1:7002 33 | # - 127.0.1.1:7003 34 | # - 127.0.1.1:7004 35 | # - 127.0.1.1:7005 36 | # - 127.0.1.1:7006 37 | # jedis: 38 | # pool: 39 | # max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) 40 | # max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) 41 | # max-idle: 10 # 连接池中的最大空闲连接 42 | # min-idle: 5 # 连接池中的最小空闲连接 43 | 44 | 45 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/redis-cluster/src/test/java/com/example/rediscluster/RedisClusterApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.rediscluster; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class RedisClusterApplicationTests { 13 | 14 | @Test 15 | public void contextLoads() { 16 | } 17 | 18 | @Autowired 19 | RedisTemplate redisTemplate; 20 | 21 | @Test 22 | public void test1(){ 23 | redisTemplate.opsForValue().set("test","test"); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/sentinel-redis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 1.5.22.RELEASE 9 | 10 | 11 | com.example 12 | sentinel-redis 13 | 0.0.1-SNAPSHOT 14 | sentinel-redis 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | org.junit.vintage 34 | junit-vintage-engine 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-redis 43 | 1.4.7.RELEASE 44 | 45 | 46 | 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-maven-plugin 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/sentinel-redis/src/main/java/com/example/sentinelredis/SentinelRedisApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.sentinelredis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SentinelRedisApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SentinelRedisApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/sentinel-redis/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | # redis 主从哨兵配置 3 | spring: 4 | redis: 5 | database: 0 6 | host: 127.0.0.1 7 | port: 6379 8 | password: 9 | pool: 10 | max-active: 8 11 | max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 12 | max-idle: 8 13 | min-idle: 0 14 | timeout: 0 15 | # 主节点哨兵名 16 | sentinel: 17 | master: mymaster 18 | # comma-separated list of host:port pairs 哨兵节点配置列表 19 | nodes: 127.0.0.1:26380,127.0.0.1:26381 20 | -------------------------------------------------------------------------------- /SpringBoot-Redis/springBoot-redis/SpringBoot-Redis/sentinel-redis/src/test/java/com/example/sentinelredis/SentinelRedisApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.sentinelredis; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class SentinelRedisApplicationTests { 13 | 14 | @Test 15 | public void contextLoads() { 16 | } 17 | 18 | @Autowired 19 | RedisTemplate redisTemplate; 20 | 21 | @Test 22 | public void test1() { 23 | redisTemplate.opsForValue().set("test", "test"); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /SpringBoot-dubbo/代码示例: -------------------------------------------------------------------------------- 1 | 代码仓库分支 https://github.com/pomestyle/gmail0105/blob/master/README.md -------------------------------------------------------------------------------- /SpringBoot-quartz/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /SpringBoot-quartz/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.6.RELEASE 9 | 10 | 11 | com.example 12 | demo 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | org.quartz-scheduler 36 | quartz 37 | 2.2.1 38 | 39 | 40 | 41 | 42 | org.springframework 43 | spring-tx 44 | 5.0.8.RELEASE 45 | 46 | 47 | 48 | 49 | org.springframework 50 | spring-context-support 51 | 4.3.13.RELEASE 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-maven-plugin 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/java/com/example/demo/cifg/Job.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.cifg; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | /** 6 | * @description: 定义任务job 7 | * @author: Administrator 8 | * @create: 2020-05-24 15:39 9 | **/ 10 | @Component 11 | public class Job { 12 | 13 | 14 | public void job() { 15 | 16 | System.out.println("--------------- 执行任务 --------------"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/java/com/example/demo/cifg/QuartzConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.cifg; 2 | 3 | 4 | import org.quartz.Trigger; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.scheduling.quartz.CronTriggerFactoryBean; 9 | import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; 10 | import org.springframework.scheduling.quartz.SchedulerFactoryBean; 11 | 12 | /** 13 | * 配置类 14 | */ 15 | @Configuration 16 | public class QuartzConfig { 17 | 18 | // 定义方法,做什么 19 | @Bean(name = "job1") 20 | public MethodInvokingJobDetailFactoryBean job1(Job job) { 21 | MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean(); 22 | // 是否并发执行 23 | factoryBean.setConcurrent(false); 24 | // 使用哪个对象 25 | factoryBean.setTargetObject(job); 26 | // 使用哪个方法 27 | factoryBean.setTargetMethod("job"); 28 | 29 | return factoryBean; 30 | } 31 | 32 | // 定义什么时候做,使用 cron 表达式 33 | @Bean(name = "cron1") 34 | public CronTriggerFactoryBean cron1(@Qualifier("job1") MethodInvokingJobDetailFactoryBean job1) { 35 | CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean(); 36 | // 设置job对象 37 | factoryBean.setJobDetail(job1.getObject()); 38 | // 设置执行时间 39 | factoryBean.setCronExpression("0/5 * * * * ?"); 40 | return factoryBean; 41 | } 42 | 43 | 44 | // 创建 Scheduler 对象 45 | // 定义 任务,传入 triggers 46 | @Bean(name = "sch1") 47 | public SchedulerFactoryBean scheduler1(Trigger... triggers) { 48 | SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); 49 | // 设置 triggers 50 | factoryBean.setTriggers(triggers); 51 | // 自动运行 52 | factoryBean.setAutoStartup(true); 53 | 54 | return factoryBean; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/java/com/example/demo/cifg/TestJob.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.cifg; 2 | 3 | import org.quartz.*; 4 | import org.quartz.Job; 5 | import org.quartz.impl.StdSchedulerFactory; 6 | 7 | /** 8 | * @description: 控制台定时器 9 | * @author: Administrator 10 | * @create: 2020-05-24 16:09 11 | **/ 12 | public class TestJob implements Job { 13 | @Override 14 | public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { 15 | 16 | 17 | System.out.println(" ------------ quartz 控制台定时器 ------------------ "); 18 | } 19 | 20 | 21 | public static void main(String[] args) throws SchedulerException { 22 | 23 | 24 | // 1,创建 job,你要做什么事? 25 | JobDetail job = JobBuilder.newJob(TestJob.class).build(); 26 | 27 | // 2,创建 trigger ,你在什么时候做? 28 | Trigger trigger = TriggerBuilder 29 | .newTrigger() 30 | //.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(2)).build(); 31 | //可以换成cron表达式 32 | .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build(); 33 | 34 | // 3,创建 schedule 对象,在什么时候执行什么事? 35 | Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 36 | 37 | scheduler.scheduleJob(job, trigger); 38 | // 4,启动 39 | scheduler.start(); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/java/com/example/demo/controller/QuartzController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import org.quartz.*; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * @description: 定时器控制层 11 | * @author: Administrator 12 | * @create: 2020-05-24 15:35 13 | **/ 14 | @RestController 15 | public class QuartzController { 16 | 17 | 18 | @Autowired 19 | @Qualifier("sch1") 20 | private Scheduler scheduler; 21 | 22 | /** 23 | * 关闭任务 24 | */ 25 | @RequestMapping("/pause") 26 | public String pause() throws Exception { 27 | 28 | System.out.println(scheduler); 29 | //任务名 30 | JobKey key = new JobKey("job1"); 31 | scheduler.pauseJob(key); 32 | System.out.println(" ---------- 关闭成功 ---------- "); 33 | return "pause"; 34 | 35 | 36 | } 37 | 38 | /** 39 | * 执行任务 40 | */ 41 | @RequestMapping("/start") 42 | public String start() throws Exception { 43 | 44 | System.out.println(scheduler); 45 | 46 | JobKey key = new JobKey("job1"); 47 | scheduler.resumeJob(key); 48 | System.out.println(" ---------- 启动成功 ---------- "); 49 | return "start"; 50 | } 51 | 52 | 53 | /** 54 | * 动态修改任务执行的时间 55 | */ 56 | @RequestMapping("/trigger") 57 | public String trigger() throws Exception { 58 | // 获取任务 59 | JobKey jobKey = new JobKey("job1"); 60 | // 获取 jobDetail 61 | JobDetail jobDetail = scheduler.getJobDetail(jobKey); 62 | // 生成 trigger 63 | Trigger trigger = TriggerBuilder 64 | .newTrigger() 65 | .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?")) 66 | .build(); 67 | // 删除任务,不删除会报错。报任务已存在 68 | scheduler.deleteJob(jobKey); 69 | // 启动任务 70 | scheduler.scheduleJob(jobDetail, trigger); 71 | System.out.println(" ---------- 更新启动成功 ---------- "); 72 | return "trigger"; 73 | } 74 | } -------------------------------------------------------------------------------- /SpringBoot-quartz/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /SpringBoot-quartz/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/HELP.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ### Reference Documentation 4 | For further reference, please consider the following sections: 5 | 6 | * [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) 7 | * [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.1.15.RELEASE/maven-plugin/) 8 | * [Spring Web](https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) 9 | 10 | ### Guides 11 | The following guides illustrate how to use some features concretely: 12 | 13 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 14 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 15 | * [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) 16 | 17 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.6.RELEASE 9 | 10 | 11 | com.vue.demo 12 | vuedemo 13 | 0.0.1-SNAPSHOT 14 | vuedemo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | 36 | mysql 37 | mysql-connector-java 38 | 39 | 40 | 41 | 42 | org.mybatis.spring.boot 43 | mybatis-spring-boot-starter 44 | 1.1.1 45 | 46 | 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | 52 | 53 | 54 | 55 | 56 | com.github.pagehelper 57 | pagehelper-spring-boot-starter 58 | 1.2.12 59 | 60 | 61 | org.jetbrains 62 | annotations 63 | RELEASE 64 | compile 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-maven-plugin 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/VuedemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.vue.demo.vuedemo.dao") 9 | public class VuedemoApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(VuedemoApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/common/PageQuery.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.common; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @description: 7 | * @author: Administrator 8 | * @create: 2020-06-20 17:28 9 | **/ 10 | @Data 11 | public class PageQuery { 12 | 13 | private Integer page = 1; 14 | private Integer pageSize = 10; 15 | 16 | private T object; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/common/ReturnMessage.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.common; 2 | 3 | 4 | import com.fasterxml.jackson.annotation.JsonInclude; 5 | import lombok.Data; 6 | 7 | import java.time.Instant; 8 | 9 | /** 10 | * 标准返回 11 | * 12 | * @author wangguichao 13 | */ 14 | @Data 15 | @JsonInclude(JsonInclude.Include.NON_NULL) 16 | public class ReturnMessage { 17 | 18 | /** 19 | * 返回代码 20 | */ 21 | int code; 22 | Integer subCode; 23 | 24 | /** 25 | * 返回信息 26 | */ 27 | String msg; 28 | String subMsg; 29 | 30 | /** 31 | * 返回数据 32 | */ 33 | T data; 34 | T subData; 35 | 36 | /** 37 | * 标记,时间戳 38 | */ 39 | Long stamp; 40 | 41 | public ReturnMessage() { 42 | } 43 | 44 | public ReturnMessage(int code, String msg) { 45 | this.code = code; 46 | this.msg = msg; 47 | } 48 | 49 | public ReturnMessage(int code, String msg, Long stamp) { 50 | this.code = code; 51 | this.msg = msg; 52 | this.stamp = stamp; 53 | } 54 | 55 | public ReturnMessage(int code, int subCode, String msg) { 56 | this.code = code; 57 | this.subCode = subCode; 58 | this.msg = msg; 59 | } 60 | 61 | public ReturnMessage(int code, String msg, T data) { 62 | this.code = code; 63 | this.msg = msg; 64 | this.data = data; 65 | } 66 | 67 | public ReturnMessage(int code, int subCode, String msg, String subMsg, T data, T subData) { 68 | this.code = code; 69 | this.subCode = subCode; 70 | this.msg = msg; 71 | this.subMsg = subMsg; 72 | this.data = data; 73 | this.subData = subData; 74 | } 75 | 76 | public ReturnMessage(int code, Integer subCode, String msg, String subMsg, T data, T subData, Long stamp) { 77 | this.code = code; 78 | this.subCode = subCode; 79 | this.msg = msg; 80 | this.subMsg = subMsg; 81 | this.data = data; 82 | this.subData = subData; 83 | this.stamp = stamp; 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.controller; 2 | 3 | import org.springframework.web.bind.annotation.CrossOrigin; 4 | import org.springframework.web.bind.annotation.RequestBody; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import java.util.Map; 9 | 10 | /** 11 | * @description: 12 | * @author: Administrator 13 | * @create: 2020-06-20 18:04 14 | **/ 15 | @RestController 16 | @RequestMapping("/api") 17 | @CrossOrigin 18 | public class LoginController { 19 | 20 | 21 | @RequestMapping("/login") 22 | public Map login(@RequestBody Map map) throws Exception { 23 | 24 | System.out.println(map); 25 | 26 | return map; 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/controller/StudentController.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.controller; 2 | 3 | import com.github.pagehelper.PageInfo; 4 | import com.vue.demo.vuedemo.common.PageQuery; 5 | import com.vue.demo.vuedemo.common.ReturnMessage; 6 | import com.vue.demo.vuedemo.pojo.Student; 7 | import com.vue.demo.vuedemo.service.StudentService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.CrossOrigin; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | @RestController 15 | @RequestMapping("/api/stu") 16 | @CrossOrigin 17 | public class StudentController { 18 | 19 | 20 | @Autowired 21 | private StudentService studentService; 22 | 23 | @RequestMapping("findAlls") 24 | public ReturnMessage findAlls(@RequestBody PageQuery pageQuery) { 25 | return new ReturnMessage(0, "成功", studentService.findList(pageQuery.getObject(), pageQuery.getPage(), pageQuery.getPageSize())); 26 | } 27 | 28 | 29 | @RequestMapping("add") 30 | public ReturnMessage add(@RequestBody Student student) { 31 | studentService.add(student); 32 | return new ReturnMessage(0, "成功", null); 33 | } 34 | 35 | 36 | @RequestMapping("update") 37 | public ReturnMessage findAll(@RequestBody Student student) { 38 | studentService.update(student); 39 | return new ReturnMessage(0, "成功"); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/dao/StudentDao.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.dao; 2 | 3 | 4 | import com.vue.demo.vuedemo.pojo.Student; 5 | import org.apache.ibatis.annotations.*; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * @description: 11 | * @author: Administrator 12 | * @create: 2020-06-11 20:38 13 | **/ 14 | @Mapper 15 | public interface StudentDao { 16 | 17 | 18 | List findAll(Student student); 19 | 20 | 21 | void insert(Student user); 22 | 23 | 24 | void update(Student student); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/pojo/Student.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.pojo; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @description: 7 | * @author: Administrator 8 | * @create: 2020-06-11 20:36 9 | **/ 10 | @Data 11 | public class Student { 12 | 13 | private Integer id; 14 | 15 | private String name; 16 | 17 | private int age; 18 | } 19 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/service/StudentService.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.service; 2 | 3 | 4 | import com.github.pagehelper.PageInfo; 5 | import com.vue.demo.vuedemo.pojo.Student; 6 | 7 | 8 | 9 | /** 10 | * @description: 11 | * @author: Administrator 12 | * @create: 2020-06-11 20:45 13 | **/ 14 | public interface StudentService { 15 | 16 | void add(Student student); 17 | 18 | PageInfo findList(Student student,int page, int pageSize); 19 | 20 | void update(Student student); 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/java/com/vue/demo/vuedemo/service/StudentServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo.service; 2 | 3 | 4 | import com.github.pagehelper.PageHelper; 5 | import com.github.pagehelper.PageInfo; 6 | import com.vue.demo.vuedemo.dao.StudentDao; 7 | import com.vue.demo.vuedemo.pojo.Student; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | import java.util.List; 13 | import java.util.concurrent.Executors; 14 | 15 | /** 16 | * @description: 17 | * @author: Administrator 18 | * @create: 2020-06-11 20:45 19 | **/ 20 | @Service 21 | public class StudentServiceImpl implements StudentService { 22 | 23 | 24 | @Autowired 25 | private StudentDao studentDao; 26 | 27 | 28 | @Override 29 | public PageInfo findList(Student student, int page, int pageSize) { 30 | 31 | PageHelper.startPage(page, pageSize); 32 | List all = studentDao.findAll(student); 33 | return new PageInfo<>(all); 34 | } 35 | 36 | @Override 37 | @Transactional(rollbackFor = Exception.class) 38 | public void update(Student student) { 39 | studentDao.update(student); 40 | } 41 | 42 | 43 | @Override 44 | @Transactional(rollbackFor = Exception.class) 45 | public void add(Student student) { 46 | studentDao.insert(student); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | 3 | spring: 4 | datasource: 5 | driver-class-name: com.mysql.jdbc.Driver 6 | url: jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai 7 | username: root 8 | password: root 9 | 10 | mybatis: 11 | type-aliases-package: com.vue.demo.vuedemo.pojo 12 | mapper-locations: classpath:mapper/*Mapper.xml 13 | 14 | 15 | server: 16 | port: 8081 -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/resources/mapper/StudentMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 20 | 21 | 22 | 23 | insert into student(`name`,age) VALUES (#{name},#{age}) 24 | 25 | 26 | 27 | 28 | update 29 | student 30 | set 31 | `name` = #{name}, 32 | age = #{age} 33 | 34 | where 35 | id = #{id} 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/main/resources/sql/student.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat Premium Data Transfer 3 | 4 | Source Server : 3306 5 | Source Server Type : MySQL 6 | Source Server Version : 50528 7 | Source Host : localhost:3306 8 | Source Schema : test 9 | 10 | Target Server Type : MySQL 11 | Target Server Version : 50528 12 | File Encoding : 65001 13 | 14 | Date: 20/06/2020 20:16:48 15 | */ 16 | 17 | SET NAMES utf8mb4; 18 | SET FOREIGN_KEY_CHECKS = 0; 19 | 20 | -- ---------------------------- 21 | -- Table structure for student 22 | -- ---------------------------- 23 | DROP TABLE IF EXISTS `student`; 24 | CREATE TABLE `student` ( 25 | `id` int(11) NOT NULL AUTO_INCREMENT, 26 | `age` int(11) NULL DEFAULT NULL, 27 | `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 28 | PRIMARY KEY (`id`) USING BTREE 29 | ) ENGINE = InnoDB AUTO_INCREMENT = 24 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; 30 | 31 | SET FOREIGN_KEY_CHECKS = 1; 32 | -------------------------------------------------------------------------------- /SpringBoot-vue-crud/src/test/java/com/vue/demo/vuedemo/VuedemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.vue.demo.vuedemo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class VuedemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/README.md: -------------------------------------------------------------------------------- 1 | ### SpringBootDuridDemo 2 | ### Spring Boot JDBC + Mybatis 配置多数据源 以及 采用Durid 作为连接池 3 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/MysqlConfig2Databases/MultiDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.MysqlConfig2Databases; 2 | 3 | import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.annotation.Primary; 8 | 9 | import javax.sql.DataSource; 10 | 11 | 12 | @Configuration 13 | public class MultiDataSourceConfig { 14 | @Primary 15 | @Bean(name = "oneDatasource") 16 | @ConfigurationProperties("spring.datasource.druid.one") 17 | public DataSource dataSourceOne() { 18 | return DruidDataSourceBuilder.create().build(); 19 | } 20 | 21 | @Bean(name = "secondDatasource") 22 | @ConfigurationProperties("spring.datasource.druid.second") 23 | public DataSource dataSourceTwo() { 24 | return DruidDataSourceBuilder.create().build(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/MysqlConfig2Databases/OneDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.MysqlConfig2Databases; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.mybatis.spring.SqlSessionFactoryBean; 5 | import org.mybatis.spring.SqlSessionTemplate; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.Primary; 11 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 12 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 13 | 14 | import javax.sql.DataSource; 15 | 16 | @Configuration 17 | @MapperScan(basePackages = "com.example.demo.mapper.one", sqlSessionTemplateRef = "oneSqlSessionTemplate") 18 | public class OneDataSourceConfig { 19 | 20 | //------------------ 加载配置的数据源: ------------------------------- 21 | 22 | 23 | //---------------------- 创建的数据源 构建对应的 SqlSessionFactory。 ---------------------- 24 | 25 | @Bean(name = "oneSqlSessionFactory") 26 | @Primary 27 | public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDatasource") DataSource dataSource) throws Exception { 28 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 29 | bean.setDataSource(dataSource); 30 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/one/*.xml")); 31 | return bean.getObject(); 32 | } 33 | 34 | 35 | //------------------------ 配置事务 -------------------------- 36 | @Bean(name = "oneTransactionManager") 37 | @Primary 38 | public DataSourceTransactionManager oneTransactionManager(@Qualifier("oneDatasource") DataSource dataSource) { 39 | return new DataSourceTransactionManager(dataSource); 40 | } 41 | 42 | 43 | //------------------------------- 注入 SqlSessionFactory 到 SqlSessionTemplate 中--------------------------------- 44 | @Bean(name = "oneSqlSessionTemplate") 45 | @Primary 46 | public SqlSessionTemplate oneSqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 47 | return new SqlSessionTemplate(sqlSessionFactory); 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/MysqlConfig2Databases/SecondDataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.MysqlConfig2Databases; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.mybatis.spring.SqlSessionFactoryBean; 5 | import org.mybatis.spring.SqlSessionTemplate; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 11 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 12 | 13 | import javax.sql.DataSource; 14 | 15 | 16 | @Configuration 17 | @MapperScan(basePackages = "com.example.demo.mapper.second", sqlSessionTemplateRef = "secondSqlSessionTemplate") 18 | public class SecondDataSourceConfig { 19 | 20 | 21 | //------------------ 加载配置的数据源: ------------------------------- 22 | 23 | //---------------------- 创建的数据源 构建对应的 SqlSessionFactory。 ---------------------- 24 | 25 | 26 | @Bean(name = "secondSqlSessionFactory") 27 | public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDatasource") DataSource dataSource) throws Exception { 28 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 29 | bean.setDataSource(dataSource); 30 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/second/*.xml")); 31 | return bean.getObject(); 32 | } 33 | 34 | //------------------------ 配置事务 -------------------------- 35 | 36 | 37 | @Bean(name = "secondTransactionManager") 38 | public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDatasource") DataSource dataSource) { 39 | return new DataSourceTransactionManager(dataSource); 40 | } 41 | 42 | 43 | //------------------------------- 注入 SqlSessionFactory 到 SqlSessionTemplate 中--------------------------------- 44 | 45 | 46 | @Bean(name = "secondSqlSessionTemplate") 47 | public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 48 | return new SqlSessionTemplate(sqlSessionFactory); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/SpringBootDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | public class SpringBootDemoApplication { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(SpringBootDemoApplication.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | 4 | import com.example.demo.mapper.one.User1Mapper; 5 | import com.example.demo.mapper.second.User2Mapper; 6 | import com.example.demo.pojo.User; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | public class UserController { 13 | 14 | @Autowired 15 | User1Mapper user1Mapper; 16 | 17 | @Autowired 18 | User2Mapper user2Mapper; 19 | 20 | 21 | @RequestMapping("add") 22 | public void add() { 23 | 24 | user1Mapper.inserts(new User("a123456", 1)); 25 | user1Mapper.inserts(new User("b123456", 1)); 26 | user2Mapper.inserts(new User("b123456", 1)); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/mapper/one/User1Mapper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.mapper.one; 2 | 3 | import com.example.demo.pojo.User; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface User1Mapper { 9 | 10 | public List findAll(); 11 | 12 | public void batchInsert(List userList); 13 | 14 | public void inserts(User user); 15 | } 16 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/mapper/second/User2Mapper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.mapper.second; 2 | 3 | import com.example.demo.pojo.User; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface User2Mapper { 9 | 10 | public List findAll(); 11 | 12 | public void batchInsert(List userList); 13 | 14 | public void inserts(User user); 15 | } 16 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/java/com/example/demo/pojo/User.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.pojo; 2 | 3 | 4 | import lombok.Data; 5 | 6 | @Data 7 | public class User { 8 | 9 | private Long id; 10 | 11 | private String name; 12 | 13 | private int age; 14 | 15 | public User(String name, int age) { 16 | this.name = name; 17 | this.age = age; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pomestyle/SpringBoot/b76d55e8410d811de23a03597d6714eb087766bb/SpringBootDuridDemo/src/main/resources/application.properties -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/resources/mapper/config/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/resources/mapper/one/User1Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 18 | 19 | 20 | insert into user VALUES 21 | 22 | 23 | 24 | (#{name},#{age}) 25 | 26 | 27 | 28 | 29 | 30 | 31 | insert into user(`name`,age) VALUE (#{name},#{age}) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/resources/mapper/second/User2Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 18 | 19 | 20 | insert into user VALUES 21 | 22 | 23 | 24 | (#{name},#{age}) 25 | 26 | 27 | 28 | 29 | 30 | 31 | insert into user(`name`,age) VALUE (#{name},#{age}) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/main/resources/sql/user.sql: -------------------------------------------------------------------------------- 1 | / 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : 127.0.0.1 5 | Source Server Version : 50720 6 | Source Host : localhost:3306 7 | Source Database : user 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50720 11 | File Encoding : 65001 12 | 13 | Date: 2018-07-19 23:28:45 14 | / 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for `user` 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `user`; 22 | CREATE TABLE `user` ( 23 | `id` tinyint(4) NOT NULL AUTO_INCREMENT, 24 | `name` varchar(200) NOT NULL, 25 | `age` int(11) NOT NULL, 26 | PRIMARY KEY (`id`) 27 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 28 | 29 | -- ---------------------------- 30 | -- Records of user 31 | -- ---------------------------- 32 | INSERT INTO `user` VALUES ('1', 'zs', '11'); 33 | INSERT INTO `user` VALUES ('2', 'ww', '12'); 34 | -------------------------------------------------------------------------------- /SpringBootDuridDemo/src/test/java/com/example/demo/SpringBootDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | import org.springframework.test.context.junit4.SpringRunner; 6 | 7 | @RunWith(SpringRunner.class) 8 | @SpringBootTest 9 | public class SpringBootDemoApplicationTests { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.example.mongodbDemo 12 | demo 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-mongodb 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-test 34 | test 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.18.8 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-maven-plugin 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo; 2 | 3 | import com.example.mongodbdemo.demo.m1dao.MongoDao1; 4 | import com.example.mongodbdemo.demo.m2dao.MongoDao2; 5 | import com.example.mongodbdemo.demo.test.User; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.data.domain.Page; 10 | import org.springframework.data.domain.PageRequest; 11 | import org.springframework.data.domain.Pageable; 12 | import org.springframework.data.domain.Sort; 13 | import org.springframework.stereotype.Controller; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | 16 | import java.util.List; 17 | 18 | @SpringBootApplication 19 | @Controller 20 | public class DemoApplication { 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(DemoApplication.class, args); 24 | } 25 | 26 | 27 | @Autowired 28 | private MongoDao1 primaryRepository; 29 | @Autowired 30 | private MongoDao2 secondaryRepository; 31 | 32 | @RequestMapping("test") 33 | public void TestSave() { 34 | //每页2条 按名字倒叙 35 | Pageable pageable = PageRequest.of(1,2, Sort.Direction.DESC,"userName"); 36 | Page all = primaryRepository.findAll(pageable); 37 | System.out.println(all.getContent().toString()); 38 | /* for (int i= 0;i<100;i++){ 39 | this.primaryRepository.save(new User("小张1", "123456")); 40 | }*/ 41 | //this.secondaryRepository.save(new User("小王1", "654321")); 42 | /* List primaries = this.primaryRepository.findAll(); 43 | for (User primary : primaries) { 44 | System.out.println(primary.toString()); 45 | } 46 | List secondaries = this.secondaryRepository.findAll(); 47 | for (User secondary : secondaries) { 48 | System.out.println(secondary.toString()); 49 | }*/ 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/m1dao/MongoDao1.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.m1dao; 2 | 3 | import com.example.mongodbdemo.demo.test.User; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.mongodb.repository.MongoRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | /** 10 | * @description: 11 | * @author: Administrator 12 | * @create: 2019-07-02 20:21 13 | **/ 14 | public interface MongoDao1 extends MongoRepository { 15 | //分页 16 | Page findAll(Pageable var1); 17 | } 18 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/m2dao/MongoDao2.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.m2dao; 2 | 3 | import com.example.mongodbdemo.demo.test.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * @description: 9 | * @author: Administrator 10 | * @create: 2019-07-02 20:21 11 | **/ 12 | public interface MongoDao2 extends MongoRepository { 13 | } 14 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/test/MongoConfig1.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.test; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 6 | 7 | /** 8 | 9 | 最后将 MongoTemplate 信息注入到对应的包路径下: 10 | **/ 11 | @Configuration 12 | @EnableConfigurationProperties(MultipleMongoProperties.class) 13 | @EnableMongoRepositories(basePackages = "com.example.mongodbdemo.demo.m1dao", mongoTemplateRef = "primaryMongoTemplate") 14 | public class MongoConfig1 { 15 | } 16 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/test/MongoConfig2.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.test; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 6 | 7 | /** 8 | 9 | 最后将 MongoTemplate 信息注入到对应的包路径下: 10 | **/ 11 | @Configuration 12 | @EnableConfigurationProperties(MultipleMongoProperties.class) 13 | @EnableMongoRepositories(basePackages = "com.example.mongodbdemo.demo.m2dao", mongoTemplateRef = "secondaryMongoTemplate") 14 | public class MongoConfig2 { 15 | } 16 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/test/MultipleMongoConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.test; 2 | 3 | import com.mongodb.MongoClient; 4 | import com.mongodb.MongoClientURI; 5 | import com.mongodb.client.jndi.MongoClientFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.boot.autoconfigure.mongo.MongoProperties; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.context.annotation.Primary; 12 | import org.springframework.data.mongodb.MongoDbFactory; 13 | import org.springframework.data.mongodb.core.MongoTemplate; 14 | import org.springframework.data.mongodb.core.SimpleMongoDbFactory; 15 | import org.springframework.stereotype.Component; 16 | 17 | /** 18 | 创建两个数据源的 MongoTemplate。 19 | **/ 20 | @Configuration 21 | public class MultipleMongoConfig { 22 | 23 | 24 | @Autowired 25 | private MultipleMongoProperties mongoProperties; 26 | 27 | @Primary 28 | @Bean(name = "primaryMongoTemplate") 29 | public MongoTemplate primaryMongoTemplate() throws Exception { 30 | return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary())); 31 | } 32 | 33 | @Bean 34 | @Qualifier("secondaryMongoTemplate") 35 | public MongoTemplate secondaryMongoTemplate() throws Exception { 36 | return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary())); 37 | } 38 | 39 | @Bean 40 | @Primary 41 | public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception { 42 | MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getPrimary().getUri())); 43 | return new SimpleMongoDbFactory(client, mongoProperties.getPrimary().getDatabase()); 44 | } 45 | 46 | @Bean 47 | public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception { 48 | MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getSecondary().getUri())); 49 | return new SimpleMongoDbFactory(client, mongoProperties.getSecondary().getDatabase()); 50 | } 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/test/MultipleMongoProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.test; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.autoconfigure.mongo.MongoProperties; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | 封装读取以 MongoDB 开头的两个配置文件: 10 | **/ 11 | @ConfigurationProperties(prefix = "mongodb") 12 | @Data 13 | public class MultipleMongoProperties { 14 | 15 | private MongoProperties primary = new MongoProperties(); 16 | private MongoProperties secondary = new MongoProperties(); 17 | } 18 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/java/com/example/mongodbdemo/demo/test/User.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo.test; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import sun.dc.pr.PRError; 6 | 7 | /** 8 | * @description: 9 | * @author: Administrator 10 | * @create: 2019-07-02 19:53 11 | **/ 12 | @Data 13 | @AllArgsConstructor 14 | public class User { 15 | private String userName; 16 | private String password; 17 | } 18 | -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 多个 IP 集群可以采用以下配置: 5 | #spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database 6 | 7 | 8 | 9 | 10 | #无用户名密码配置 11 | #spring.data.mongodb.uri=mongodb://localhost:27017/test,47.94.216.99:27071/test 12 | 13 | #spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test 14 | 15 | 16 | #一库 17 | mongodb.primary.uri=mongodb://localhost:27017 18 | mongodb.primary.database=test 19 | #二库 20 | mongodb.secondary.uri=mongodb://127.0.0.1:27018 21 | mongodb.secondary.database=test -------------------------------------------------------------------------------- /Springboot-MongodbDemo/src/test/java/com/example/mongodbdemo/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.mongodbdemo.demo; 2 | 3 | import com.example.mongodbdemo.demo.m1dao.MongoDao1; 4 | import com.example.mongodbdemo.demo.m2dao.MongoDao2; 5 | import com.example.mongodbdemo.demo.test.User; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.List; 13 | 14 | @RunWith(SpringRunner.class) 15 | @SpringBootTest 16 | public class DemoApplicationTests { 17 | 18 | @Test 19 | public void contextLoads() { 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Springboot-Redis-SETEX/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-session/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /spring-session/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pomestyle/SpringBoot/b76d55e8410d811de23a03597d6714eb087766bb/spring-session/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-session/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /spring-session/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.5.RELEASE 9 | 10 | 11 | com.example.spring-session 12 | demo 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | 31 | org.springframework.session 32 | spring-session-data-redis 33 | 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-data-redis 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.apache.commons 47 | commons-pool2 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-devtools 55 | true 56 | 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-test 62 | test 63 | 64 | 65 | org.projectlombok 66 | lombok 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-maven-plugin 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /spring-session/src/main/java/com/example/springsession/demo/Config/SessionConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springsession.demo.Config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; 5 | 6 | /** 7 | * 8 | * maxInactiveIntervalInSeconds: 设置 Session 失效时间,使用 Redis Session 之后,原 Spring Boot 中的 server.session.timeout 属性不再生效。 9 | * 10 | */ 11 | @Configuration 12 | @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) 13 | public class SessionConfig { 14 | } -------------------------------------------------------------------------------- /spring-session/src/main/java/com/example/springsession/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springsession.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-session/src/main/java/com/example/springsession/demo/jpa/StudentController.java: -------------------------------------------------------------------------------- 1 | 2 | package com.example.springsession.demo.jpa; 3 | 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import java.time.LocalDate; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * @description: 17 | * @author: Administrator 18 | * @create: 2019-06-29 15:23 19 | **/ 20 | 21 | 22 | @RestController 23 | public class StudentController { 24 | 25 | 26 | 27 | @RequestMapping(value = "/setSession") 28 | public Map setSession (HttpServletRequest request){ 29 | Map map = new HashMap<>(); 30 | request.getSession().setAttribute("message", request.getRequestURL()); 31 | map.put("request Url", request.getRequestURL()); 32 | return map; 33 | } 34 | 35 | @RequestMapping(value = "/getSession") 36 | public Object getSession (HttpServletRequest request){ 37 | Map map = new HashMap<>(); 38 | map.put("sessionId", request.getSession().getId()); 39 | map.put("message", request.getSession().getAttribute("message")); 40 | return map; 41 | } 42 | 43 | 44 | @RequestMapping(value = "/login") 45 | public String login (HttpServletRequest request,String userName,String password){ 46 | System.out.println(request.getSession().getId()); 47 | String msg="logon failure!"; 48 | 49 | if (userName!=null && "admin".equals(userName) && "123".equals(password)){ 50 | request.getSession().setAttribute("user",userName); 51 | msg="login successful!"; 52 | } 53 | return msg; 54 | } 55 | 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /spring-session/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pomestyle/SpringBoot/b76d55e8410d811de23a03597d6714eb087766bb/spring-session/src/main/resources/application.properties -------------------------------------------------------------------------------- /spring-session/src/test/java/com/example/springsession/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springsession.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /springBoot-redis/SpringBoot-Redis/README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot-Redis 2 | SpringBoot 整合Redis哨兵和cluster集群模式 3 | -------------------------------------------------------------------------------- /springBoot-redis/SpringBoot-Redis/redis-cluster/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springBoot-redis/SpringBoot-Redis/sentinel-redis/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springboot-atomikos/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springboot-atomikos/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.6.RELEASE 9 | 10 | 11 | com.example 12 | springbootatomikos 13 | 0.0.1-SNAPSHOT 14 | springbootatomikos 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-jta-atomikos 37 | 38 | 39 | 40 | 41 | org.mybatis.spring.boot 42 | mybatis-spring-boot-starter 43 | 1.3.5 44 | 45 | 46 | 47 | mysql 48 | mysql-connector-java 49 | 5.1.5 50 | 51 | 52 | 53 | 54 | org.projectlombok 55 | lombok 56 | 1.16.10 57 | provided 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/SpringbootatomikosApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos; 2 | 3 | import com.example.springbootatomikos.pojo.User; 4 | import com.example.springbootatomikos.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @SpringBootApplication 12 | @RestController 13 | public class SpringbootatomikosApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SpringbootatomikosApplication.class, args); 17 | } 18 | 19 | @Autowired 20 | private UserService userService; 21 | 22 | @RequestMapping("test") 23 | public void test(){ 24 | User user = new User(); 25 | user.setName("lynn"); 26 | user.setAge(10); 27 | try { 28 | userService.addUser(user); 29 | }catch (Exception e){ 30 | e.printStackTrace(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/config/one/MyBatisConfig1.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.config.one; 2 | 3 | import com.example.springbootatomikos.config.pojo.DBConfig1; 4 | import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.mybatis.spring.annotation.MapperScan; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.boot.SpringBootConfiguration; 11 | import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Primary; 14 | 15 | import javax.sql.DataSource; 16 | import java.sql.SQLException; 17 | 18 | /** 19 | * @description: 数据源1配置 20 | * @author: Administrator 21 | * @create: 2020-05-02 19:25 22 | **/ 23 | @SpringBootConfiguration 24 | @MapperScan(basePackages = "com.example.springbootatomikos.mapper.one", sqlSessionTemplateRef = "sqlSessionTemplate") 25 | public class MyBatisConfig1 { 26 | 27 | // 配置数据源 28 | @Primary 29 | @Bean(name = "dataSource") 30 | public DataSource dataSource(DBConfig1 config) throws SQLException { 31 | MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); 32 | mysqlXaDataSource.setUrl(config.getUrl()); 33 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 34 | mysqlXaDataSource.setPassword(config.getPassword()); 35 | mysqlXaDataSource.setUser(config.getUsername()); 36 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 37 | 38 | AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); 39 | xaDataSource.setXaDataSource(mysqlXaDataSource); 40 | xaDataSource.setUniqueResourceName("dataSource"); 41 | 42 | xaDataSource.setMinPoolSize(config.getMinPoolSize()); 43 | xaDataSource.setMaxPoolSize(config.getMaxPoolSize()); 44 | xaDataSource.setMaxLifetime(config.getMaxLifetime()); 45 | xaDataSource.setBorrowConnectionTimeout(config.getBorrowConnectionTimeout()); 46 | xaDataSource.setLoginTimeout(config.getLoginTimeout()); 47 | xaDataSource.setMaintenanceInterval(config.getMaintenanceInterval()); 48 | xaDataSource.setMaxIdleTime(config.getMaxIdleTime()); 49 | xaDataSource.setTestQuery(config.getTestQuery()); 50 | return xaDataSource; 51 | } 52 | @Primary 53 | @Bean(name = "sqlSessionFactory") 54 | public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) 55 | throws Exception { 56 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 57 | bean.setDataSource(dataSource); 58 | return bean.getObject(); 59 | } 60 | 61 | @Primary 62 | @Bean(name = "sqlSessionTemplate") 63 | public SqlSessionTemplate sqlSessionTemplate( 64 | @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 65 | return new SqlSessionTemplate(sqlSessionFactory); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/config/pojo/DBConfig1.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.config.pojo; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.SpringBootConfiguration; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | 7 | /** 8 | * @description: 数据源test1 9 | * @author: Administrator 10 | * @create: 2020-05-02 19:22 11 | **/ 12 | @ConfigurationProperties(prefix = "mysql.datasource.test1") 13 | @SpringBootConfiguration 14 | public class DBConfig1 { 15 | 16 | private String url; 17 | private String username; 18 | private String password; 19 | private int minPoolSize; 20 | private int maxPoolSize; 21 | private int maxLifetime; 22 | private int borrowConnectionTimeout; 23 | private int loginTimeout; 24 | private int maintenanceInterval; 25 | private int maxIdleTime; 26 | private String testQuery; 27 | 28 | 29 | public String getUrl() { 30 | return url; 31 | } 32 | 33 | public void setUrl(String url) { 34 | this.url = url; 35 | } 36 | 37 | public String getUsername() { 38 | return username; 39 | } 40 | 41 | public void setUsername(String username) { 42 | this.username = username; 43 | } 44 | 45 | public String getPassword() { 46 | return password; 47 | } 48 | 49 | public void setPassword(String password) { 50 | this.password = password; 51 | } 52 | 53 | public int getMinPoolSize() { 54 | return minPoolSize; 55 | } 56 | 57 | public void setMinPoolSize(int minPoolSize) { 58 | this.minPoolSize = minPoolSize; 59 | } 60 | 61 | public int getMaxPoolSize() { 62 | return maxPoolSize; 63 | } 64 | 65 | public void setMaxPoolSize(int maxPoolSize) { 66 | this.maxPoolSize = maxPoolSize; 67 | } 68 | 69 | public int getMaxLifetime() { 70 | return maxLifetime; 71 | } 72 | 73 | public void setMaxLifetime(int maxLifetime) { 74 | this.maxLifetime = maxLifetime; 75 | } 76 | 77 | public int getBorrowConnectionTimeout() { 78 | return borrowConnectionTimeout; 79 | } 80 | 81 | public void setBorrowConnectionTimeout(int borrowConnectionTimeout) { 82 | this.borrowConnectionTimeout = borrowConnectionTimeout; 83 | } 84 | 85 | public int getLoginTimeout() { 86 | return loginTimeout; 87 | } 88 | 89 | public void setLoginTimeout(int loginTimeout) { 90 | this.loginTimeout = loginTimeout; 91 | } 92 | 93 | public int getMaintenanceInterval() { 94 | return maintenanceInterval; 95 | } 96 | 97 | public void setMaintenanceInterval(int maintenanceInterval) { 98 | this.maintenanceInterval = maintenanceInterval; 99 | } 100 | 101 | public int getMaxIdleTime() { 102 | return maxIdleTime; 103 | } 104 | 105 | public void setMaxIdleTime(int maxIdleTime) { 106 | this.maxIdleTime = maxIdleTime; 107 | } 108 | 109 | public String getTestQuery() { 110 | return testQuery; 111 | } 112 | 113 | public void setTestQuery(String testQuery) { 114 | this.testQuery = testQuery; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/config/pojo/DBConfig2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.config.pojo; 2 | 3 | import org.springframework.boot.SpringBootConfiguration; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | /** 7 | * @description: 数据源test2 8 | * @author: Administrator 9 | * @create: 2020-05-02 19:22 10 | **/ 11 | @ConfigurationProperties(prefix = "mysql.datasource.test2") 12 | @SpringBootConfiguration 13 | public class DBConfig2 { 14 | 15 | private String url; 16 | private String username; 17 | private String password; 18 | private int minPoolSize; 19 | private int maxPoolSize; 20 | private int maxLifetime; 21 | private int borrowConnectionTimeout; 22 | private int loginTimeout; 23 | private int maintenanceInterval; 24 | private int maxIdleTime; 25 | private String testQuery; 26 | 27 | public String getUrl() { 28 | return url; 29 | } 30 | 31 | public void setUrl(String url) { 32 | this.url = url; 33 | } 34 | 35 | public String getUsername() { 36 | return username; 37 | } 38 | 39 | public void setUsername(String username) { 40 | this.username = username; 41 | } 42 | 43 | public String getPassword() { 44 | return password; 45 | } 46 | 47 | public void setPassword(String password) { 48 | this.password = password; 49 | } 50 | 51 | public int getMinPoolSize() { 52 | return minPoolSize; 53 | } 54 | 55 | public void setMinPoolSize(int minPoolSize) { 56 | this.minPoolSize = minPoolSize; 57 | } 58 | 59 | public int getMaxPoolSize() { 60 | return maxPoolSize; 61 | } 62 | 63 | public void setMaxPoolSize(int maxPoolSize) { 64 | this.maxPoolSize = maxPoolSize; 65 | } 66 | 67 | public int getMaxLifetime() { 68 | return maxLifetime; 69 | } 70 | 71 | public void setMaxLifetime(int maxLifetime) { 72 | this.maxLifetime = maxLifetime; 73 | } 74 | 75 | public int getBorrowConnectionTimeout() { 76 | return borrowConnectionTimeout; 77 | } 78 | 79 | public void setBorrowConnectionTimeout(int borrowConnectionTimeout) { 80 | this.borrowConnectionTimeout = borrowConnectionTimeout; 81 | } 82 | 83 | public int getLoginTimeout() { 84 | return loginTimeout; 85 | } 86 | 87 | public void setLoginTimeout(int loginTimeout) { 88 | this.loginTimeout = loginTimeout; 89 | } 90 | 91 | public int getMaintenanceInterval() { 92 | return maintenanceInterval; 93 | } 94 | 95 | public void setMaintenanceInterval(int maintenanceInterval) { 96 | this.maintenanceInterval = maintenanceInterval; 97 | } 98 | 99 | public int getMaxIdleTime() { 100 | return maxIdleTime; 101 | } 102 | 103 | public void setMaxIdleTime(int maxIdleTime) { 104 | this.maxIdleTime = maxIdleTime; 105 | } 106 | 107 | public String getTestQuery() { 108 | return testQuery; 109 | } 110 | 111 | public void setTestQuery(String testQuery) { 112 | this.testQuery = testQuery; 113 | } 114 | } 115 | 116 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/config/two/MyBatisConfig2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.config.two; 2 | 3 | import com.example.springbootatomikos.config.pojo.DBConfig2; 4 | import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.mybatis.spring.SqlSessionFactoryBean; 7 | import org.mybatis.spring.SqlSessionTemplate; 8 | import org.mybatis.spring.annotation.MapperScan; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.boot.SpringBootConfiguration; 11 | import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; 12 | import org.springframework.context.annotation.Bean; 13 | 14 | import javax.sql.DataSource; 15 | import java.sql.SQLException; 16 | 17 | /** 18 | * @description: 数据源2配置 19 | * @author: Administrator 20 | * @create: 2020-05-02 19:26 21 | **/ 22 | @SpringBootConfiguration 23 | //basePackages 最好分开配置 如果放在同一个文件夹可能会报错 24 | @MapperScan(basePackages = "com.example.springbootatomikos.mapper.two", sqlSessionTemplateRef = "sqlSessionTemplate2") 25 | public class MyBatisConfig2 { 26 | 27 | // 配置数据源 28 | @Bean(name = "dataSource2") 29 | public DataSource dataSource(DBConfig2 config) throws SQLException { 30 | MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); 31 | mysqlXaDataSource.setUrl(config.getUrl()); 32 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 33 | mysqlXaDataSource.setPassword(config.getPassword()); 34 | mysqlXaDataSource.setUser(config.getUsername()); 35 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 36 | 37 | AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); 38 | xaDataSource.setXaDataSource(mysqlXaDataSource); 39 | xaDataSource.setUniqueResourceName("dataSource2"); 40 | 41 | xaDataSource.setMinPoolSize(config.getMinPoolSize()); 42 | xaDataSource.setMaxPoolSize(config.getMaxPoolSize()); 43 | xaDataSource.setMaxLifetime(config.getMaxLifetime()); 44 | xaDataSource.setBorrowConnectionTimeout(config.getBorrowConnectionTimeout()); 45 | xaDataSource.setLoginTimeout(config.getLoginTimeout()); 46 | xaDataSource.setMaintenanceInterval(config.getMaintenanceInterval()); 47 | xaDataSource.setMaxIdleTime(config.getMaxIdleTime()); 48 | xaDataSource.setTestQuery(config.getTestQuery()); 49 | return xaDataSource; 50 | } 51 | 52 | @Bean(name = "sqlSessionFactory2") 53 | public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) 54 | throws Exception { 55 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 56 | bean.setDataSource(dataSource); 57 | return bean.getObject(); 58 | } 59 | 60 | @Bean(name = "sqlSessionTemplate2") 61 | public SqlSessionTemplate sqlSessionTemplate( 62 | @Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception { 63 | return new SqlSessionTemplate(sqlSessionFactory); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/mapper/one/UserMapper1.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.mapper.one; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | /** 8 | * @description: 9 | * @author: Administrator 10 | * @create: 2020-05-02 19:27 11 | **/ 12 | @Mapper 13 | public interface UserMapper1 { 14 | 15 | @Insert("insert into test_user1(name,age) values(#{name},#{age})") 16 | void addUser(@Param("name")String name, @Param("age") int age); 17 | } 18 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/mapper/two/UserMapper2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.mapper.two; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | /** 8 | * @description: 9 | * @author: Administrator 10 | * @create: 2020-05-02 19:27 11 | **/ 12 | @Mapper 13 | public interface UserMapper2 { 14 | 15 | @Insert("insert into test_user2(name,age) values(#{name},#{age})") 16 | void addUser(@Param("name") String name, @Param("age") int age); 17 | } 18 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/pojo/User.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.pojo; 2 | 3 | import lombok.EqualsAndHashCode; 4 | 5 | /** 6 | * @description: 用户类 7 | * @author: Administrator 8 | * @create: 2020-05-02 19:29 9 | **/ 10 | @EqualsAndHashCode 11 | public class User { 12 | 13 | private Long id; 14 | private String name; 15 | private int age; 16 | 17 | 18 | public Long getId() { 19 | return id; 20 | } 21 | 22 | public void setId(Long id) { 23 | this.id = id; 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | public int getAge() { 35 | return age; 36 | } 37 | 38 | public void setAge(int age) { 39 | this.age = age; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /springboot-atomikos/src/main/java/com/example/springbootatomikos/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos.service; 2 | 3 | import com.example.springbootatomikos.mapper.one.UserMapper1; 4 | import com.example.springbootatomikos.mapper.two.UserMapper2; 5 | import com.example.springbootatomikos.pojo.User; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import javax.transaction.Transactional; 10 | 11 | /** 12 | * @description: 业务类 13 | * @author: Administrator 14 | * @create: 2020-05-02 19:27 15 | **/ 16 | @Service 17 | public class UserService { 18 | 19 | @Autowired 20 | private UserMapper1 userMapper1; 21 | @Autowired 22 | private UserMapper2 userMapper2; 23 | 24 | @Transactional 25 | public void addUser(User user)throws Exception{ 26 | userMapper1.addUser(user.getName(),user.getAge()); 27 | int a= 1/0; 28 | userMapper2.addUser(user.getName(),user.getAge()); 29 | } 30 | } -------------------------------------------------------------------------------- /springboot-atomikos/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | server: 3 | port: 8080 4 | spring: 5 | redis: 6 | host: localhost 7 | port: 6379 8 | mysql: 9 | datasource: 10 | test1: 11 | url: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8 12 | username: root 13 | password: root 14 | minPoolSize: 3 15 | maxPoolSize: 25 16 | maxLifetime: 20000 17 | borrowConnectionTimeout: 30 18 | loginTimeout: 30 19 | maintenanceInterval: 60 20 | maxIdleTime: 60 21 | testQuery: select 1 22 | test2: 23 | url: jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8 24 | username: root 25 | password: root 26 | minPoolSize: 3 27 | maxPoolSize: 25 28 | maxLifetime: 20000 29 | borrowConnectionTimeout: 30 30 | loginTimeout: 30 31 | maintenanceInterval: 60 32 | maxIdleTime: 60 33 | testQuery: select 1 -------------------------------------------------------------------------------- /springboot-atomikos/src/test/java/com/example/springbootatomikos/SpringbootatomikosApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootatomikos; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootatomikosApplicationTests { 11 | 12 | @Test 13 | void contextLoads() { 14 | } 15 | 16 | 17 | } 18 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.0.5.RELEASE 9 | 10 | 11 | com.example 12 | springboot-handlerinterceptor 13 | 0.0.1-SNAPSHOT 14 | springboot-handlerinterceptor 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | true 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | io.projectreactor 39 | reactor-test 40 | test 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/SpringbootHandlerinterceptorApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootHandlerinterceptorApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootHandlerinterceptorApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/config/MyHandlerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.web.method.HandlerMethod; 6 | import org.springframework.web.servlet.HandlerInterceptor; 7 | import org.springframework.web.servlet.ModelAndView; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.lang.reflect.Method; 12 | 13 | /** 14 | * @description: 自定义拦截器 15 | * @author: Administrator 16 | * @create: 2019-07-06 18:18 17 | **/ 18 | 19 | public class MyHandlerInterceptor implements HandlerInterceptor { 20 | 21 | private static final Logger logger = LoggerFactory.getLogger(MyHandlerInterceptor.class); 22 | 23 | /** 24 | * @description: 拦截在控制方法之前拦截 25 | * 26 | * ,当某个 URL 已经匹配到对应的 Controller 中的某个方法,且在这个方法执行之前。 27 | * 所以 preHandle(……) 方法可以决定是否将请求放行,这是通过返回值来决定的,返回 true 则放行,返回 false 则不会向后执行。 28 | * 29 | * @author: wangl 30 | * @create: 2019-07-06 18:19 31 | * @version 1.0 32 | **/ 33 | 34 | @Override 35 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 36 | HandlerMethod handlerMethod = (HandlerMethod) handler; 37 | Method method = handlerMethod.getMethod(); 38 | String methodName = method.getName(); 39 | logger.info("==== preHandle ===== 拦截到了方法:{},在该方法执行之前执行====",methodName); 40 | 41 | System.out.println(((HandlerMethod) handler).getMethod().getName()); 42 | // 返回 true 才会继续执行,返回 false 则取消当前请求 43 | 44 | 45 | 46 | // 判断用户有没有登陆,一般登陆之后的用户都有一个对应的 token 47 | String token = request.getParameter("token"); 48 | if (null == token || "".equals(token)) { 49 | logger.info("用户未登录,没有权限执行……请登录"); 50 | response.getWriter().println("error"); 51 | return false; 52 | } 53 | 54 | // 返回 true 才会继续执行,返回 false 则取消当前请求 55 | return true; 56 | } 57 | 58 | /** 59 | * @description: 在渲染页面之前拦截 60 | 该方法的执行时机是,当某个 URL 已经匹配到对应的 Controller 中的某个方法,且在执行完了该方法,但是在 DispatcherServlet 视图渲染之前。 61 | 所以在这个方法中有个 ModelAndView 参数,可以在此做一些修改动作。 62 | * @author: wangl 63 | * @create: 2019-07-06 18:20 64 | * @version 1.0 65 | **/ 66 | @Override 67 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 68 | logger.info("=================== postHandle ================== 执行完方法之后进执行(Controller方法调用之后),但是此时还没进行视图渲染"); 69 | } 70 | 71 | /** 72 | * @description: 在控制方法正确返回后拦截 73 | * 74 | * 该方法是在整个请求处理完成后(包括视图渲染)执行,这时做一些资源的清理工作, 75 | * 这个方法只有在 preHandle(……) 被成功执行后并且返回 true 才会被执行。 76 | * @author: wangl 77 | * @create: 2019-07-06 18:20 78 | * @version 1.0 79 | **/ 80 | @Override 81 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 82 | logger.info("============ afterCompletion =================== 整个请求都处理完咯,DispatcherServlet也渲染了对应的视图咯,此时我可以做一些清理的工作了"); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/config/MyInterceptorConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor.config; 2 | 3 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 4 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 6 | 7 | /** 8 | * @description: 配置拦截器 9 | * @author: Administrator 10 | * @create: 2019-07-06 18:23 11 | **/ 12 | //@Configuration 13 | public class MyInterceptorConfig extends WebMvcConfigurationSupport { 14 | @Override 15 | protected void addInterceptors(InterceptorRegistry registry) { 16 | //配置拦截所有请求 17 | registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/**"); 18 | super.addInterceptors(registry); 19 | } 20 | 21 | @Override 22 | protected void addResourceHandlers(ResourceHandlerRegistry registry) { 23 | registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/static/"); 24 | super.addResourceHandlers(registry); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/config/MyInterceptorConfig2.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | /** 8 | * @description: 配置拦截器 9 | * @author: Administrator 10 | * @create: 2019-07-06 18:23 11 | **/ 12 | @Configuration 13 | public class MyInterceptorConfig2 implements WebMvcConfigurer{ 14 | @Override 15 | public void addInterceptors(InterceptorRegistry registry) { 16 | //配置拦截所有请求 17 | registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/**"); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | /** 9 | * @description: 10 | * @author: Administrator 11 | * @create: 2019-07-06 17:29 12 | **/ 13 | @RestController 14 | public class TestController { 15 | 16 | @GetMapping("/") 17 | public String getRequestInfo(HttpServletRequest request) { 18 | System.out.println("getRequestInfo " ); 19 | return "index"; 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/java/com/example/springboothandlerinterceptor/other/User.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor.other; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | /** 7 | * @description: 8 | * @author: Administrator 9 | * @create: 2019-07-06 17:22 10 | **/ 11 | @Data 12 | @AllArgsConstructor 13 | public class User { 14 | 15 | private Long id; 16 | private String name; 17 | private String pass; 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.servlet.path=/a 2 | spring.application.name=a 3 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/resources/static/a.txt: -------------------------------------------------------------------------------- 1 | 12312312321312 -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/resources/static/css/a.css: -------------------------------------------------------------------------------- 1 | a{ 2 | animation: inherit; 3 | } -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 1111111111111111111111 10 | 11 | -------------------------------------------------------------------------------- /springboot-handlerinterceptor/src/test/java/com/example/springboothandlerinterceptor/SpringbootHandlerinterceptorApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springboothandlerinterceptor; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootHandlerinterceptorApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /springboot-listener-demo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springboot-listener-demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pomestyle/SpringBoot/b76d55e8410d811de23a03597d6714eb087766bb/springboot-listener-demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /springboot-listener-demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /springboot-listener-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.6.RELEASE 9 | 10 | 11 | com.example 12 | springboot-listener-demo 13 | 0.0.1-SNAPSHOT 14 | springboot-listener-demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | true 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-maven-plugin 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/SpringbootListenerDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootListenerDemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootListenerDemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/bean/User.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.bean; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | /** 7 | * @description: 8 | * @author: Administrator 9 | * @create: 2019-07-06 17:22 10 | **/ 11 | @Data 12 | @AllArgsConstructor 13 | public class User { 14 | 15 | private Long id; 16 | private String name; 17 | private String pass; 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.controller; 2 | 3 | import com.example.springbootlistenerdemo.bean.User; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import javax.servlet.ServletContext; 9 | import javax.servlet.http.Cookie; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.UnsupportedEncodingException; 13 | import java.net.URLEncoder; 14 | 15 | /** 16 | * @description: 17 | * @author: Administrator 18 | * @create: 2019-07-06 17:29 19 | **/ 20 | @RestController 21 | @RequestMapping("/listener") 22 | public class TestController { 23 | 24 | @GetMapping("/user") 25 | public User getUser(HttpServletRequest request) { 26 | ServletContext application = request.getServletContext(); 27 | return (User) application.getAttribute("user"); 28 | } 29 | 30 | 31 | /** 32 | * 获取当前在线人数,该方法有bug 33 | * @param request 34 | * @return 35 | */ 36 | @GetMapping("/total") 37 | public String getTotalUser(HttpServletRequest request) { 38 | Integer count = (Integer) request.getSession().getServletContext().getAttribute("count"); 39 | return "当前在线人数:" + count; 40 | } 41 | 42 | @GetMapping("/total2") 43 | public String getTotalUser(HttpServletRequest request, HttpServletResponse response) { 44 | Cookie cookie; 45 | try { 46 | // 把 sessionId 记录在浏览器中 47 | cookie = new Cookie("JSESSIONID", URLEncoder.encode(request.getSession().getId(), "utf-8")); 48 | cookie.setPath("/"); 49 | //设置 cookie 有效期为 2 天,设置长一点 50 | cookie.setMaxAge( 48*60 * 60); 51 | response.addCookie(cookie); 52 | } catch (UnsupportedEncodingException e) { 53 | e.printStackTrace(); 54 | } 55 | Integer count = (Integer) request.getSession().getServletContext().getAttribute("count"); 56 | return "当前在线人数:" + count; 57 | } 58 | 59 | 60 | 61 | @GetMapping("/request") 62 | public String getRequestInfo(HttpServletRequest request) { 63 | System.out.println("requestListener中的初始化的name数据:" + request.getAttribute("name")); 64 | return "success"; 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/listener/MyEvent.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.listener; 2 | 3 | import com.example.springbootlistenerdemo.bean.User; 4 | import lombok.Data; 5 | import org.springframework.context.ApplicationEvent; 6 | 7 | /** 8 | * @description: 自定义事件 9 | * @author: Administrator 10 | * @create: 2019-07-06 18:02 11 | **/ 12 | @Data 13 | public class MyEvent extends ApplicationEvent { 14 | 15 | private User user; 16 | 17 | public MyEvent(Object source, User user) { 18 | super(source); 19 | this.user = user; 20 | } 21 | } -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/listener/MyEventListener.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.listener; 2 | 3 | import com.example.springbootlistenerdemo.bean.User; 4 | import org.springframework.context.ApplicationListener; 5 | import org.springframework.stereotype.Component; 6 | 7 | /** 8 | * @description: 自定义监听器,监听 MyEvent 事件 9 | * @author: Administrator 10 | * @create: 2019-07-06 18:03 11 | **/ 12 | @Component 13 | public class MyEventListener implements ApplicationListener { 14 | @Override 15 | public void onApplicationEvent(MyEvent myEvent) { 16 | // 把事件中的信息获取到 17 | User user = myEvent.getUser(); 18 | // 处理事件,实际项目中可以通知别的微服务或者处理其他逻辑等 19 | System.out.println("用户名:" + user.getName()); 20 | System.out.println("密码:" + user.getPass()); 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/listener/MyHttpSessionListener.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.listener; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpSessionEvent; 8 | import javax.servlet.http.HttpSessionListener; 9 | 10 | /** 11 | * @description: 用 HttpSessionListener 统计在线用户数的监听器 12 | * @author: Administrator 13 | * @create: 2019-07-06 17:44 14 | **/ 15 | @Component 16 | public class MyHttpSessionListener implements HttpSessionListener { 17 | 18 | private static final Logger logger = LoggerFactory.getLogger(MyHttpSessionListener.class); 19 | 20 | /** 21 | * 记录在线的用户数量 22 | */ 23 | public Integer count = 0; 24 | 25 | @Override 26 | public synchronized void sessionCreated(HttpSessionEvent httpSessionEvent) { 27 | logger.info("新用户上线了"); 28 | count++; 29 | httpSessionEvent.getSession().getServletContext().setAttribute("count", count); 30 | } 31 | 32 | @Override 33 | public synchronized void sessionDestroyed(HttpSessionEvent httpSessionEvent) { 34 | logger.info("用户下线了"); 35 | count--; 36 | httpSessionEvent.getSession().getServletContext().setAttribute("count", count); 37 | httpSessionEvent.getSession().invalidate(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/listener/MyServletContextListener.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.listener; 2 | 3 | import com.example.springbootlistenerdemo.bean.User; 4 | import com.example.springbootlistenerdemo.services.UserService; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ApplicationListener; 7 | import org.springframework.context.event.ContextRefreshedEvent; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.servlet.ServletContext; 11 | 12 | /** 13 | * @description: 使用 ApplicationListener 来初始化一些数据到 application 域中的监听器 14 | * @author: Administrator 15 | * @create: 2019-07-06 17:24 16 | **/ 17 | @Component 18 | public class MyServletContextListener implements ApplicationListener { 19 | @Override 20 | public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { 21 | 22 | //获取上下文对象 23 | ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext(); 24 | 25 | // 获取对应的 service 26 | UserService userService = applicationContext.getBean(UserService.class); 27 | User user = userService.getUser(); 28 | // 获取 application 域对象,将查到的信息放到 application 域中 29 | ServletContext application = applicationContext.getBean(ServletContext.class); 30 | application.setAttribute("user", user); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/listener/MyServletRequestListener.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.listener; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.ServletRequestEvent; 8 | import javax.servlet.ServletRequestListener; 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | /** 12 | * @description: 使用 ServletRequestListener 获取访问信息 13 | * @author: Administrator 14 | * @create: 2019-07-06 17:59 15 | **/ 16 | @Component 17 | public class MyServletRequestListener implements ServletRequestListener { 18 | 19 | private static final Logger logger = LoggerFactory.getLogger(MyServletRequestListener.class); 20 | 21 | @Override 22 | public void requestInitialized(ServletRequestEvent servletRequestEvent) { 23 | HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest(); 24 | logger.info("session id为:{}", request.getRequestedSessionId()); 25 | logger.info("request url为:{}", request.getRequestURL()); 26 | 27 | request.setAttribute("name", "tizzy"); 28 | } 29 | 30 | @Override 31 | public void requestDestroyed(ServletRequestEvent servletRequestEvent) { 32 | 33 | logger.info("request end"); 34 | HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest(); 35 | logger.info("request域中保存的name值为:{}", request.getAttribute("name")); 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/java/com/example/springbootlistenerdemo/services/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo.services; 2 | 3 | import com.example.springbootlistenerdemo.bean.User; 4 | import org.springframework.stereotype.Service; 5 | 6 | /** 7 | * @description: 8 | * @author: Administrator 9 | * @create: 2019-07-06 17:22 10 | **/ 11 | @Service 12 | public class UserService { 13 | /** 14 | * 获取用户信息 15 | * @return 16 | */ 17 | public User getUser() { 18 | // 实际中会根据具体的业务场景,从数据库中查询对应的信息 19 | return new User(1L, "tizzy", "123456"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | server.port=8080 3 | -------------------------------------------------------------------------------- /springboot-listener-demo/src/test/java/com/example/springbootlistenerdemo/SpringbootListenerDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootlistenerdemo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootListenerDemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /springbootCrudDemo/README.md: -------------------------------------------------------------------------------- 1 | # springbootDemo 2 | 3 | 4 | 5 | 6 | #### resources 里面包含sql脚本文件! 7 | #### 改项目是用eclipse 写的. 8 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/SpringBootDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.cache.annotation.EnableCaching; 8 | //import org.springframework.web.bind.annotation.RequestMapping; 9 | 10 | 11 | @SpringBootApplication 12 | @EnableCaching //开启redis缓存 13 | @MapperScan("com.example.demo.mapper") //扫描全部mapper 14 | 15 | public class SpringBootDemoApplication { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(SpringBootDemoApplication.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/common/beans.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.common; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.example.demo.pojo.User; 7 | 8 | @Configuration //相当于 xml beans 标签 9 | public class beans { 10 | 11 | 12 | @Bean("user1") // bean 13 | public User getUser1() { 14 | return new User(); 15 | } 16 | 17 | @Bean("user2") 18 | public User getUser2222() { 19 | 20 | User u = new User(); 21 | u.setAge(111); 22 | return u; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/controller/userController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.ui.Model; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | import org.springframework.web.servlet.ModelAndView; 12 | 13 | import com.example.demo.pojo.User; 14 | import com.example.demo.serviceImp.userServiceImp; 15 | 16 | //@Controller 17 | 18 | @RestController 19 | public class userController { 20 | 21 | @Autowired 22 | private userServiceImp userService; 23 | 24 | @Autowired 25 | @Qualifier("user1") 26 | private User user1; 27 | 28 | @Autowired 29 | @Qualifier("user2") 30 | private User user2; 31 | 32 | @RequestMapping("userLists") 33 | public List showUsers() { 34 | 35 | System.err.println(user1); 36 | System.err.println(user2); 37 | List list = userService.findAll(); 38 | 39 | return list; 40 | } 41 | 42 | @RequestMapping("showUser") 43 | public String showUser(Model model) { 44 | List list = userService.findAll(); 45 | 46 | model.addAttribute("user", list.get(0)); 47 | 48 | 49 | return "msg"; 50 | } 51 | 52 | @RequestMapping("showIndex") 53 | public ModelAndView showindex(Model model) { 54 | 55 | ModelAndView mv = new ModelAndView("userList"); 56 | List list = userService.findAll(); 57 | 58 | model.addAttribute("user", list.get(0)); 59 | return mv; 60 | } 61 | 62 | @RequestMapping("msg") 63 | public ModelAndView showindexs() { 64 | 65 | ModelAndView mv = new ModelAndView("index"); 66 | return mv; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/fiflter/fiflterTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.fiflter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.ServletRequest; 9 | import javax.servlet.ServletResponse; 10 | import javax.servlet.annotation.WebServlet; 11 | 12 | @WebServlet("/*") 13 | public class fiflterTest implements Filter{ 14 | 15 | @Override 16 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 17 | throws IOException, ServletException { 18 | 19 | System.err.println("拦截器。。。"); 20 | chain.doFilter(request, response); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/mapper/userMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.mapper; 2 | 3 | import java.util.List; 4 | 5 | import com.example.demo.pojo.User; 6 | 7 | 8 | public interface userMapper { 9 | 10 | public List findAll(); 11 | public void batchInsert(List userList); 12 | } 13 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/pojo/User.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.pojo; 2 | 3 | import java.io.Serializable; 4 | 5 | public class User implements Serializable { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = -6253572513712044837L; 10 | /** 11 | * 12 | */ 13 | private Long id; 14 | private String name; 15 | private int age; 16 | 17 | 18 | public Long getId() { 19 | return id; 20 | } 21 | 22 | public void setId(Long id) { 23 | this.id = id; 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | public int getAge() { 35 | return age; 36 | } 37 | 38 | public void setAge(int age) { 39 | this.age = age; 40 | } 41 | 42 | public User(Long id, String name, int age) { 43 | this.id = id; 44 | this.name = name; 45 | this.age = age; 46 | } 47 | 48 | 49 | public User( String name, int age) { 50 | this.name = name; 51 | this.age = age; 52 | } 53 | public User() { 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/service/userService.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import java.util.List; 4 | 5 | import com.example.demo.pojo.User; 6 | 7 | public interface userService { 8 | 9 | public List findAll(); 10 | //批量插入 11 | public void batchInsert(List userList); 12 | } 13 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/java/com/example/demo/serviceImp/userServiceImp.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.serviceImp; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.cache.annotation.Cacheable; 7 | import org.springframework.cache.annotation.Caching; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import com.example.demo.mapper.userMapper; 12 | import com.example.demo.pojo.User; 13 | import com.example.demo.service.userService; 14 | 15 | @Service 16 | public class userServiceImp implements userService { 17 | 18 | @Autowired 19 | private userMapper userMapper; 20 | 21 | //设置缓存 22 | @Cacheable(value="findAll") 23 | public List findAll() { 24 | // TODO Auto-generated method stub 25 | System.err.println("第二次没打印则说明,缓存成功。。。"); 26 | List list = userMapper.findAll(); 27 | return list; 28 | 29 | } 30 | 31 | @Override 32 | @Transactional 33 | public void batchInsert(List userList) { 34 | 35 | userMapper.batchInsert(userList); 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/resources/NewFile.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 狗蛋 5 | 17 6 | 7 | 8 | 李狗蛋 9 | 19 10 | 11 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #port 2 | #server.port=8181 3 | # mybatis 4 | mybatis.mapper-locations = classpath:mapper/*.xml 5 | 6 | mybatis.config-location = classpath:mapper/config/mybatis-config.xml 7 | # 8 | mybatis.type-aliases-package = com.example.demo.pojo 9 | ################# mysql ################# 10 | 11 | spring.datasource.url = jdbc:mysql://localhost:3306/user 12 | spring.datasource.driver-class-name = com.mysql.jdbc.Driver 13 | spring.datasource.username =root 14 | spring.datasource.password=root 15 | 16 | 17 | ################# jsp \u652F\u6301 ################# 18 | 19 | spring.mvc.view.prefix=/WEB-INF/jsp/ 20 | spring.view.suffix=.jsp 21 | 22 | #\u5173\u95ED\u9ED8\u8BA4\u6A21\u677F\u5F15\u64CE 23 | #spring.thymeleaf.cache = false 24 | #spring.thymeleaf.enabled = false 25 | 26 | ################# redis\u57FA\u7840\u914D\u7F6E ################# 27 | #spring.redis.database=5 28 | spring.redis.host=192.168.1.115 29 | #spring.redis.password=admin.1231 30 | spring.redis.port=6379 31 | # \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4 \u5355\u4F4D ms\uFF08\u6BEB\u79D2\uFF09 32 | #spring.redis.timeout=3000 33 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/resources/mapper/config/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/resources/mapper/userMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | insert into user VALUES 22 | 23 | 24 | 25 | (#{user.name},#{user.age}) 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/main/resources/sql/user.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : 127.0.0.1 5 | Source Server Version : 50720 6 | Source Host : localhost:3306 7 | Source Database : user 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50720 11 | File Encoding : 65001 12 | 13 | Date: 2018-07-19 23:28:45 14 | */ 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for `user` 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `user`; 22 | CREATE TABLE `user` ( 23 | `id` tinyint(4) NOT NULL AUTO_INCREMENT, 24 | `name` varchar(200) NOT NULL, 25 | `age` int(11) NOT NULL, 26 | PRIMARY KEY (`id`) 27 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 28 | 29 | -- ---------------------------- 30 | -- Records of user 31 | -- ---------------------------- 32 | INSERT INTO `user` VALUES ('1', 'zs', '11'); 33 | INSERT INTO `user` VALUES ('2', 'ww', '12'); 34 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/src/test/java/com/example/demo/SpringBootDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebApplicationContext; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import com.example.demo.pojo.User; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class SpringBootDemoApplicationTests { 16 | 17 | @Test 18 | public void contextLoads() { 19 | 20 | 21 | } 22 | 23 | 24 | @Test 25 | public void tesst() { 26 | ApplicationContext annotationContext = new AnnotationConfigApplicationContext("common"); 27 | User u1 = (User) annotationContext.getBean("user1"); 28 | User u2 = (User) annotationContext.getBean("user2"); 29 | 30 | User c = annotationContext.getBean("user1", User.class);// 创建 c = annotationContext.getBean("counter", Counter.class);// 创建 31 | 32 | System.out.println(u1+"\n" + u2 + c); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/classes/NewFile.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 狗蛋 5 | 17 6 | 7 | 8 | 李狗蛋 9 | 19 10 | 11 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/classes/application.properties: -------------------------------------------------------------------------------- 1 | #port 2 | #server.port=8181 3 | # mybatis 4 | mybatis.mapper-locations = classpath:mapper/*.xml 5 | 6 | mybatis.config-location = classpath:mapper/config/mybatis-config.xml 7 | # 8 | mybatis.type-aliases-package = com.example.demo.pojo 9 | ################# mysql ################# 10 | 11 | spring.datasource.url = jdbc:mysql://localhost:3306/user 12 | spring.datasource.driver-class-name = com.mysql.jdbc.Driver 13 | spring.datasource.username =root 14 | spring.datasource.password=root 15 | 16 | 17 | ################# jsp \u652F\u6301 ################# 18 | 19 | spring.mvc.view.prefix=/WEB-INF/jsp/ 20 | spring.view.suffix=.jsp 21 | 22 | #\u5173\u95ED\u9ED8\u8BA4\u6A21\u677F\u5F15\u64CE 23 | #spring.thymeleaf.cache = false 24 | #spring.thymeleaf.enabled = false 25 | 26 | ################# redis\u57FA\u7840\u914D\u7F6E ################# 27 | #spring.redis.database=5 28 | spring.redis.host=192.168.1.115 29 | #spring.redis.password=admin.1231 30 | spring.redis.port=6379 31 | # \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4 \u5355\u4F4D ms\uFF08\u6BEB\u79D2\uFF09 32 | #spring.redis.timeout=3000 33 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/classes/mapper/config/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/classes/mapper/userMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | insert into user VALUES 22 | 23 | 24 | 25 | (#{user.name},#{user.age}) 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/classes/sql/user.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : 127.0.0.1 5 | Source Server Version : 50720 6 | Source Host : localhost:3306 7 | Source Database : user 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50720 11 | File Encoding : 65001 12 | 13 | Date: 2018-07-19 23:28:45 14 | */ 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for `user` 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `user`; 22 | CREATE TABLE `user` ( 23 | `id` tinyint(4) NOT NULL AUTO_INCREMENT, 24 | `name` varchar(200) NOT NULL, 25 | `age` int(11) NOT NULL, 26 | PRIMARY KEY (`id`) 27 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 28 | 29 | -- ---------------------------- 30 | -- Records of user 31 | -- ---------------------------- 32 | INSERT INTO `user` VALUES ('1', 'zs', '11'); 33 | INSERT INTO `user` VALUES ('2', 'ww', '12'); 34 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/m2e-wtp/web-resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Implementation-Title: springBootDemo 3 | Implementation-Version: 0.0.1-SNAPSHOT 4 | Built-By: Administrator 5 | Implementation-Vendor-Id: com.example 6 | Build-Jdk: 1.8.0_66 7 | Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo 8 | ot-starter-parent/springBootDemo 9 | Created-By: Maven Integration for Eclipse 10 | 11 | -------------------------------------------------------------------------------- /springbootCrudDemo/springBootDemo/target/m2e-wtp/web-resources/META-INF/maven/com.example/springBootDemo/pom.properties: -------------------------------------------------------------------------------- 1 | #Generated by Maven Integration for Eclipse 2 | #Tue Mar 19 21:26:14 CST 2019 3 | version=0.0.1-SNAPSHOT 4 | groupId=com.example 5 | m2e.projectName=springBootDemo 6 | m2e.projectLocation=K\:\\eclipse-jee-oxygen-1a-win32-x86_64\\eclipse_new\\workspace\\springBootDemo 7 | artifactId=springBootDemo 8 | -------------------------------------------------------------------------------- /springsecuritydemo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /springsecuritydemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.0.RELEASE 9 | 10 | 11 | com.example 12 | springsecuritydemo 13 | 0.0.1-SNAPSHOT 14 | springsecuritydemo 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-security 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-devtools 34 | runtime 35 | true 36 | 37 | 38 | org.projectlombok 39 | lombok 40 | true 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-test 45 | test 46 | 47 | 48 | org.springframework.security 49 | spring-security-test 50 | test 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-thymeleaf 56 | 57 | 58 | 59 | org.thymeleaf.extras 60 | thymeleaf-extras-springsecurity5 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-maven-plugin 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/java/com/example/springsecuritydemo/SpringsecuritydemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecuritydemo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringsecuritydemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringsecuritydemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/java/com/example/springsecuritydemo/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecuritydemo.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.SecurityConfigurerAdapter; 6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 7 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | import org.springframework.stereotype.Component; 14 | 15 | /** 16 | * @description: 17 | * @author: Administrator 18 | * @create: 2019-07-03 22:54 19 | **/ 20 | @Configuration 21 | @EnableGlobalMethodSecurity(prePostEnabled = true) 22 | @EnableWebSecurity //开启 Spring Security 权限控制和认证功能。 23 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 24 | 25 | 26 | //添加角色 27 | // 当配置文件和 SecurityConfig 类中都配置了用户名和密码时,会使用代码中的用户名和密码。 28 | @Autowired 29 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 30 | auth.inMemoryAuthentication() 31 | .passwordEncoder(new BCryptPasswordEncoder()) 32 | .withUser("user") 33 | .password(new BCryptPasswordEncoder() 34 | .encode("123456")).roles("USER") 35 | .and() 36 | .withUser("admin").password(new BCryptPasswordEncoder() 37 | .encode("123456")).roles("ADMIN") 38 | ; 39 | } 40 | 41 | 42 | 43 | 44 | @Override 45 | protected void configure(HttpSecurity http) throws Exception { 46 | http.authorizeRequests() 47 | .antMatchers("/css/**", "/","/static/**","/**.css").permitAll()//配置不用登录可以访问的请求。 配置所有的css静态资源可以访问 48 | //.antMatchers("/", "/home") 49 | .antMatchers("/admin/**").hasRole("ADMIN") 50 | //.antMatchers("/content/**").access("hasRole('ADMIN') or hasRole('USER')") 51 | .antMatchers("/content/**").hasAnyRole("ADMIN","USER") // 参数中任意角色的用户可访问 == .access("hasRole('ADMIN') or hasRole('USER')") 52 | .anyRequest().authenticated() //表示其他的请求都必须要有权限认证。 53 | .and() 54 | .formLogin() //定制登录信息。 55 | //.loginPage("/login")//自定义登录地址,若注释掉则使用默认登录页面。 56 | //.successForwardUrl("/index") //登陆成功跳转url 57 | //.failureForwardUrl("/login?error")//失败跳转url 58 | .permitAll() 59 | .and() 60 | .logout() //默认是logout登出 61 | .permitAll() 62 | .and() 63 | .csrf() 64 | .ignoringAntMatchers("/logout"); 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/java/com/example/springsecuritydemo/controller/SecurityController.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecuritydemo.controller; 2 | 3 | 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestMethod; 8 | import org.springframework.web.bind.annotation.ResponseBody; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | @Controller 14 | public class SecurityController { 15 | /* @RequestMapping("/") 16 | public String index() { 17 | return "index"; 18 | } 19 | */ 20 | 21 | @RequestMapping("/content") 22 | public String content() { 23 | return "content"; 24 | } 25 | 26 | @RequestMapping(value = "/login", method = RequestMethod.GET) 27 | public String login() { 28 | return "login"; 29 | } 30 | 31 | //方法执行前检查权限 @PreAuthorize 可以将登录用户的角色 / 权限参数传到方法中。 32 | @PreAuthorize("hasAnyAuthority('ADMIN')") 33 | @RequestMapping("/admin") 34 | public String admin() { 35 | return "admin"; 36 | } 37 | 38 | @RequestMapping("/admin/admin2") 39 | @ResponseBody 40 | public String admin2() { 41 | 42 | return "admin2"; 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | #配置文件中将 Thymeleaf 的缓存先去掉。 3 | spring.thymeleaf.cache=false 4 | 5 | spring.security.user.name=user 6 | spring.security.user.password=123456 7 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/static/a.css: -------------------------------------------------------------------------------- 1 | asdasda -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/static/css/main.css: -------------------------------------------------------------------------------- 1 | .a{animation-delay: inherit} -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/templates/admin.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | admin 6 | 7 | 8 |

admin

9 |

管理员页面

10 |

点击 这里 返回首页

11 | 12 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/templates/content.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

content

5 |

我是登录后才可以看的页面

6 |
7 | 8 |
9 | 10 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | index 5 | 6 | 7 |

Hello!

8 |

今天天气很好,来一个纯洁的微笑吧!

9 |

点击 这里 进入受限页面

10 | 11 | -------------------------------------------------------------------------------- /springsecuritydemo/src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | login 7 | 8 | 9 |
10 | 用户名或密码错 11 |
12 |
13 | 您已注销成功 14 |
15 |
16 |
17 |
18 |
19 |
20 | 21 | -------------------------------------------------------------------------------- /springsecuritydemo/src/test/java/com/example/springsecuritydemo/SpringsecuritydemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springsecuritydemo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringsecuritydemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------