├── .gitignore ├── activemq ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── activemq │ │ ├── ActivemqApplication.java │ │ ├── config │ │ └── ActiveMQConfig.java │ │ ├── consumer │ │ └── Consumer.java │ │ └── producer │ │ └── Producer.java │ └── resources │ └── application.yml ├── aop ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── aop │ │ ├── AopApplication.java │ │ ├── annotation │ │ └── Print.java │ │ ├── aspect │ │ └── LogAspect.java │ │ └── ctrl │ │ └── TestController.java │ └── resources │ └── application.yml ├── async ├── pom.xml └── src │ ├── main │ └── java │ │ └── demo │ │ └── springboot │ │ └── async │ │ ├── AsyncApplication.java │ │ ├── config │ │ └── BeanLoad.java │ │ └── service │ │ └── AsyncService.java │ └── test │ └── java │ └── demo │ └── springboot │ └── async │ └── AsyncApplicationTests.java ├── bean ├── pom.xml └── src │ ├── main │ └── java │ │ └── demo │ │ └── springboot │ │ └── bean │ │ ├── BeanApplication.java │ │ ├── bean │ │ ├── Test.java │ │ └── Test1.java │ │ └── config │ │ └── BeanLoad.java │ └── test │ └── java │ └── demo │ └── springboot │ └── bean │ └── BeanApplicationTests.java ├── cache ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── cache │ │ │ ├── CacheApplication.java │ │ │ └── service │ │ │ └── CacheService.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── cache │ └── CacheApplicationTests.java ├── dubbo ├── dubbo-consumer │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ ├── ConsumerApplication.java │ │ │ └── ctrl │ │ │ └── TestController.java │ │ └── resources │ │ └── application.yml ├── dubbo-producer │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ ├── ProducerApplication.java │ │ │ └── service │ │ │ └── impl │ │ │ └── TestServiceImpl.java │ │ └── resources │ │ └── application.yml ├── dubbo-service │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── demo │ │ └── springboot │ │ ├── domain │ │ └── User.java │ │ └── service │ │ └── TestService.java └── pom.xml ├── jedis-spring-boot-starter ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ ├── JedisAutoConfiguration.java │ │ └── JedisProperties.java │ └── resources │ └── META-INF │ └── spring.factories ├── limiter ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── limiter │ │ ├── LimiterApplication.java │ │ ├── annotation │ │ └── Limiter.java │ │ ├── aspect │ │ └── LimitingAspect.java │ │ ├── bean │ │ └── BeanLoad.java │ │ ├── ctrl │ │ └── TestController.java │ │ ├── exception │ │ └── FrequentRequestsException.java │ │ └── util │ │ └── WebUtil.java │ └── resources │ └── application.yml ├── mail ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── mail │ │ │ └── MailApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── mail │ └── MailApplicationTests.java ├── multiple-datasource ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── multipledatasource │ │ │ ├── MultipleDatasourceApplication.java │ │ │ ├── config │ │ │ ├── DataSource1Config.java │ │ │ └── DataSource2Config.java │ │ │ ├── dao1 │ │ │ └── User1DAO.java │ │ │ ├── dao2 │ │ │ └── User2DAO.java │ │ │ └── domain │ │ │ └── User.java │ └── resources │ │ ├── application.yml │ │ └── mapper │ │ ├── one │ │ └── User1Mapper.xml │ │ └── two │ │ └── User2Mapper.xml │ └── test │ └── java │ └── demo │ └── springboot │ └── multipledatasource │ └── MultipleDatasourceApplicationTests.java ├── mybatis-mapper-pagehelper ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── mybatismapperpagehelper │ │ │ ├── MybatisMapperPagehelperApplication.java │ │ │ ├── basedao │ │ │ └── BaseMapper.java │ │ │ ├── dao │ │ │ └── SysUserDAO.java │ │ │ └── domain │ │ │ └── SysUser.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── mybatismapperpagehelper │ └── MybatisMapperPagehelperApplicationTests.java ├── mybatis ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── mybatis │ │ │ ├── MybatisApplication.java │ │ │ ├── dao │ │ │ └── SysUserMapper.java │ │ │ ├── domain │ │ │ └── SysUser.java │ │ │ └── service │ │ │ └── UserService.java │ └── resources │ │ ├── application.yml │ │ ├── mapper │ │ └── SysUserMapper.xml │ │ └── mybatis │ │ └── SqlMapConfig.xml │ └── test │ └── java │ └── demo │ └── springboot │ └── mybatis │ └── MybatisApplicationTests.java ├── mysql ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── mysql │ │ │ └── MysqlApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── mysql │ └── MysqlApplicationTests.java ├── pom.xml ├── properties ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── properties │ │ │ ├── PropertiesApplication.java │ │ │ └── bean │ │ │ ├── PropertiesBean.java │ │ │ ├── PropertiesBean1.java │ │ │ └── PropertiesBean2.java │ └── resources │ │ ├── application-db.yml │ │ ├── application-dev.yml │ │ ├── application.yml │ │ └── test.properties │ └── test │ └── java │ └── demo │ └── springboot │ └── properties │ └── PropertiesApplicationTests.java ├── redis-session ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── redissession │ │ ├── RedisSessionApplication.java │ │ └── ctrl │ │ └── TestController.java │ └── resources │ └── application.yml ├── redis ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── redis │ │ │ ├── RedisApplication.java │ │ │ └── bean │ │ │ └── BeanLoad.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── redis │ └── RedisApplicationTests.java ├── redisson ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── redisson │ │ │ ├── RedissonApplication.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── dao │ │ │ └── SysUserMapper.java │ │ │ ├── domain │ │ │ └── SysUser.java │ │ │ └── service │ │ │ └── UserService.java │ └── resources │ │ ├── application.yml │ │ └── redisson.yml │ └── test │ └── java │ └── demo │ └── springboot │ └── redisson │ └── RedissonApplicationTests.java ├── resttemplate ├── pom.xml └── src │ ├── main │ └── java │ │ └── demo │ │ └── springboot │ │ └── resttemplate │ │ ├── ResttemplateApplication.java │ │ ├── config │ │ └── BeanLoad.java │ │ ├── ctrl │ │ └── TestController.java │ │ └── domain │ │ └── User.java │ └── test │ └── java │ └── demo │ └── springboot │ └── resttemplate │ └── ResttemplateApplicationTests.java ├── scheduler ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── scheduler │ │ ├── SchedulerApplication.java │ │ └── scheduling │ │ └── TestScheduling.java │ └── resources │ └── application.yml ├── sharding-jdbc ├── pom.xml └── src │ ├── main │ ├── java │ │ └── demo │ │ │ └── springboot │ │ │ └── shardingjdbc │ │ │ ├── ShardingJdbcApplication.java │ │ │ ├── dao │ │ │ ├── DictDAO.java │ │ │ └── OrderDAO.java │ │ │ ├── domain │ │ │ ├── Dict.java │ │ │ ├── Order.java │ │ │ └── OrderItem.java │ │ │ └── service │ │ │ └── TestService.java │ └── resources │ │ ├── application-sharding.yml │ │ ├── application-split.yml │ │ ├── application.yml │ │ └── sharding-jdbc.sql │ └── test │ └── java │ └── demo │ └── springboot │ └── shardingjdbc │ └── ShardingJdbcApplicationTests.java ├── validation ├── pom.xml └── src │ └── main │ └── java │ └── demo │ └── springboot │ └── validation │ ├── ValidationApplication.java │ ├── annotation │ └── Phone.java │ ├── ctrl │ ├── PhoneController.java │ ├── RoleController.java │ ├── UserBetterController.java │ └── UserController.java │ ├── domian │ ├── Role.java │ └── User.java │ ├── group │ ├── Add.java │ └── Update.java │ ├── handler │ └── GlobalExceptionHandler.java │ ├── util │ └── JsonResult.java │ └── validator │ └── PhoneValidator.java ├── web-start ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── webstart │ │ ├── WebStartApplication.java │ │ └── controller │ │ └── TestController.java │ └── resources │ └── application.yml ├── websocket ├── pom.xml └── src │ └── main │ ├── java │ └── demo │ │ └── springboot │ │ └── websocket │ │ ├── WebsocketApplication.java │ │ ├── config │ │ └── WebSocketConfig.java │ │ ├── handler │ │ ├── MyHandshakeHandler.java │ │ └── MyWebSocketHandler.java │ │ ├── message │ │ └── SendMsg.java │ │ └── principal │ │ └── MyPrincipal.java │ └── resources │ ├── application.yml │ └── static │ └── index.html └── websocket2 ├── pom.xml └── src └── main ├── java └── demo │ └── springboot │ └── websocket │ ├── WebSocketApplication.java │ ├── config │ ├── RedisMessageListenerConfig.java │ └── WebSocketConfig.java │ ├── controller │ └── ImController.java │ ├── handler │ ├── MyHandshakeHandler.java │ └── MyWebSocketHandler.java │ ├── message │ └── SendMsg.java │ ├── principal │ └── MyPrincipal.java │ └── redis │ └── RedisReceiver.java └── resources ├── application.yml └── static └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | */target/ 3 | *.mvn 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /activemq/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | activemq 11 | activemq 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-activemq 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | 30 | ${project.name} 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-maven-plugin 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /activemq/src/main/java/demo/springboot/activemq/ActivemqApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.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 | -------------------------------------------------------------------------------- /activemq/src/main/java/demo/springboot/activemq/config/ActiveMQConfig.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.activemq.config; 2 | 3 | import org.apache.activemq.command.ActiveMQQueue; 4 | import org.apache.activemq.command.ActiveMQTopic; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.jms.annotation.EnableJms; 8 | import org.springframework.jms.config.DefaultJmsListenerContainerFactory; 9 | import org.springframework.jms.config.JmsListenerContainerFactory; 10 | 11 | import javax.jms.ConnectionFactory; 12 | import javax.jms.Queue; 13 | import javax.jms.Topic; 14 | 15 | /** 16 | * @author dean.lee 17 | */ 18 | @Configuration 19 | @EnableJms 20 | public class ActiveMQConfig { 21 | @Bean 22 | public Queue queue() { 23 | return new ActiveMQQueue("springboot.queue"); 24 | } 25 | 26 | //springboot默认只配置queue类型消息,如果要使用topic类型的消息,则需要配置该bean 27 | @Bean 28 | public JmsListenerContainerFactory jmsTopicListenerContainerFactory(ConnectionFactory connectionFactory){ 29 | DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); 30 | factory.setConnectionFactory(connectionFactory); 31 | //这里必须设置为true,false则表示是queue类型 32 | factory.setPubSubDomain(true); 33 | return factory; 34 | } 35 | 36 | @Bean 37 | public Topic topic() { 38 | return new ActiveMQTopic("springboot.topic"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /activemq/src/main/java/demo/springboot/activemq/consumer/Consumer.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.activemq.consumer; 2 | 3 | import org.springframework.jms.annotation.JmsListener; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @author dean.lee 8 | */ 9 | @Component 10 | public class Consumer { 11 | 12 | //接收queue类型消息 13 | //destination对应配置类中ActiveMQQueue("springboot.queue")设置的名字 14 | @JmsListener(destination="springboot.queue") 15 | public void ListenQueue(String msg){ 16 | System.out.println("接收到queue消息:" + msg); 17 | } 18 | 19 | //接收topic类型消息 20 | //destination对应配置类中ActiveMQTopic("springboot.topic")设置的名字 21 | //containerFactory对应配置类中注册JmsListenerContainerFactory的bean名称 22 | @JmsListener(destination="springboot.topic", containerFactory = "jmsTopicListenerContainerFactory") 23 | public void ListenTopic(String msg){ 24 | System.out.println("接收到topic消息:" + msg); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /activemq/src/main/java/demo/springboot/activemq/producer/Producer.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.activemq.producer; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jms.core.JmsMessagingTemplate; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import javax.jms.Queue; 9 | import javax.jms.Topic; 10 | 11 | /** 12 | * @author dean.lee 13 | */ 14 | @RestController 15 | public class Producer { 16 | @Autowired 17 | private JmsMessagingTemplate jmsTemplate; 18 | 19 | @Autowired 20 | private Queue queue; 21 | 22 | @Autowired 23 | private Topic topic; 24 | 25 | //发送queue类型消息 26 | @GetMapping("/queue") 27 | public void sendQueueMsg(String msg){ 28 | jmsTemplate.convertAndSend(queue, msg); 29 | } 30 | 31 | //发送topic类型消息 32 | @GetMapping("/topic") 33 | public void sendTopicMsg(String msg){ 34 | jmsTemplate.convertAndSend(topic, msg); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /activemq/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | activemq: 3 | #ActiveMQ\u901A\u8BAF\u5730\u5740 4 | broker-url: tcp://localhost:61616 5 | #\u7528\u6237\u540D 6 | user: admin 7 | #\u5BC6\u7801 8 | password: admin 9 | #\u662F\u5426\u542F\u7528\u5185\u5B58\u6A21\u5F0F\uFF08\u5C31\u662F\u4E0D\u5B89\u88C5MQ\uFF0C\u9879\u76EE\u542F\u52A8\u65F6\u540C\u65F6\u542F\u52A8\u4E00\u4E2AMQ\u5B9E\u4F8B\uFF09 10 | in-memory: false 11 | packages: 12 | #\u4FE1\u4EFB\u6240\u6709\u7684\u5305 13 | trust-all: true 14 | pool: 15 | #\u662F\u5426\u66FF\u6362\u9ED8\u8BA4\u7684\u8FDE\u63A5\u6C60\uFF0C\u4F7F\u7528ActiveMQ\u7684\u8FDE\u63A5\u6C60\u9700\u5F15\u5165\u7684\u4F9D\u8D56 16 | enabled: false 17 | -------------------------------------------------------------------------------- /aop/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | aop 11 | aop 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-aop 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | org.projectlombok 30 | lombok 31 | true 32 | 33 | 34 | 35 | com.alibaba 36 | fastjson 37 | 1.2.51 38 | 39 | 40 | 41 | 42 | ${project.name} 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-maven-plugin 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /aop/src/main/java/demo/springboot/aop/AopApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.aop; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class AopApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(AopApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /aop/src/main/java/demo/springboot/aop/annotation/Print.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.aop.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author dean.lee 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface Print { 14 | String value() default ""; 15 | } 16 | -------------------------------------------------------------------------------- /aop/src/main/java/demo/springboot/aop/aspect/LogAspect.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.aop.aspect; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import demo.springboot.aop.annotation.Print; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.aspectj.lang.JoinPoint; 7 | import org.aspectj.lang.ProceedingJoinPoint; 8 | import org.aspectj.lang.Signature; 9 | import org.aspectj.lang.annotation.Around; 10 | import org.aspectj.lang.annotation.Aspect; 11 | import org.aspectj.lang.annotation.Before; 12 | import org.aspectj.lang.annotation.Pointcut; 13 | import org.springframework.stereotype.Component; 14 | 15 | /** 16 | * @author dean.lee 17 | */ 18 | @Aspect 19 | @Component 20 | @Slf4j 21 | public class LogAspect { 22 | 23 | @Pointcut("execution(* demo.springboot.aop.ctrl.*.*(..))") 24 | public void pointcut() {} 25 | 26 | @Before("pointcut()") 27 | public void printParam(JoinPoint joinPoint){ 28 | //获取请求的方法 29 | Signature sig = joinPoint.getSignature(); 30 | String method = joinPoint.getTarget().getClass().getName() + "." + sig.getName(); 31 | 32 | //获取请求的参数 33 | Object[] args = joinPoint.getArgs(); 34 | //fastjson转换 35 | String params = JSONObject.toJSONString(args); 36 | 37 | //打印请求参数 38 | log.info(method + ":" + params); 39 | } 40 | 41 | @Pointcut("@annotation(print)") 42 | public void annotationPointcut(Print print){} 43 | 44 | @Around("annotationPointcut(print)") 45 | public Object around(ProceedingJoinPoint pjp, Print print) throws Throwable { 46 | //获取请求方法 47 | Signature sig = pjp.getSignature(); 48 | String method = pjp.getTarget().getClass().getName() + "." + sig.getName(); 49 | 50 | //获取请求的参数 51 | Object[] args = pjp.getArgs(); 52 | //fastjson转换 53 | String params = JSONObject.toJSONString(args); 54 | 55 | //打印请求参数 56 | log.info("参数:" + method + ":" + params); 57 | 58 | //执行方法 59 | Object result = pjp.proceed(); 60 | 61 | //打印返回结果 62 | log.info("返回结果:" + method + ":" + result); 63 | return result; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /aop/src/main/java/demo/springboot/aop/ctrl/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.aop.ctrl; 2 | 3 | import demo.springboot.aop.annotation.Print; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @RestController 11 | public class TestController { 12 | 13 | @GetMapping("getInfo") 14 | public String getInfo(String name, Integer age){ 15 | return name + ":" + age; 16 | } 17 | 18 | @Print(value = "printParamAndResult") 19 | @GetMapping("getString") 20 | public String getString(String src){ 21 | return src; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /aop/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | root: error 4 | demo.springboot: debug 5 | -------------------------------------------------------------------------------- /async/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | async 11 | async 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | 26 | ${project.name} 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-maven-plugin 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /async/src/main/java/demo/springboot/async/AsyncApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.async; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.scheduling.annotation.EnableAsync; 6 | 7 | @SpringBootApplication 8 | @EnableAsync 9 | public class AsyncApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(AsyncApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /async/src/main/java/demo/springboot/async/config/BeanLoad.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.async.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @Configuration 11 | public class BeanLoad { 12 | 13 | @Bean 14 | public ThreadPoolTaskExecutor threadPoolTaskExecutor(){ 15 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 16 | executor.setThreadNamePrefix("springboot-"); 17 | executor.setCorePoolSize(3); 18 | executor.setMaxPoolSize(10); 19 | 20 | executor.initialize(); 21 | return executor; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /async/src/main/java/demo/springboot/async/service/AsyncService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.async.service; 2 | 3 | import org.springframework.scheduling.annotation.Async; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @author dean.lee 8 | */ 9 | @Component 10 | public class AsyncService { 11 | 12 | //@Async表示方法是一个异步方法 13 | @Async 14 | public void test1(){ 15 | //打印线程name 16 | System.out.println("test1 start:" + Thread.currentThread().getName()); 17 | //模拟程序执行 18 | try { 19 | Thread.sleep(5000); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | System.out.println("test1 end"); 24 | } 25 | 26 | @Async 27 | public void test2(){ 28 | System.out.println("test2 start:" + Thread.currentThread().getName()); 29 | try { 30 | Thread.sleep(5000); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | System.out.println("test2 end"); 35 | } 36 | 37 | @Async 38 | public void test3(){ 39 | System.out.println("test3 start:" + Thread.currentThread().getName()); 40 | try { 41 | Thread.sleep(5000); 42 | } catch (InterruptedException e) { 43 | e.printStackTrace(); 44 | } 45 | System.out.println("test3 end"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /async/src/test/java/demo/springboot/async/AsyncApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.async; 2 | 3 | import demo.springboot.async.service.AsyncService; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class AsyncApplicationTests { 13 | 14 | @Autowired 15 | private AsyncService asyncService; 16 | 17 | @Test 18 | public void testAsync() { 19 | asyncService.test1(); 20 | asyncService.test2(); 21 | asyncService.test3(); 22 | //避免主线程结束出现错误 23 | try { 24 | Thread.sleep(5000); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /bean/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | bean 11 | bean 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | 26 | ${project.name} 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-maven-plugin 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /bean/src/main/java/demo/springboot/bean/BeanApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.bean; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BeanApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BeanApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /bean/src/main/java/demo/springboot/bean/bean/Test.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.bean.bean; 2 | 3 | /** 4 | * @author dean.lee 5 | */ 6 | public class Test { 7 | private String name; 8 | 9 | public String getName() { 10 | return name; 11 | } 12 | 13 | public void setName(String name) { 14 | this.name = name; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return "Test{" + 20 | "name='" + name + '\'' + 21 | '}'; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bean/src/main/java/demo/springboot/bean/bean/Test1.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.bean.bean; 2 | 3 | /** 4 | * @author dean.lee 5 | */ 6 | public class Test1 { 7 | private Test test; 8 | 9 | public Test getTest() { 10 | return test; 11 | } 12 | 13 | public void setTest(Test test) { 14 | this.test = test; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return "Test1{" + 20 | "test=" + test + 21 | '}'; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bean/src/main/java/demo/springboot/bean/config/BeanLoad.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.bean.config; 2 | 3 | import demo.springboot.bean.bean.Test; 4 | import demo.springboot.bean.bean.Test1; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | //@Configuration注解声明当前类是一个配置类,相当于spring中xml的 9 | @Configuration 10 | public class BeanLoad { 11 | 12 | //@Bean注解相当于spring中xml的 13 | //当前方法返回的值会被注册成bean 14 | //bean默认的名称是方法名 15 | //如果需要设置自定义名称修改@Bean中name属性 16 | @Bean(name = "t") 17 | public Test test(){ 18 | return new Test(); 19 | } 20 | 21 | //需要依赖其他bean,在方法参数中加入即可 22 | @Bean 23 | public Test1 test1(Test test){ 24 | Test1 test1 = new Test1(); 25 | test1.setTest(test); 26 | return test1; 27 | } 28 | 29 | //或者在当前类使用@Autowired注解装配bean,方法参数就可以为空 30 | // @Autowired 31 | // private Test test; 32 | // @Bean 33 | // public Test1 test1(){ 34 | // Test1 test1 = new Test1(); 35 | // test1.setTest(test); 36 | // return test1; 37 | // } 38 | } 39 | -------------------------------------------------------------------------------- /bean/src/test/java/demo/springboot/bean/BeanApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.bean; 2 | 3 | import demo.springboot.bean.bean.Test1; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class BeanApplicationTests { 13 | 14 | @Autowired 15 | private demo.springboot.bean.bean.Test test; 16 | @Autowired 17 | private Test1 test1; 18 | 19 | @Test 20 | public void testBean() { 21 | test.setName("test"); 22 | System.out.println(test); 23 | System.out.println(test1); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /cache/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | cache 11 | cache 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-cache 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-data-redis 33 | 34 | 35 | 36 | 37 | ${project.name} 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-maven-plugin 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /cache/src/main/java/demo/springboot/cache/CacheApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.cache; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | 7 | @SpringBootApplication 8 | @EnableCaching 9 | public class CacheApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(CacheApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /cache/src/main/java/demo/springboot/cache/service/CacheService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.cache.service; 2 | 3 | import org.springframework.cache.annotation.CacheEvict; 4 | import org.springframework.cache.annotation.CachePut; 5 | import org.springframework.cache.annotation.Cacheable; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author dean.lee 10 | */ 11 | @Service 12 | public class CacheService { 13 | 14 | /** 15 | * 如果缓存中有则直接走缓存,如果没有则执行方法,将方法的返回值作为缓存 16 | * @param id 17 | * @return 18 | */ 19 | @Cacheable(value = "cache-test", key = "'getName:' + #p0") 20 | public String getName(long id){ 21 | System.out.println("等待3秒。。。。"); 22 | try { 23 | Thread.sleep(3000L); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | 28 | return id + ":name"; 29 | } 30 | 31 | /** 32 | * 将方法的返回值更新到缓存 33 | * @param id 34 | * @return 35 | */ 36 | @CachePut(value = "cache-test", key = "'getName:' + #p0") 37 | public String updateName(long id){ 38 | System.out.println("更新名称"); 39 | return id + ":nickname"; 40 | } 41 | 42 | /** 43 | * 删除缓存 44 | * @param id 45 | */ 46 | @CacheEvict(value = "cache-test", key = "'getName:' + #p0") 47 | public void deleteName(long id){ 48 | System.out.println("删除名称"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cache/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | redis: 3 | #\u5730\u5740 4 | host: localhost 5 | #\u7AEF\u53E3 6 | port: 6379 7 | #\u7D22\u5F15\u5E93 8 | database: 1 9 | #\u5BC6\u7801 10 | password: 11 | #\u8D85\u65F6\u65F6\u95F4 12 | timeout: 5000ms 13 | cache: 14 | #\u8BBE\u7F6E\u7F13\u5B58\u7C7B\u578B 15 | type: redis 16 | redis: 17 | #\u7F13\u5B58\u5B58\u6D3B\u65F6\u95F4\uFF0C\u4E0D\u8BBE\u7F6E\u5219\u6CA1\u6709\u8FC7\u671F\u65F6\u95F4 18 | time-to-live: 1800000ms 19 | -------------------------------------------------------------------------------- /cache/src/test/java/demo/springboot/cache/CacheApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.cache; 2 | 3 | import demo.springboot.cache.service.CacheService; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class CacheApplicationTests { 13 | 14 | @Autowired 15 | private CacheService cacheService; 16 | 17 | @Test 18 | public void testCache() { 19 | System.out.println(cacheService.getName(1L)); 20 | System.out.println(cacheService.getName(1L)); 21 | cacheService.updateName(1L); 22 | System.out.println(cacheService.getName(1L)); 23 | cacheService.deleteName(1L); 24 | System.out.println(cacheService.getName(1L)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /dubbo/dubbo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | dubbo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | dubbo-consumer 13 | 14 | dubbo-consumer 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | demo.springboot 23 | dubbo-service 24 | 1.0-SNAPSHOT 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | com.alibaba.boot 34 | dubbo-spring-boot-starter 35 | 0.2.0 36 | 37 | 38 | 39 | 40 | 41 | ${project.name} 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-maven-plugin 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /dubbo/dubbo-consumer/src/main/java/demo/springboot/ConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author dean.lee 8 | */ 9 | @SpringBootApplication 10 | public class ConsumerApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(ConsumerApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /dubbo/dubbo-consumer/src/main/java/demo/springboot/ctrl/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.ctrl; 2 | 3 | import com.alibaba.dubbo.config.annotation.Reference; 4 | import demo.springboot.domain.User; 5 | import demo.springboot.service.TestService; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @RestController 13 | public class TestController { 14 | 15 | @Reference(version = "${application.version}") 16 | private TestService testService; 17 | 18 | @GetMapping("/getString") 19 | public String getString(String src){ 20 | return testService.getString(src); 21 | } 22 | 23 | @GetMapping("/getUser") 24 | public User getUser(String name, Integer age){ 25 | return testService.getUser(name, age); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dubbo/dubbo-consumer/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | servlet: 4 | context-path: / 5 | 6 | application: 7 | #版本号 8 | version: 1.0.0 9 | 10 | dubbo: 11 | application: 12 | #应用名称,每个dubbo应用的名称都是唯一的 13 | name: dubbo-consumer 14 | registry: 15 | #注册中心 16 | address: zookeeper://172.16.77.131:2181 17 | -------------------------------------------------------------------------------- /dubbo/dubbo-producer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | dubbo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | dubbo-producer 13 | 14 | dubbo-producer 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | demo.springboot 23 | dubbo-service 24 | 1.0-SNAPSHOT 25 | 26 | 27 | 28 | com.alibaba.boot 29 | dubbo-spring-boot-starter 30 | 0.2.0 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter 35 | 36 | 37 | 38 | 39 | ${project.name} 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-maven-plugin 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /dubbo/dubbo-producer/src/main/java/demo/springboot/ProducerApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot; 2 | 3 | import org.springframework.boot.WebApplicationType; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @SpringBootApplication 11 | public class ProducerApplication { 12 | 13 | public static void main(String[] args) { 14 | new SpringApplicationBuilder(ProducerApplication.class) 15 | .web(WebApplicationType.NONE) //非web应用 16 | .run(args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dubbo/dubbo-producer/src/main/java/demo/springboot/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.service.impl; 2 | 3 | import com.alibaba.dubbo.config.annotation.Service; 4 | import demo.springboot.domain.User; 5 | import demo.springboot.service.TestService; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @Service(version = "${application.version}") 11 | public class TestServiceImpl implements TestService { 12 | @Override 13 | public String getString(String src) { 14 | return src; 15 | } 16 | 17 | @Override 18 | public User getUser(String name, int age) { 19 | User user = new User(); 20 | user.setName(name); 21 | user.setAge(age); 22 | return user; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dubbo/dubbo-producer/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | application: 2 | #版本号 3 | version: 1.0.0 4 | 5 | dubbo: 6 | application: 7 | #应用名称,每个dubbo应用的名称都是唯一的 8 | name: dubbo-producer 9 | registry: 10 | #注册中心 11 | address: zookeeper://172.16.77.131:2181 12 | protocol: 13 | #协议名称 14 | name: dubbo 15 | #服务暴露端口 16 | port: 20880 17 | scan: 18 | #扫描服务注册bean 19 | basePackages: demo.springboot.service.impl -------------------------------------------------------------------------------- /dubbo/dubbo-service/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | dubbo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | dubbo-service 13 | 14 | dubbo-service 15 | 16 | 17 | UTF-8 18 | 1.8 19 | 1.8 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /dubbo/dubbo-service/src/main/java/demo/springboot/domain/User.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author dean.lee 7 | */ 8 | public class User implements Serializable { 9 | 10 | private static final long serialVersionUID = -1563308959112481804L; 11 | 12 | private String name; 13 | 14 | private Integer age; 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public Integer getAge() { 25 | return age; 26 | } 27 | 28 | public void setAge(Integer age) { 29 | this.age = age; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "User{" + 35 | "name='" + name + '\'' + 36 | ", age='" + age + '\'' + 37 | '}'; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /dubbo/dubbo-service/src/main/java/demo/springboot/service/TestService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.service; 2 | 3 | import demo.springboot.domain.User; 4 | 5 | /** 6 | * @author dean.lee 7 | */ 8 | public interface TestService { 9 | 10 | 11 | String getString(String src); 12 | 13 | User getUser(String name, int age); 14 | } 15 | -------------------------------------------------------------------------------- /dubbo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | dubbo 13 | pom 14 | 15 | 16 | dubbo-service 17 | dubbo-producer 18 | dubbo-consumer 19 | 20 | 21 | 22 | UTF-8 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /jedis-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | jedis-spring-boot-starter 13 | 14 | jedis-spring-boot-starter 15 | 16 | 17 | UTF-8 18 | 1.8 19 | 1.8 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-autoconfigure 26 | 2.0.6.RELEASE 27 | 28 | 29 | 30 | redis.clients 31 | jedis 32 | 3.0.0 33 | provided 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /jedis-spring-boot-starter/src/main/java/demo/springboot/JedisAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package demo.springboot; 2 | 3 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 4 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 5 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import redis.clients.jedis.Jedis; 9 | 10 | /** 11 | * @author dean.lee 12 | */ 13 | @Configuration 14 | //当类路径下有Jedis依赖时进行配置 15 | @ConditionalOnClass(Jedis.class) 16 | //引入JedisProperties对象 17 | @EnableConfigurationProperties(JedisProperties.class) 18 | public class JedisAutoConfiguration { 19 | 20 | @Bean 21 | //当spring容器中没有该Bean时注册 22 | @ConditionalOnMissingBean(Jedis.class) 23 | public Jedis jedis(JedisProperties jedisProperties){ 24 | //设置地址端口 25 | Jedis jedis = new Jedis(jedisProperties.getHost(), jedisProperties.getPort()); 26 | //验证密码 27 | jedis.auth(jedisProperties.getPassword()); 28 | //设置索引库 29 | jedis.select(jedisProperties.getDatabase()); 30 | jedis.connect(); 31 | return jedis; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /jedis-spring-boot-starter/src/main/java/demo/springboot/JedisProperties.java: -------------------------------------------------------------------------------- 1 | package demo.springboot; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * @author dean.lee 7 | */ 8 | //获取配置文件中的属性 9 | @ConfigurationProperties(prefix = "jedis") 10 | public class JedisProperties { 11 | 12 | private int database = 0; 13 | private String host = "localhost"; 14 | private String password = ""; 15 | private int port = 6379; 16 | 17 | public int getDatabase() { 18 | return database; 19 | } 20 | 21 | public void setDatabase(int database) { 22 | this.database = database; 23 | } 24 | 25 | public String getHost() { 26 | return host; 27 | } 28 | 29 | public void setHost(String host) { 30 | this.host = host; 31 | } 32 | 33 | public String getPassword() { 34 | return password; 35 | } 36 | 37 | public void setPassword(String password) { 38 | this.password = password; 39 | } 40 | 41 | public int getPort() { 42 | return port; 43 | } 44 | 45 | public void setPort(int port) { 46 | this.port = port; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /jedis-spring-boot-starter/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=demo.springboot.JedisAutoConfiguration -------------------------------------------------------------------------------- /limiter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | limiter 11 | limiter 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-aop 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-redis 32 | 33 | 34 | 35 | 36 | ${project.name} 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-maven-plugin 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/LimiterApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class LimiterApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(LimiterApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/annotation/Limiter.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | public @interface Limiter { 16 | 17 | /** 18 | * 从第一次访问接口的时间到cycle周期时间内,无法超过frequency次 19 | * 20 | * @return 21 | */ 22 | int frequency() default 20; 23 | 24 | /** 25 | * 周期时间,单位ms: 26 | * 默认周期时间为一分钟 27 | * 28 | * @return 29 | */ 30 | long cycle() default 60 * 1000; 31 | 32 | /** 33 | * 返回的错误信息 34 | * 35 | * @return 36 | */ 37 | String message() default "请求过于频繁"; 38 | 39 | /** 40 | * 到期时间,单位s: 41 | * 如果在cycle周期时间内超过frequency次,则默认1分钟内无法继续访问 42 | * @return 43 | */ 44 | long expireTime() default 1 * 60; 45 | } 46 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/aspect/LimitingAspect.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.aspect; 2 | 3 | import demo.springboot.limiter.annotation.Limiter; 4 | import demo.springboot.limiter.exception.FrequentRequestsException; 5 | import demo.springboot.limiter.util.WebUtil; 6 | import org.aspectj.lang.ProceedingJoinPoint; 7 | import org.aspectj.lang.annotation.Around; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.annotation.Pointcut; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.data.redis.core.RedisTemplate; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.util.concurrent.TimeUnit; 15 | 16 | /** 17 | * ip防刷api功能实现。 18 | * 该功能使用redis作为存储,方便在集群中使用。 19 | * 如果是单项目部署,可以将redis换成本地缓存。 20 | * 21 | * @author dean.lee 22 | *

23 | */ 24 | @Aspect 25 | @Component 26 | public class LimitingAspect { 27 | private static final String LIMITING_KEY = "limiting:%s:%s"; 28 | private static final String LIMITING_BEGINTIME = "beginTime"; 29 | private static final String LIMITING_EXFREQUENCY = "exFrequency"; 30 | 31 | @Autowired 32 | private RedisTemplate redisTemplate; 33 | 34 | @Pointcut("@annotation(limiter)") 35 | public void pointcut(Limiter limiter) { 36 | } 37 | 38 | @Around("pointcut(limiter)") 39 | public Object around(ProceedingJoinPoint pjp, Limiter limiter) throws Throwable { 40 | //获取请求的ip和方法 41 | String ipAddress = WebUtil.getIpAddress(); 42 | String methodName = pjp.getSignature().toLongString(); 43 | 44 | //获取方法的访问周期和频率 45 | long cycle = limiter.cycle(); 46 | int frequency = limiter.frequency(); 47 | long currentTime = System.currentTimeMillis(); 48 | 49 | //获取redis中周期内第一次访问方法的时间和执行的次数 50 | Long beginTimeLong = (Long) redisTemplate.opsForHash().get(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_BEGINTIME); 51 | Integer exFrequencyLong = (Integer) redisTemplate.opsForHash().get(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY); 52 | 53 | long beginTime = beginTimeLong == null ? 0L : beginTimeLong; 54 | int exFrequency = exFrequencyLong == null ? 0 : exFrequencyLong; 55 | 56 | //如果当前时间减去周期内第一次访问方法的时间大于周期时间,则正常访问 57 | //并将周期内第一次访问方法的时间和执行次数初始化 58 | if (currentTime - beginTime > cycle) { 59 | redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_BEGINTIME, currentTime); 60 | redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY, 1); 61 | redisTemplate.expire(String.format(LIMITING_KEY, ipAddress, methodName), limiter.expireTime(), TimeUnit.SECONDS); 62 | return pjp.proceed(); 63 | } else { 64 | //如果在周期时间内,执行次数小于频率,则正常访问 65 | //并将执行次数加一 66 | if (exFrequency < frequency) { 67 | redisTemplate.opsForHash().put(String.format(LIMITING_KEY, ipAddress, methodName), LIMITING_EXFREQUENCY, exFrequency + 1); 68 | redisTemplate.expire(String.format(LIMITING_KEY, ipAddress, methodName), limiter.expireTime(), TimeUnit.SECONDS); 69 | return pjp.proceed(); 70 | } else { 71 | //否则抛出访问频繁异常 72 | throw new FrequentRequestsException(limiter.message()); 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/bean/BeanLoad.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.bean; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.serializer.StringRedisSerializer; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @Configuration 13 | public class BeanLoad { 14 | /** 15 | * 设置redisTemplate key序列化 16 | * @param factory 17 | * @return 18 | */ 19 | @Bean 20 | public RedisTemplate redisTemplate(RedisConnectionFactory factory){ 21 | RedisTemplate redisTemplate = new RedisTemplate<>(); 22 | redisTemplate.setConnectionFactory(factory); 23 | 24 | StringRedisSerializer keySerializer = new StringRedisSerializer(); 25 | redisTemplate.setKeySerializer(keySerializer); 26 | redisTemplate.setHashKeySerializer(keySerializer); 27 | 28 | redisTemplate.afterPropertiesSet(); 29 | return redisTemplate; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/ctrl/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.ctrl; 2 | 3 | import demo.springboot.limiter.annotation.Limiter; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @RestController 11 | public class TestController { 12 | 13 | //限制在周期内只能访问3次 14 | @Limiter(frequency = 3) 15 | @GetMapping("getString") 16 | public String getString(){ 17 | return "hello"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/exception/FrequentRequestsException.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.exception; 2 | 3 | /** 4 | * @author dean.lee 5 | */ 6 | public class FrequentRequestsException extends RuntimeException { 7 | 8 | public FrequentRequestsException() { 9 | super(); 10 | } 11 | 12 | public FrequentRequestsException(String message) { 13 | super(message); 14 | } 15 | 16 | public FrequentRequestsException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public FrequentRequestsException(Throwable cause) { 21 | super(cause); 22 | } 23 | 24 | protected FrequentRequestsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 25 | super(message, cause, enableSuppression, writableStackTrace); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /limiter/src/main/java/demo/springboot/limiter/util/WebUtil.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.limiter.util; 2 | 3 | import org.springframework.web.context.request.RequestContextHolder; 4 | import org.springframework.web.context.request.ServletRequestAttributes; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | public class WebUtil { 13 | 14 | private static final String UNKNOWN = "unknown"; 15 | 16 | //获取request 17 | public static HttpServletRequest getRequest() { 18 | return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 19 | } 20 | 21 | //获取response 22 | public static HttpServletResponse getResponse() { 23 | return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); 24 | } 25 | 26 | public static String getIpAddress() { 27 | HttpServletRequest request = getRequest(); 28 | String ip = request.getHeader("x-forwarded-for"); 29 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 30 | ip = request.getHeader("Proxy-Client-IP"); 31 | } 32 | 33 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 34 | ip = request.getHeader("WL-Proxy-Client-IP"); 35 | } 36 | 37 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 38 | ip = request.getRemoteAddr(); 39 | } 40 | 41 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 42 | ip = request.getHeader("HTTP_CLIENT_IP"); 43 | } 44 | 45 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 46 | ip = request.getHeader("X-Real-IP"); 47 | } 48 | 49 | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 50 | ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 51 | } 52 | 53 | String regex = ","; 54 | if (ip != null && ip.indexOf(regex) > 0) { 55 | ip = ip.split(regex)[0]; 56 | } 57 | 58 | return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /limiter/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | root: error 4 | 5 | spring: 6 | redis: 7 | host: localhost 8 | port: 6379 9 | database: 1 10 | password: 11 | timeout: 5000ms 12 | -------------------------------------------------------------------------------- /mail/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | mail 11 | mail 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-mail 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | 30 | ${project.name} 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-maven-plugin 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /mail/src/main/java/demo/springboot/mail/MailApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mail; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MailApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MailApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mail/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | mail: 3 | default-encoding: UTF-8 4 | host: smtp.163.com 5 | port: 465 6 | username: username@163.com 7 | password: password 8 | properties: 9 | mail.smtp.ssl.enable: true -------------------------------------------------------------------------------- /mail/src/test/java/demo/springboot/mail/MailApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mail; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.mail.SimpleMailMessage; 9 | import org.springframework.mail.javamail.JavaMailSender; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | public class MailApplicationTests { 15 | 16 | @Autowired 17 | private JavaMailSender mailSender; 18 | 19 | @Value("${spring.mail.username}") 20 | private String username; 21 | 22 | @Test 23 | public void testMail() { 24 | //建立邮件消息 25 | SimpleMailMessage mailMessage = new SimpleMailMessage(); 26 | //发送者 27 | mailMessage.setFrom(username); 28 | //接收者 29 | mailMessage.setTo("dean.lee@aliyun.com"); 30 | //发送的标题 31 | mailMessage.setSubject("主题"); 32 | //发送的内容 33 | mailMessage.setText("内容"); 34 | //发送邮件 35 | mailSender.send(mailMessage); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /multiple-datasource/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | multiple-datasource 11 | multiple-datasource 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | org.mybatis.spring.boot 25 | mybatis-spring-boot-starter 26 | 2.0.1 27 | 28 | 29 | com.alibaba 30 | druid-spring-boot-starter 31 | 1.1.14 32 | 33 | 34 | 35 | mysql 36 | mysql-connector-java 37 | runtime 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | true 44 | 45 | 46 | 47 | 48 | ${project.name} 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-maven-plugin 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/MultipleDatasourceApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MultipleDatasourceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MultipleDatasourceApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/config/DataSource1Config.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource.config; 2 | 3 | import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 4 | import org.apache.ibatis.session.SqlSessionFactory; 5 | import org.mybatis.spring.SqlSessionFactoryBean; 6 | import org.mybatis.spring.SqlSessionTemplate; 7 | import org.mybatis.spring.annotation.MapperScan; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Primary; 13 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 14 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 15 | 16 | import javax.sql.DataSource; 17 | 18 | @Configuration 19 | //指定扫描的dao包和SqlSession实例 20 | @MapperScan(basePackages = "demo.springboot.multipledatasource.dao1", sqlSessionTemplateRef="oneSqlSessionTemplate") 21 | public class DataSource1Config { 22 | 23 | /** 24 | * 连接池 25 | * @return 26 | */ 27 | @Bean 28 | @Primary 29 | @ConfigurationProperties("spring.datasource.druid.one") 30 | public DataSource oneDataSource(){ 31 | return DruidDataSourceBuilder.create().build(); 32 | } 33 | 34 | /** 35 | * SqlSessionFactory 36 | * @param dataSource 37 | * @return 38 | * @throws Exception 39 | */ 40 | @Bean 41 | @Primary 42 | public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception { 43 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 44 | bean.setDataSource(dataSource); 45 | //mapper文件位置 46 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/one/*.xml")); 47 | return bean.getObject(); 48 | } 49 | 50 | /** 51 | * 事务管理器 52 | * 注解@Primary:当程序中使用@Transactional时,优先使用该事务管理器。 53 | * 如果不使用@Primary注解,需要在@Transactional(value="oneTransactionManager")指定事务管理器 54 | * @param dataSource 55 | * @return 56 | */ 57 | @Bean 58 | @Primary 59 | public DataSourceTransactionManager oneTransactionManager(@Qualifier("oneDataSource")DataSource dataSource){ 60 | return new DataSourceTransactionManager(dataSource); 61 | } 62 | 63 | /** 64 | * SqlSession实例 65 | * @param sqlSessionFactory 66 | * @return 67 | */ 68 | @Bean 69 | @Primary 70 | public SqlSessionTemplate oneSqlSessionTemplate(@Qualifier("oneSqlSessionFactory")SqlSessionFactory sqlSessionFactory) { 71 | return new SqlSessionTemplate(sqlSessionFactory); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/config/DataSource2Config.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource.config; 2 | 3 | import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 4 | import org.apache.ibatis.session.SqlSessionFactory; 5 | import org.mybatis.spring.SqlSessionFactoryBean; 6 | import org.mybatis.spring.SqlSessionTemplate; 7 | import org.mybatis.spring.annotation.MapperScan; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 13 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 14 | 15 | import javax.sql.DataSource; 16 | 17 | @Configuration 18 | @MapperScan(basePackages = "demo.springboot.multipledatasource.dao2", sqlSessionTemplateRef="twoSqlSessionTemplate") 19 | public class DataSource2Config { 20 | 21 | @Bean 22 | @ConfigurationProperties("spring.datasource.druid.two") 23 | public DataSource twoDataSource(){ 24 | return DruidDataSourceBuilder.create().build(); 25 | } 26 | 27 | @Bean 28 | public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception{ 29 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 30 | bean.setDataSource(dataSource); 31 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/two/*.xml")); 32 | return bean.getObject(); 33 | } 34 | 35 | @Bean 36 | public DataSourceTransactionManager twoTransactionManager(@Qualifier("twoDataSource")DataSource dataSource){ 37 | return new DataSourceTransactionManager(dataSource); 38 | } 39 | 40 | @Bean 41 | public SqlSessionTemplate twoSqlSessionTemplate(@Qualifier("twoSqlSessionFactory")SqlSessionFactory sqlSessionFactory) { 42 | return new SqlSessionTemplate(sqlSessionFactory); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/dao1/User1DAO.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource.dao1; 2 | 3 | import demo.springboot.multipledatasource.domain.User; 4 | 5 | import java.util.List; 6 | 7 | public interface User1DAO { 8 | 9 | List selectAll(); 10 | } 11 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/dao2/User2DAO.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource.dao2; 2 | 3 | import demo.springboot.multipledatasource.domain.User; 4 | 5 | import java.util.List; 6 | 7 | public interface User2DAO { 8 | 9 | List selectAll(); 10 | } 11 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/java/demo/springboot/multipledatasource/domain/User.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource.domain; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class User { 7 | 8 | private String username; 9 | 10 | private String age; 11 | } 12 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | #使用druid连接池 4 | druid: 5 | #数据源1的名称 6 | one: 7 | driver-class-name: com.mysql.jdbc.Driver 8 | url: jdbc:mysql://192.168.211.128:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false 9 | username: root 10 | password: root 11 | #数据源2的名称 12 | two: 13 | driver-class-name: com.mysql.jdbc.Driver 14 | url: jdbc:mysql://192.168.211.129:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false 15 | username: root 16 | password: root 17 | logging: 18 | level: 19 | root: error 20 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/resources/mapper/one/User1Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 15 | -------------------------------------------------------------------------------- /multiple-datasource/src/main/resources/mapper/two/User2Mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 15 | -------------------------------------------------------------------------------- /multiple-datasource/src/test/java/demo/springboot/multipledatasource/MultipleDatasourceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.multipledatasource; 2 | 3 | import demo.springboot.multipledatasource.dao1.User1DAO; 4 | import demo.springboot.multipledatasource.dao2.User2DAO; 5 | import demo.springboot.multipledatasource.domain.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 MultipleDatasourceApplicationTests { 17 | 18 | @Autowired 19 | private User1DAO user1DAO; 20 | 21 | @Autowired 22 | private User2DAO user2DAO; 23 | 24 | @Test 25 | public void test() { 26 | List users1 = user1DAO.selectAll(); 27 | System.out.println(users1); 28 | List users2 = user2DAO.selectAll(); 29 | System.out.println(users2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | mybatis-mapper-pagehelper 11 | mybatis-mapper-pagehelper 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | 26 | org.mybatis.spring.boot 27 | mybatis-spring-boot-starter 28 | 2.0.0 29 | 30 | 31 | 32 | tk.mybatis 33 | mapper-spring-boot-starter 34 | 2.0.0 35 | 36 | 37 | 38 | mysql 39 | mysql-connector-java 40 | runtime 41 | 42 | 43 | 44 | com.alibaba 45 | druid-spring-boot-starter 46 | 1.1.14 47 | 48 | 49 | 50 | com.github.pagehelper 51 | pagehelper-spring-boot-starter 52 | 1.2.10 53 | 54 | 55 | 56 | org.projectlombok 57 | lombok 58 | true 59 | 60 | 61 | 62 | 63 | ${project.name} 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/main/java/demo/springboot/mybatismapperpagehelper/MybatisMapperPagehelperApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatismapperpagehelper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import tk.mybatis.spring.annotation.MapperScan; 6 | 7 | @SpringBootApplication 8 | //这里使用的扫描注解不是mybatis的,是通用mapper的注解 9 | @MapperScan("demo.springboot.mybatismapperpagehelper.dao") 10 | public class MybatisMapperPagehelperApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(MybatisMapperPagehelperApplication.class, args); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/main/java/demo/springboot/mybatismapperpagehelper/basedao/BaseMapper.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatismapperpagehelper.basedao; 2 | 3 | import tk.mybatis.mapper.common.Mapper; 4 | import tk.mybatis.mapper.common.MySqlMapper; 5 | 6 | /** 7 | * @author dean.lee 8 | */ 9 | //继承tkmapper中的接口,更多可查看官方文档 10 | //Mapper是基础的增删改查,根据Example查询等 11 | //MySqlMapper是对mysql的一些操作 12 | public interface BaseMapper extends Mapper, MySqlMapper { 13 | } 14 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/main/java/demo/springboot/mybatismapperpagehelper/dao/SysUserDAO.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatismapperpagehelper.dao; 2 | 3 | import demo.springboot.mybatismapperpagehelper.basedao.BaseMapper; 4 | import demo.springboot.mybatismapperpagehelper.domain.SysUser; 5 | 6 | /** 7 | * @author dean.lee 8 | */ 9 | public interface SysUserDAO extends BaseMapper { 10 | } 11 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/main/java/demo/springboot/mybatismapperpagehelper/domain/SysUser.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatismapperpagehelper.domain; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Id; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @Data 11 | public class SysUser { 12 | //根据主键查询时必须要有@Id注解,否则会报错 13 | @Id 14 | private Long id; 15 | 16 | private String username; 17 | 18 | private String password; 19 | 20 | private String nickname; 21 | 22 | private Integer age; 23 | } 24 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | spring: 5 | datasource: 6 | type: com.alibaba.druid.pool.DruidDataSource 7 | driver-class-name: com.mysql.jdbc.Driver 8 | url: jdbc:mysql://106.14.186.54:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false 9 | username: root 10 | password: mysql4aliyun 11 | 12 | mybatis: 13 | #\u52A0\u8F7Dmapper\u6587\u4EF6 14 | mapper-locations: classpath:mapper/*.xml 15 | #\u8BBE\u7F6E\u5B9E\u4F53\u7C7B\u522B\u540D 16 | #type-aliases-package: demo.springboot.mybatismapperpagehelper.domain 17 | #\u52A0\u8F7Dmybatis\u5168\u5C40\u914D\u7F6E\u6587\u4EF6 18 | #config-location: classpath:mybatis/SqlMapConfig.xml 19 | 20 | mapper: 21 | #\u901A\u7528mapper\u7684\u7C7B\uFF0C\u53EF\u4EE5\u591A\u4E2A\uFF0C\u4E0D\u8981\u548C\u4E1A\u52A1dao\u653E\u5230\u4E00\u8D77 22 | mappers: demo.springboot.mybatismapperpagehelper.basedao.BaseMapper 23 | 24 | logging: 25 | level: 26 | root: error 27 | demo.springboot: debug 28 | -------------------------------------------------------------------------------- /mybatis-mapper-pagehelper/src/test/java/demo/springboot/mybatismapperpagehelper/MybatisMapperPagehelperApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatismapperpagehelper; 2 | 3 | import com.github.pagehelper.PageHelper; 4 | import com.github.pagehelper.PageInfo; 5 | import demo.springboot.mybatismapperpagehelper.dao.SysUserDAO; 6 | import demo.springboot.mybatismapperpagehelper.domain.SysUser; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import java.util.List; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | public class MybatisMapperPagehelperApplicationTests { 18 | 19 | @Autowired 20 | private SysUserDAO userDAO; 21 | 22 | @Test 23 | public void testSelectByPrimaryKey() { 24 | //根据主键查询 25 | SysUser sysUser = userDAO.selectByPrimaryKey(1L); 26 | System.out.println(sysUser); 27 | } 28 | 29 | @Test 30 | public void testSelectAll() { 31 | //查询所有数据 32 | List sysUsers = userDAO.selectAll(); 33 | System.out.println(sysUsers); 34 | } 35 | 36 | @Test 37 | public void testPageHelper(){ 38 | //第一个参数为页数,第二个为条数。对这个方法后的第一个sql生效, 39 | //单表分页,一对一分页正确。一对多,多对多分页会出现错误 40 | //PageHelper.startPage(1, 10); 41 | //根据id倒序排序 42 | PageHelper.startPage(1, 2, "id desc"); 43 | List sysUsers = userDAO.selectAll(); 44 | 45 | //获取分页数据 46 | PageInfo pageInfo = new PageInfo<>(sysUsers); 47 | //获取总条数 48 | System.out.println(pageInfo.getTotal()); 49 | //获取分页页数 50 | System.out.println(pageInfo.getPageNum()); 51 | //获取分页条数 52 | System.out.println(pageInfo.getPageSize()); 53 | //获取分页数据,即上面查询到的sysUsers 54 | System.out.println(pageInfo.getList()); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | mybatis 11 | mybatis 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | org.mybatis.spring.boot 25 | mybatis-spring-boot-starter 26 | 2.0.1 27 | 28 | 29 | com.alibaba 30 | druid-spring-boot-starter 31 | 1.1.14 32 | 33 | 34 | 35 | mysql 36 | mysql-connector-java 37 | runtime 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | true 44 | 45 | 46 | 47 | 48 | ${project.name} 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-maven-plugin 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /mybatis/src/main/java/demo/springboot/mybatis/MybatisApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatis; 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("demo.springboot.mybatis.dao") 9 | public class MybatisApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(MybatisApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /mybatis/src/main/java/demo/springboot/mybatis/dao/SysUserMapper.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatis.dao; 2 | 3 | import demo.springboot.mybatis.domain.SysUser; 4 | import org.apache.ibatis.annotations.Param; 5 | import org.apache.ibatis.annotations.Update; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | public interface SysUserMapper { 11 | SysUser selectById(long id); 12 | 13 | @Update("update sys_user set age = #{age} where id = #{id}") 14 | int updateAgeById(@Param("age") int age, @Param("id") long id); 15 | } 16 | -------------------------------------------------------------------------------- /mybatis/src/main/java/demo/springboot/mybatis/domain/SysUser.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatis.domain; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author dean.lee 7 | */ 8 | @Data 9 | public class SysUser { 10 | private Long id; 11 | private String username; 12 | private String nickname; 13 | private Integer age; 14 | } 15 | -------------------------------------------------------------------------------- /mybatis/src/main/java/demo/springboot/mybatis/service/UserService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatis.service; 2 | 3 | import demo.springboot.mybatis.dao.SysUserMapper; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | /** 9 | * @author dean.lee 10 | */ 11 | @Service 12 | public class UserService { 13 | @Autowired 14 | private SysUserMapper userMapper; 15 | 16 | @Transactional(rollbackFor = RuntimeException.class) 17 | public void updateUserAge(){ 18 | userMapper.updateAgeById(40, 1L); 19 | int a = 1/0; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /mybatis/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | type: com.alibaba.druid.pool.DruidDataSource 4 | driver-class-name: com.mysql.jdbc.Driver 5 | url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false 6 | username: root 7 | password: root 8 | 9 | mybatis: 10 | #加载mapper文件 11 | mapper-locations: classpath:mapper/*.xml 12 | #设置实体类别名 13 | #type-aliases-package: demo.springboot.mybatis.domain 14 | #加载mybatis全局配置文件 15 | #config-location: classpath:mybatis/SqlMapConfig.xml -------------------------------------------------------------------------------- /mybatis/src/main/resources/mapper/SysUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 18 | -------------------------------------------------------------------------------- /mybatis/src/main/resources/mybatis/SqlMapConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /mybatis/src/test/java/demo/springboot/mybatis/MybatisApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mybatis; 2 | 3 | import demo.springboot.mybatis.dao.SysUserMapper; 4 | import demo.springboot.mybatis.domain.SysUser; 5 | import demo.springboot.mybatis.service.UserService; 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 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | public class MybatisApplicationTests { 15 | 16 | @Autowired 17 | private SysUserMapper userMapper; 18 | 19 | @Autowired 20 | private UserService userService; 21 | 22 | @Test 23 | public void testMybatis() { 24 | SysUser sysUser = userMapper.selectById(1L); 25 | System.out.println(sysUser); 26 | } 27 | 28 | @Test 29 | public void testTransactional(){ 30 | System.out.println(userMapper.selectById(1L)); 31 | 32 | try { 33 | userService.updateUserAge(); 34 | }catch (RuntimeException e){ 35 | 36 | } 37 | 38 | System.out.println(userMapper.selectById(1L)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /mysql/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | mysql 11 | mysql 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | mysql 26 | mysql-connector-java 27 | runtime 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-jdbc 32 | 33 | 34 | com.alibaba 35 | druid-spring-boot-starter 36 | 1.1.14 37 | 38 | 39 | 40 | 41 | ${project.name} 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-maven-plugin 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /mysql/src/main/java/demo/springboot/mysql/MysqlApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mysql; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class MysqlApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(MysqlApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mysql/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | type: com.alibaba.druid.pool.DruidDataSource 4 | driver-class-name: com.mysql.jdbc.Driver 5 | url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false 6 | username: root 7 | password: root 8 | 9 | logging: 10 | level: 11 | root: error 12 | -------------------------------------------------------------------------------- /mysql/src/test/java/demo/springboot/mysql/MysqlApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.mysql; 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.jdbc.core.JdbcTemplate; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class MysqlApplicationTests { 16 | 17 | @Autowired 18 | private JdbcTemplate jdbcTemplate; 19 | 20 | @Test 21 | public void testJdbc() { 22 | List> maps = jdbcTemplate.queryForList("select * from sys_user"); 23 | maps.forEach(System.out::println); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.0.6.RELEASE 10 | 11 | 12 | demo.springboot 13 | springboot-demo 14 | pom 15 | 1.0-SNAPSHOT 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | web-start 23 | properties 24 | bean 25 | mysql 26 | mybatis 27 | redis 28 | cache 29 | resttemplate 30 | aop 31 | scheduler 32 | mail 33 | activemq 34 | validation 35 | async 36 | mybatis-mapper-pagehelper 37 | redis-session 38 | limiter 39 | dubbo 40 | jedis-spring-boot-starter 41 | multiple-datasource 42 | sharding-jdbc 43 | websocket2 44 | websocket 45 | redisson 46 | 47 | 48 | springboot-demo 49 | https://github.com/dean4lee/springboot-demo 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /properties/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 11 | properties 12 | properties 13 | Demo project for Spring Boot 14 | 15 | 16 | 1.8 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | 26 | 27 | ${project.name} 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-maven-plugin 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /properties/src/main/java/demo/springboot/properties/PropertiesApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.properties; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class PropertiesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(PropertiesApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /properties/src/main/java/demo/springboot/properties/bean/PropertiesBean.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.properties.bean; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class PropertiesBean { 8 | @Value("${bean.name}") 9 | private String name; 10 | 11 | @Value("${bean.age}") 12 | private Integer age; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public Integer getAge() { 23 | return age; 24 | } 25 | 26 | public void setAge(Integer age) { 27 | this.age = age; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "PropertiesBean{" + 33 | "name='" + name + '\'' + 34 | ", age=" + age + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /properties/src/main/java/demo/springboot/properties/bean/PropertiesBean1.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.properties.bean; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties(prefix = "bean") 6 | //@Component 7 | public class PropertiesBean1 { 8 | 9 | private String name; 10 | private Integer age; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public Integer getAge() { 21 | return age; 22 | } 23 | 24 | public void setAge(Integer age) { 25 | this.age = age; 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return "PropertiesBean1{" + 31 | "name='" + name + '\'' + 32 | ", age=" + age + 33 | '}'; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /properties/src/main/java/demo/springboot/properties/bean/PropertiesBean2.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.properties.bean; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.PropertySource; 6 | 7 | @Configuration 8 | @PropertySource("classpath:test.properties") 9 | @ConfigurationProperties(prefix = "test") 10 | public class PropertiesBean2 { 11 | private String name; 12 | private Integer age; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public Integer getAge() { 23 | return age; 24 | } 25 | 26 | public void setAge(Integer age) { 27 | this.age = age; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "PropertiesBean2{" + 33 | "name='" + name + '\'' + 34 | ", age=" + age + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /properties/src/main/resources/application-db.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dean4lee/springboot-demo/a7863e1ff312ee7612c2ec931bd4374c4e1b58b8/properties/src/main/resources/application-db.yml -------------------------------------------------------------------------------- /properties/src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | servlet: 4 | context-path: / -------------------------------------------------------------------------------- /properties/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | servlet: 4 | context-path: / 5 | 6 | bean: 7 | name: springboot 8 | age: 20 9 | 10 | spring: 11 | profiles: 12 | include: db 13 | -------------------------------------------------------------------------------- /properties/src/main/resources/test.properties: -------------------------------------------------------------------------------- 1 | test.name=spring-test 2 | test.age=18 -------------------------------------------------------------------------------- /properties/src/test/java/demo/springboot/properties/PropertiesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.properties; 2 | 3 | import demo.springboot.properties.bean.PropertiesBean; 4 | import demo.springboot.properties.bean.PropertiesBean1; 5 | import demo.springboot.properties.bean.PropertiesBean2; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.core.env.Environment; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | 14 | @RunWith(SpringRunner.class) 15 | @SpringBootTest 16 | @EnableConfigurationProperties({PropertiesBean1.class}) 17 | public class PropertiesApplicationTests { 18 | 19 | @Autowired 20 | private PropertiesBean bean; 21 | @Autowired 22 | private PropertiesBean1 bean1; 23 | @Autowired 24 | private PropertiesBean2 bean2; 25 | @Autowired 26 | private Environment env; 27 | 28 | @Test 29 | public void loadBean() { 30 | System.out.println(bean); 31 | } 32 | 33 | @Test 34 | public void loadBean1() { 35 | System.out.println(bean1); 36 | } 37 | 38 | @Test 39 | public void loadBean2() { 40 | System.out.println(bean2); 41 | } 42 | 43 | @Test 44 | public void testEnvironment() { 45 | System.out.println(env.getProperty("bean.name")); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /redis-session/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | redis-session 11 | redis-session 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-data-redis 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | org.springframework.session 29 | spring-session-data-redis 30 | 31 | 32 | 33 | 34 | ${project.name} 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-maven-plugin 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /redis-session/src/main/java/demo/springboot/redissession/RedisSessionApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redissession; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RedisSessionApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RedisSessionApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /redis-session/src/main/java/demo/springboot/redissession/ctrl/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redissession.ctrl; 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 | * @author dean.lee 10 | */ 11 | @RestController 12 | public class TestController { 13 | 14 | //设置参数到session 15 | @GetMapping("/setValue") 16 | public String setValue(String value, HttpServletRequest request){ 17 | System.out.println("setValue"); 18 | request.getSession().setAttribute("value", value); 19 | return value; 20 | } 21 | 22 | //获取session中的参数 23 | @GetMapping("getValue") 24 | public String getValue(HttpServletRequest request){ 25 | System.out.println("getValue"); 26 | return (String) request.getSession().getAttribute("value"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /redis-session/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | logging: 5 | level: 6 | root: error 7 | 8 | spring: 9 | redis: 10 | host: localhost 11 | port: 6379 12 | database: 1 13 | password: 14 | timeout: 5000ms 15 | -------------------------------------------------------------------------------- /redis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | redis 11 | redis 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-data-redis 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | 30 | ${project.name} 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-maven-plugin 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /redis/src/main/java/demo/springboot/redis/RedisApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RedisApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RedisApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /redis/src/main/java/demo/springboot/redis/bean/BeanLoad.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redis.bean; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.serializer.StringRedisSerializer; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @Configuration 13 | public class BeanLoad { 14 | /** 15 | * 设置redisTemplate key序列化 16 | * @param factory 17 | * @return 18 | */ 19 | @Bean 20 | public RedisTemplate redisTemplate(RedisConnectionFactory factory){ 21 | RedisTemplate redisTemplate = new RedisTemplate<>(); 22 | redisTemplate.setConnectionFactory(factory); 23 | 24 | StringRedisSerializer keySerializer = new StringRedisSerializer(); 25 | redisTemplate.setKeySerializer(keySerializer); 26 | redisTemplate.setHashKeySerializer(keySerializer); 27 | 28 | redisTemplate.afterPropertiesSet(); 29 | return redisTemplate; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /redis/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | redis: 3 | #地址 4 | host: localhost 5 | #端口 6 | port: 6379 7 | #索引库 8 | database: 1 9 | #密码 10 | password: 11 | #超时时间 12 | timeout: 5000ms 13 | 14 | logging: 15 | level: 16 | root: error -------------------------------------------------------------------------------- /redis/src/test/java/demo/springboot/redis/RedisApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redis; 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.data.redis.core.StringRedisTemplate; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | @RunWith(SpringRunner.class) 12 | @SpringBootTest 13 | public class RedisApplicationTests { 14 | 15 | //@Autowired 16 | //private RedisTemplate redisTemplate; 17 | 18 | //@Resource 19 | @Autowired 20 | private RedisTemplate redisTemplate; 21 | 22 | @Autowired 23 | private StringRedisTemplate stringRedisTemplate; 24 | 25 | @Test 26 | public void contextLoads() { 27 | redisTemplate.opsForValue().set("test", 1); 28 | int test = (int) redisTemplate.opsForValue().get("test"); 29 | System.out.println(test); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /redisson/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | demo.springboot.redisson 13 | redisson 14 | 15 | 16 | 1.8 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.redisson 26 | redisson-spring-boot-starter 27 | 3.9.0 28 | 29 | 30 | 31 | 32 | mysql 33 | mysql-connector-java 34 | runtime 35 | 36 | 37 | org.mybatis.spring.boot 38 | mybatis-spring-boot-starter 39 | 2.0.1 40 | 41 | 42 | com.alibaba 43 | druid-spring-boot-starter 44 | 1.1.14 45 | 46 | 47 | 48 | org.projectlombok 49 | lombok 50 | true 51 | 52 | 53 | 54 | 55 | ${project.name} 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-maven-plugin 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /redisson/src/main/java/demo/springboot/redisson/RedissonApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson; 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("demo.springboot.redisson.dao") 9 | public class RedissonApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(RedissonApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /redisson/src/main/java/demo/springboot/redisson/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson.controller; 2 | 3 | import demo.springboot.redisson.domain.SysUser; 4 | import demo.springboot.redisson.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | public class UserController { 12 | @Autowired 13 | private UserService userService; 14 | 15 | @PostMapping("addUser") 16 | public String addUser(@RequestBody SysUser user){ 17 | return userService.addUser(user); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /redisson/src/main/java/demo/springboot/redisson/dao/SysUserMapper.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson.dao; 2 | 3 | 4 | import demo.springboot.redisson.domain.SysUser; 5 | import org.apache.ibatis.annotations.Insert; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | public interface SysUserMapper { 9 | 10 | @Select("select * from sys_user where username = #{username}") 11 | SysUser selectByUsername(String username); 12 | 13 | @Insert("insert into sys_user(username, password) values(#{username}, #{password})") 14 | int insert(SysUser user); 15 | } 16 | -------------------------------------------------------------------------------- /redisson/src/main/java/demo/springboot/redisson/domain/SysUser.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson.domain; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class SysUser { 7 | private String username; 8 | 9 | private String password; 10 | } 11 | -------------------------------------------------------------------------------- /redisson/src/main/java/demo/springboot/redisson/service/UserService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson.service; 2 | 3 | import demo.springboot.redisson.dao.SysUserMapper; 4 | import demo.springboot.redisson.domain.SysUser; 5 | import org.redisson.api.RLock; 6 | import org.redisson.api.RedissonClient; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class UserService { 12 | @Autowired 13 | private SysUserMapper userMapper; 14 | @Autowired 15 | private RedissonClient redissonClient; 16 | 17 | public String addUser(SysUser user){ 18 | // 获取锁,以username为锁名称。这样用户名相同的数据添加时,无法并行处理。 19 | // 第二次的请求需要等到第一次请求的锁释放后才可以继续执行 20 | RLock lock = redissonClient.getLock(user.getUsername()); 21 | // 默认锁30秒,如果当前线程处理时间过长。 22 | // redisson会在锁时间过了三分之二的时候将锁的时间重新设置为30秒 23 | lock.lock(); 24 | //将需要锁住的代码try起来,并在finally中释放锁 25 | try { 26 | // 判断用户账号是否重复 27 | SysUser sysUser = userMapper.selectByUsername(user.getUsername()); 28 | // 如果用户存在,抛出异常 29 | if (sysUser != null) { 30 | throw new RuntimeException("用户已经存在"); 31 | } 32 | // 模拟线程不安全的情况 33 | try { 34 | Thread.sleep(3000L); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } 38 | 39 | // 不重复则添加用户 40 | userMapper.insert(user); 41 | }finally { 42 | // 释放锁 43 | lock.unlock(); 44 | } 45 | return "success"; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /redisson/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | spring: 4 | redis: 5 | host: localhost 6 | port: 6379 7 | database: 0 8 | password: 9 | timeout: 3000ms 10 | redisson: 11 | config: classpath:redisson.yml 12 | 13 | datasource: 14 | type: com.alibaba.druid.pool.DruidDataSource 15 | driver-class-name: com.mysql.jdbc.Driver 16 | url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false 17 | username: root 18 | password: root 19 | 20 | logging: 21 | level: 22 | root: error 23 | demo.springboot: debug -------------------------------------------------------------------------------- /redisson/src/main/resources/redisson.yml: -------------------------------------------------------------------------------- 1 | #更多配置详情查看 https://github.com/redisson/redisson/wiki/2.-Configuration 2 | singleServerConfig: 3 | idleConnectionTimeout: 10000 4 | pingTimeout: 1000 5 | connectTimeout: 10000 6 | timeout: 3000 7 | retryAttempts: 3 8 | retryInterval: 1500 9 | reconnectionTimeout: 3000 10 | failedAttempts: 3 11 | password: 12 | subscriptionsPerConnection: 5 13 | clientName: null 14 | address: "redis://localhost:6379" 15 | subscriptionConnectionMinimumIdleSize: 1 16 | subscriptionConnectionPoolSize: 50 17 | connectionMinimumIdleSize: 32 18 | connectionPoolSize: 64 19 | database: 0 20 | #不注释会注入bean失败 21 | # dnsMonitoring: false 22 | # dnsMonitoringInterval: 5000 23 | threads: 0 24 | nettyThreads: 0 25 | codec: ! {} 26 | transportMode: NIO -------------------------------------------------------------------------------- /redisson/src/test/java/demo/springboot/redisson/RedissonApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.redisson; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.redisson.api.RedissonClient; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class RedissonApplicationTests { 13 | @Autowired 14 | private RedissonClient redissonClient; 15 | 16 | @Test 17 | public void initRedissonClient(){ 18 | System.out.println(redissonClient); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /resttemplate/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | resttemplate 11 | resttemplate 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | org.projectlombok 26 | lombok 27 | true 28 | 29 | 30 | 31 | 32 | ${project.name} 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-maven-plugin 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /resttemplate/src/main/java/demo/springboot/resttemplate/ResttemplateApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.resttemplate; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ResttemplateApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ResttemplateApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /resttemplate/src/main/java/demo/springboot/resttemplate/config/BeanLoad.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.resttemplate.config; 2 | 3 | import org.springframework.boot.web.client.RestTemplateBuilder; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | /** 9 | * @author dean.lee 10 | */ 11 | @Configuration 12 | public class BeanLoad { 13 | 14 | @Bean 15 | public RestTemplate restTemplate(RestTemplateBuilder builder){ 16 | return builder.build(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /resttemplate/src/main/java/demo/springboot/resttemplate/ctrl/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.resttemplate.ctrl; 2 | 3 | import demo.springboot.resttemplate.domain.User; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @RestController 13 | public class TestController { 14 | 15 | @GetMapping("getString") 16 | public String getString(String src){ 17 | return src; 18 | } 19 | 20 | @PostMapping("getUser") 21 | public User getUser(@RequestBody User user){ 22 | return user; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /resttemplate/src/main/java/demo/springboot/resttemplate/domain/User.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.resttemplate.domain; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author dean.lee 7 | */ 8 | @Data 9 | public class User { 10 | private Long id; 11 | private String name; 12 | private Integer age; 13 | } 14 | -------------------------------------------------------------------------------- /resttemplate/src/test/java/demo/springboot/resttemplate/ResttemplateApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.resttemplate; 2 | 3 | import demo.springboot.resttemplate.domain.User; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.http.HttpEntity; 9 | import org.springframework.http.HttpHeaders; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest 19 | public class ResttemplateApplicationTests { 20 | 21 | @Autowired 22 | private RestTemplate restTemplate; 23 | 24 | @Test 25 | public void testGetRequest(){ 26 | //直接获取响内容 27 | String object = restTemplate.getForObject("http://localhost:8080/getString?src=hello", String.class); 28 | System.out.println(object); 29 | 30 | //获取相应信息,包含响应状态、响应头、响应内容 31 | ResponseEntity entity = restTemplate.getForEntity("http://localhost:8080/getString?src=hello", String.class); 32 | System.out.println(entity); 33 | //响应状态码 34 | System.out.println(entity.getStatusCode()); 35 | //响应头 36 | System.out.println(entity.getHeaders()); 37 | //响应内容 38 | System.out.println(entity.getBody()); 39 | } 40 | 41 | @Test 42 | public void testPostRequest(){ 43 | Map postData = new HashMap<>(); 44 | postData.put("id", 1L); 45 | postData.put("name", "测试"); 46 | postData.put("age", 18); 47 | User user = restTemplate.postForObject("http://localhost:8080/getUser", postData, User.class); 48 | System.out.println(user); 49 | } 50 | 51 | @Test 52 | public void testPostHeaders(){ 53 | //设置请求头 54 | HttpHeaders httpHeaders = new HttpHeaders(); 55 | httpHeaders.add("Content-Type", "application/json;charset=utf-8"); 56 | 57 | //设置请求参数 58 | Map postData = new HashMap<>(); 59 | postData.put("id", 1L); 60 | postData.put("name", "测试"); 61 | postData.put("age", 18); 62 | 63 | //将请求头和请求参数设置到HttpEntity中 64 | HttpEntity> httpEntity = new HttpEntity<>(postData, httpHeaders); 65 | 66 | User user = restTemplate.postForObject("http://localhost:8080/getUser", httpEntity, User.class); 67 | System.out.println(user); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /scheduler/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | scheduler 11 | scheduler 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | 26 | ${project.name} 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-maven-plugin 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /scheduler/src/main/java/demo/springboot/scheduler/SchedulerApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.scheduler; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.scheduling.annotation.EnableScheduling; 6 | 7 | @SpringBootApplication 8 | @EnableScheduling 9 | public class SchedulerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SchedulerApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /scheduler/src/main/java/demo/springboot/scheduler/scheduling/TestScheduling.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.scheduler.scheduling; 2 | 3 | import org.springframework.scheduling.annotation.Scheduled; 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.text.SimpleDateFormat; 7 | import java.util.Date; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @Component 13 | public class TestScheduling { 14 | 15 | private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); 16 | 17 | @Scheduled(fixedDelay = 3000) 18 | public void printDate(){ 19 | System.out.println(sdf.format(new Date())); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /scheduler/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | root: error 4 | demo.springboot: debug 5 | -------------------------------------------------------------------------------- /sharding-jdbc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | sharding-jdbc 11 | sharding-jdbc 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | org.mybatis.spring.boot 25 | mybatis-spring-boot-starter 26 | 2.0.1 27 | 28 | 29 | 30 | com.alibaba 31 | druid 32 | 1.1.14 33 | 34 | 35 | 36 | org.apache.shardingsphere 37 | sharding-jdbc-spring-boot-starter 38 | 4.0.0 39 | 40 | 41 | mysql 42 | mysql-connector-java 43 | runtime 44 | 45 | 46 | 47 | 48 | ${project.name} 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-maven-plugin 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/ShardingJdbcApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc; 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("demo.springboot.shardingjdbc.dao") 9 | public class ShardingJdbcApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ShardingJdbcApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/dao/DictDAO.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.dao; 2 | 3 | import demo.springboot.shardingjdbc.domain.Dict; 4 | import org.apache.ibatis.annotations.Insert; 5 | 6 | public interface DictDAO { 7 | 8 | @Insert("insert into t_dict(name) values(#{name})") 9 | int insert(Dict dict); 10 | } 11 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/dao/OrderDAO.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.dao; 2 | 3 | import demo.springboot.shardingjdbc.domain.Order; 4 | import demo.springboot.shardingjdbc.domain.OrderItem; 5 | import org.apache.ibatis.annotations.Insert; 6 | import org.apache.ibatis.annotations.Options; 7 | import org.apache.ibatis.annotations.Select; 8 | 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | public interface OrderDAO { 13 | 14 | //使用表名是配置文件中的逻辑表名称 15 | @Insert("insert into t_order(user_id, product_name) values(#{userId}, #{productName})") 16 | //返回主键的值 17 | @Options(useGeneratedKeys = true, keyProperty = "orderId") 18 | int insertOrder(Order order); 19 | 20 | @Insert("insert into t_order_item(order_id, create_time, user_id) values(#{orderId}, #{createTime}, #{userId})") 21 | int insertOrderItem(OrderItem item); 22 | 23 | //表别名需要加as,不加会报错 24 | @Select("select * from t_order as o left join t_order_item as item on o.order_id = item.order_id order by o.order_id desc") 25 | List selectAll(); 26 | } 27 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/domain/Dict.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.domain; 2 | 3 | public class Dict { 4 | 5 | private Long id; 6 | 7 | private String name; 8 | 9 | public Long getId() { 10 | return id; 11 | } 12 | 13 | public void setId(Long id) { 14 | this.id = id; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/domain/Order.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.domain; 2 | 3 | public class Order { 4 | 5 | private Long orderId; 6 | 7 | private Long userId; 8 | 9 | private String productName; 10 | 11 | public Long getOrderId() { 12 | return orderId; 13 | } 14 | 15 | public void setOrderId(Long orderId) { 16 | this.orderId = orderId; 17 | } 18 | 19 | public Long getUserId() { 20 | return userId; 21 | } 22 | 23 | public void setUserId(Long userId) { 24 | this.userId = userId; 25 | } 26 | 27 | public String getProductName() { 28 | return productName; 29 | } 30 | 31 | public void setProductName(String productName) { 32 | this.productName = productName; 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return "Order{" + 38 | "orderId=" + orderId + 39 | ", userId=" + userId + 40 | ", productName='" + productName + '\'' + 41 | '}'; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/domain/OrderItem.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.domain; 2 | 3 | import java.util.Date; 4 | 5 | public class OrderItem { 6 | 7 | private Long orderItemId; 8 | 9 | private Long orderId; 10 | 11 | private Long userId; 12 | 13 | private Date createTime; 14 | 15 | public Long getOrderItemId() { 16 | return orderItemId; 17 | } 18 | 19 | public void setOrderItemId(Long orderItemId) { 20 | this.orderItemId = orderItemId; 21 | } 22 | 23 | public Long getOrderId() { 24 | return orderId; 25 | } 26 | 27 | public void setOrderId(Long orderId) { 28 | this.orderId = orderId; 29 | } 30 | 31 | public Long getUserId() { 32 | return userId; 33 | } 34 | 35 | public void setUserId(Long userId) { 36 | this.userId = userId; 37 | } 38 | 39 | public Date getCreateTime() { 40 | return createTime; 41 | } 42 | 43 | public void setCreateTime(Date createTime) { 44 | this.createTime = createTime; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/java/demo/springboot/shardingjdbc/service/TestService.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc.service; 2 | 3 | import demo.springboot.shardingjdbc.dao.DictDAO; 4 | import demo.springboot.shardingjdbc.dao.OrderDAO; 5 | import demo.springboot.shardingjdbc.domain.Dict; 6 | import demo.springboot.shardingjdbc.domain.Order; 7 | import demo.springboot.shardingjdbc.domain.OrderItem; 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.Date; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | @Service 17 | public class TestService { 18 | 19 | @Autowired 20 | private OrderDAO orderDAO; 21 | @Autowired 22 | private DictDAO dictDAO; 23 | 24 | @Transactional 25 | public void addOrder() { 26 | for (int i = 0; i < 10; i++) { 27 | //模拟分库策略,根据用户id分库 28 | Long userId = 1L; 29 | if (i % 2 == 0) { 30 | userId = 2L; 31 | } 32 | //添加订单 33 | Order order = new Order(); 34 | order.setProductName("test"); 35 | order.setUserId(userId); 36 | orderDAO.insertOrder(order); 37 | 38 | //添加订单详情 39 | OrderItem item = new OrderItem(); 40 | item.setUserId(userId); 41 | item.setOrderId(order.getOrderId()); 42 | item.setCreateTime(new Date()); 43 | orderDAO.insertOrderItem(item); 44 | } 45 | } 46 | 47 | public List selectAll(){ 48 | List maps = orderDAO.selectAll(); 49 | return maps; 50 | } 51 | 52 | @Transactional 53 | public void addDict(){ 54 | Dict dict = new Dict(); 55 | dict.setName("haha"); 56 | dictDAO.insert(dict); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/resources/application-sharding.yml: -------------------------------------------------------------------------------- 1 | #分片配置 2 | spring: 3 | shardingsphere: 4 | datasource: 5 | #数据源名称,多数据源以逗号分隔 6 | names: ds0, ds1 7 | ds0: 8 | type: com.alibaba.druid.pool.DruidDataSource 9 | driver-class-name: com.mysql.jdbc.Driver 10 | url: jdbc:mysql://192.168.211.128:3306/sharding-jdbc?useUnicode=true&characterEncoding=UTF-8&useSSL=false 11 | username: root 12 | password: root 13 | ds1: 14 | type: com.alibaba.druid.pool.DruidDataSource 15 | driver-class-name: com.mysql.jdbc.Driver 16 | url: jdbc:mysql://192.168.211.129:3306/sharding-jdbc?useUnicode=true&characterEncoding=UTF-8&useSSL=false 17 | username: root 18 | password: root 19 | 20 | sharding: 21 | tables: 22 | #逻辑表名称(随意取名),在项目中sql使用 23 | t_order: 24 | #逻辑表名称指向的实际表,数据源名 + 实际表名组成 25 | #ds$->{0..1}代表数据源ds0或者ds1,库分片策略决定使用哪个数据源 26 | #t_order$->{0..1}代表表t_order0或者t_order1,表分片策略决定使用哪个表 27 | actual-data-nodes: ds$->{0..1}.t_order$->{0..1} 28 | #主键生成规则,自动生成主键 29 | key-generator: 30 | #主键的字段名称 31 | column: order_id 32 | #雪花算法生成主键 33 | type: SNOWFLAKE 34 | #分布式主键需要设置worker.id不能相同 35 | props: 36 | worker.id = 1 37 | #表分片策略 38 | table-strategy: 39 | #inline行表达式分片 40 | inline: 41 | #分片字段的名称 42 | sharding-column: order_id 43 | #分片算法行表达式,需符合groovy语法. 44 | #根据order_id%2计算出当前执行的sql是在t_order0还是t_order1中执行 45 | algorithm-expression: t_order$->{order_id % 2} 46 | #库分片策略 47 | database-strategy: 48 | inline: 49 | #分片字段的名称 50 | sharding-column: user_id 51 | #分片算法 52 | algorithm-expression: ds$->{user_id % 2} 53 | #订单详情表配置 54 | t_order_item: 55 | actual-data-nodes: ds$->{0..1}.t_order_item$->{0..1} 56 | key-generator: 57 | column: order_item_id 58 | type: SNOWFLAKE 59 | props: 60 | worker.id = 1 61 | table-strategy: 62 | inline: 63 | sharding-column: order_id 64 | algorithm-expression: t_order_item$->{order_id % 2} 65 | database-strategy: 66 | inline: 67 | sharding-column: user_id 68 | algorithm-expression: ds$->{user_id % 2} 69 | #公共表配置 70 | t_dict: 71 | key-generator: 72 | column: id 73 | type: SNOWFLAKE 74 | props: 75 | worker.id = 1 76 | #默认的库分片策略,所有的库分片策略相同时使用 77 | # default-database-strategy: 78 | # inline: 79 | # sharding-column: user_id 80 | # algorithm-expression: ds$->{user_id % 2} 81 | 82 | #绑定表,垂直分表需要绑定,不绑定会出现笛卡尔积 83 | #绑定表的分片策略中的sharding-column配置要相同 84 | binding-tables: 85 | - t_order, t_order_item 86 | #广播表,修改操作会操作所有库的表,即公共表 87 | broadcast-tables: t_dict 88 | #开启sql显示 89 | props: 90 | sql.show: true 91 | 92 | logging: 93 | level: 94 | root: error 95 | #sharding-jdbc的sql显示日志是info级别 96 | ShardingSphere-SQL: info 97 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/resources/application-split.yml: -------------------------------------------------------------------------------- 1 | #读写分离配置 2 | spring: 3 | shardingsphere: 4 | datasource: 5 | names: master, slave 6 | master: 7 | type: com.alibaba.druid.pool.DruidDataSource 8 | driver-class-name: com.mysql.jdbc.Driver 9 | url: jdbc:mysql://192.168.211.128:3306/sharding-jdbc?useUnicode=true&characterEncoding=UTF-8&useSSL=false 10 | username: root 11 | password: root 12 | slave: 13 | type: com.alibaba.druid.pool.DruidDataSource 14 | driver-class-name: com.mysql.jdbc.Driver 15 | url: jdbc:mysql://192.168.211.130:3306/sharding-jdbc?useUnicode=true&characterEncoding=UTF-8&useSSL=false 16 | username: root 17 | password: root 18 | 19 | sharding: 20 | #sharding-jdbc支持一主多从 21 | master-slave-rules: 22 | #读写分离数据源名称 23 | ds0: 24 | #主数据源的名称,对应数据源中配置的名称 25 | master-data-source-name: master 26 | #从数据源名称 27 | slave-data-source-names: slave 28 | #从库负载均衡算法类型,可选值:ROUND_ROBIN,RANDOM 29 | #load-balance-algorithm-type: ROUND_ROBIN 30 | #分片策略配置不变,只需要在使用读写分离的actual-data-nodes中修改为读写分离数据源名称即可 31 | tables: 32 | t_order: 33 | actual-data-nodes: ds0.t_order$->{0..1} 34 | key-generator: 35 | column: order_id 36 | type: SNOWFLAKE 37 | props: 38 | worker.id = 1 39 | table-strategy: 40 | inline: 41 | sharding-column: order_id 42 | algorithm-expression: t_order$->{order_id % 2} 43 | t_order_item: 44 | actual-data-nodes: ds0.t_order_item$->{0..1} 45 | key-generator: 46 | column: order_item_id 47 | type: SNOWFLAKE 48 | props: 49 | worker.id = 1 50 | table-strategy: 51 | inline: 52 | sharding-column: order_id 53 | algorithm-expression: t_order_item$->{order_id % 2} 54 | props: 55 | sql.show: true 56 | 57 | logging: 58 | level: 59 | root: error 60 | ShardingSphere-SQL: info 61 | -------------------------------------------------------------------------------- /sharding-jdbc/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: sharding #split -------------------------------------------------------------------------------- /sharding-jdbc/src/main/resources/sharding-jdbc.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat Premium Data Transfer 3 | 4 | Source Server : xuniji 5 | Source Server Type : MySQL 6 | Source Server Version : 50728 7 | Source Host : 192.168.211.128:3306 8 | Source Schema : sharding-jdbc 9 | 10 | Target Server Type : MySQL 11 | Target Server Version : 50728 12 | File Encoding : 65001 13 | 14 | Date: 20/03/2020 19:24:52 15 | */ 16 | 17 | SET NAMES utf8mb4; 18 | SET FOREIGN_KEY_CHECKS = 0; 19 | 20 | -- ---------------------------- 21 | -- Table structure for t_dict 22 | -- ---------------------------- 23 | DROP TABLE IF EXISTS `t_dict`; 24 | CREATE TABLE `t_dict` ( 25 | `id` bigint(20) NOT NULL, 26 | `name` varchar(255) NOT NULL, 27 | PRIMARY KEY (`id`) USING BTREE 28 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 29 | 30 | -- ---------------------------- 31 | -- Table structure for t_order0 32 | -- ---------------------------- 33 | DROP TABLE IF EXISTS `t_order0`; 34 | CREATE TABLE `t_order0` ( 35 | `order_id` bigint(20) NOT NULL COMMENT '订单id', 36 | `user_id` bigint(20) NOT NULL COMMENT '购买的用户id', 37 | `product_name` varchar(255) NOT NULL COMMENT '购买的商品名称', 38 | PRIMARY KEY (`order_id`) 39 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 40 | 41 | -- ---------------------------- 42 | -- Table structure for t_order1 43 | -- ---------------------------- 44 | DROP TABLE IF EXISTS `t_order1`; 45 | CREATE TABLE `t_order1` ( 46 | `order_id` bigint(20) NOT NULL COMMENT '订单id', 47 | `user_id` bigint(20) NOT NULL COMMENT '购买的用户id', 48 | `product_name` varchar(255) NOT NULL COMMENT '购买的商品名称', 49 | PRIMARY KEY (`order_id`) 50 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 51 | 52 | -- ---------------------------- 53 | -- Table structure for t_order_item0 54 | -- ---------------------------- 55 | DROP TABLE IF EXISTS `t_order_item0`; 56 | CREATE TABLE `t_order_item0` ( 57 | `order_item_id` bigint(20) NOT NULL COMMENT '订单详情的id', 58 | `order_id` bigint(20) NOT NULL COMMENT '关联订单的id', 59 | `create_time` datetime NOT NULL COMMENT '订单创建的时间', 60 | `user_id` bigint(10) NOT NULL, 61 | PRIMARY KEY (`order_item_id`) USING BTREE 62 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 63 | 64 | -- ---------------------------- 65 | -- Table structure for t_order_item1 66 | -- ---------------------------- 67 | DROP TABLE IF EXISTS `t_order_item1`; 68 | CREATE TABLE `t_order_item1` ( 69 | `order_item_id` bigint(20) NOT NULL COMMENT '订单详情的id', 70 | `order_id` bigint(20) NOT NULL COMMENT '关联订单的id', 71 | `create_time` datetime NOT NULL COMMENT '订单创建的时间', 72 | `user_id` bigint(10) NOT NULL, 73 | PRIMARY KEY (`order_item_id`) USING BTREE 74 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 75 | 76 | SET FOREIGN_KEY_CHECKS = 1; 77 | -------------------------------------------------------------------------------- /sharding-jdbc/src/test/java/demo/springboot/shardingjdbc/ShardingJdbcApplicationTests.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.shardingjdbc; 2 | 3 | import demo.springboot.shardingjdbc.service.TestService; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class ShardingJdbcApplicationTests { 16 | @Autowired 17 | private TestService testService; 18 | 19 | @Test 20 | public void testAddOrder() { 21 | testService.addOrder(); 22 | } 23 | 24 | @Test 25 | public void testSelectAll(){ 26 | List select = testService.selectAll(); 27 | System.out.println(select); 28 | } 29 | 30 | @Test 31 | public void testAddDict(){ 32 | testService.addDict(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /validation/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | validation 11 | validation 12 | Demo project for Spring Boot 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-web 22 | 23 | 24 | 25 | org.projectlombok 26 | lombok 27 | true 28 | 29 | 30 | 31 | 32 | ${project.name} 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-maven-plugin 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/ValidationApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ValidationApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ValidationApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/annotation/Phone.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.annotation; 2 | 3 | import demo.springboot.validation.validator.PhoneValidator; 4 | 5 | import javax.validation.Constraint; 6 | import javax.validation.Payload; 7 | import java.lang.annotation.Documented; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import static java.lang.annotation.ElementType.ANNOTATION_TYPE; 12 | import static java.lang.annotation.ElementType.CONSTRUCTOR; 13 | import static java.lang.annotation.ElementType.FIELD; 14 | import static java.lang.annotation.ElementType.METHOD; 15 | import static java.lang.annotation.ElementType.PARAMETER; 16 | import static java.lang.annotation.ElementType.TYPE_USE; 17 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 18 | 19 | /** 20 | * @author dean.lee 21 | */ 22 | @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) 23 | @Retention(RUNTIME) 24 | //用于校验手机号的逻辑类 25 | @Constraint(validatedBy = PhoneValidator.class) 26 | public @interface Phone { 27 | //手机号的校验格式 28 | String regexp() default "^[1][3-9][0-9]{9}$"; 29 | 30 | //出现错误返回的信息 31 | String message() default "手机号格式错误"; 32 | 33 | Class[] groups() default { }; 34 | 35 | Class[] payload() default { }; 36 | 37 | @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) 38 | @Retention(RUNTIME) 39 | @Documented 40 | public @interface List { 41 | Phone[] value(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/ctrl/PhoneController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.ctrl; 2 | 3 | import demo.springboot.validation.annotation.Phone; 4 | import demo.springboot.validation.util.JsonResult; 5 | import org.springframework.validation.annotation.Validated; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.validation.constraints.NotNull; 10 | 11 | /** 12 | * @author dean.lee 13 | */ 14 | @RestController 15 | @Validated 16 | public class PhoneController { 17 | 18 | @GetMapping("/sendPhone") 19 | public JsonResult sendPhone(@Phone @NotNull(message = "手机号不能为空") String phone){ 20 | return JsonResult.success("正确的手机号"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/ctrl/RoleController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.ctrl; 2 | 3 | import demo.springboot.validation.domian.Role; 4 | import demo.springboot.validation.group.Add; 5 | import demo.springboot.validation.group.Update; 6 | import demo.springboot.validation.util.JsonResult; 7 | import org.springframework.validation.annotation.Validated; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * @author dean.lee 13 | */ 14 | @RestController 15 | public class RoleController { 16 | 17 | @GetMapping("add") 18 | public JsonResult add(@Validated(Add.class) Role role){ 19 | return JsonResult.success("添加成功"); 20 | } 21 | 22 | @GetMapping("update") 23 | public JsonResult update(@Validated(Update.class) Role role){ 24 | return JsonResult.success("修改成功"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/ctrl/UserBetterController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.ctrl; 2 | 3 | import demo.springboot.validation.domian.User; 4 | import demo.springboot.validation.util.JsonResult; 5 | import org.springframework.validation.annotation.Validated; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import javax.validation.constraints.NotNull; 13 | 14 | /** 15 | * @author dean.lee 16 | */ 17 | @RestController 18 | @RequestMapping("/better") 19 | @Validated 20 | public class UserBetterController { 21 | 22 | @PostMapping("/login") 23 | public JsonResult login(@Validated @RequestBody User user){ 24 | return JsonResult.success("登陆成功"); 25 | } 26 | 27 | @GetMapping("/getLogin") 28 | public JsonResult getLogin(@Validated User user){ 29 | return JsonResult.success("登陆成功"); 30 | } 31 | 32 | @GetMapping("/getUser") 33 | public JsonResult getUser(@NotNull(message = "用户名不能为空") String username){ 34 | User user = new User(); 35 | user.setUsername(username); 36 | user.setPassword("123456"); 37 | return JsonResult.success(user); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/ctrl/UserController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.ctrl; 2 | 3 | import demo.springboot.validation.domian.User; 4 | import demo.springboot.validation.util.JsonResult; 5 | import org.springframework.validation.BindingResult; 6 | import org.springframework.validation.annotation.Validated; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import javax.validation.constraints.NotNull; 13 | 14 | /** 15 | * @author dean.lee 16 | */ 17 | @RestController 18 | //在请求方法中校验需要在类上加该注解 19 | @Validated 20 | public class UserController { 21 | 22 | //测试post请求 23 | //@Validated用于校验参数,如果参数校验失败,错误信息封装到BindingResult 24 | @PostMapping("/login") 25 | public JsonResult login(@Validated @RequestBody User user, BindingResult bindingResult){ 26 | //判断BindingResult中是否有错误信息 27 | if(bindingResult.hasErrors()){ 28 | return JsonResult.fail(bindingResult.getFieldError().getDefaultMessage()); 29 | } 30 | return JsonResult.success("登陆成功"); 31 | } 32 | 33 | //测试get请求 34 | @GetMapping("/getLogin") 35 | public JsonResult getLogin(@Validated User user, BindingResult bindingResult){ 36 | System.out.println(user); 37 | if(bindingResult.hasErrors()){ 38 | return JsonResult.fail(bindingResult.getFieldError().getDefaultMessage()); 39 | } 40 | return JsonResult.success("登陆成功"); 41 | } 42 | 43 | //测试请求方法中校验 44 | //这种校验不支持封装到BindingResult中,需要自己做异常处理 45 | @GetMapping("/getUser") 46 | public JsonResult getUser(@NotNull(message = "用户名不能为空") String username){ 47 | User user = new User(); 48 | user.setUsername(username); 49 | user.setPassword("123456"); 50 | return JsonResult.success(user); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/domian/Role.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.domian; 2 | 3 | import demo.springboot.validation.group.Add; 4 | import demo.springboot.validation.group.Update; 5 | import lombok.Data; 6 | import org.hibernate.validator.constraints.Length; 7 | 8 | import javax.validation.constraints.NotNull; 9 | 10 | /** 11 | * @author dean.lee 12 | */ 13 | @Data 14 | public class Role { 15 | 16 | //修改角色时,必须要有id 17 | @NotNull(message = "修改角色必须有id", groups = Update.class) 18 | private Long id; 19 | 20 | //添加角色时必须要有name 21 | @NotNull(message = "添加角色必须有name", groups = Add.class) 22 | //添加修改都需要name的长度在1-10 23 | @Length(min = 1, max = 10, message = "名称不合法", groups = {Add.class, Update.class}) 24 | private String name; 25 | } 26 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/domian/User.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.domian; 2 | 3 | import lombok.Data; 4 | import org.hibernate.validator.constraints.Length; 5 | 6 | import javax.validation.constraints.NotNull; 7 | import java.io.Serializable; 8 | 9 | /** 10 | * @author dean.lee 11 | */ 12 | @Data 13 | public class User implements Serializable { 14 | 15 | @Length(min = 5, max = 10, message = "用户名长度不合法") 16 | @NotNull(message = "用户名不能为空") 17 | private String username; 18 | 19 | @Length(min = 6, max = 16, message = "密码长度不合法") 20 | @NotNull(message = "密码不能为空") 21 | private String password; 22 | } 23 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/group/Add.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.group; 2 | 3 | /** 4 | * @author dean.lee 5 | */ 6 | public interface Add { 7 | } 8 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/group/Update.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.group; 2 | 3 | /** 4 | * @author dean.lee 5 | */ 6 | public interface Update { 7 | } 8 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/handler/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.handler; 2 | 3 | import demo.springboot.validation.util.JsonResult; 4 | import org.springframework.validation.BindException; 5 | import org.springframework.web.bind.MethodArgumentNotValidException; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.RestControllerAdvice; 8 | 9 | import javax.validation.ConstraintViolationException; 10 | 11 | /** 12 | * @author dean.lee 13 | */ 14 | @RestControllerAdvice 15 | public class GlobalExceptionHandler { 16 | 17 | /** 18 | * post请求参数校验抛出的异常 19 | * @param e 20 | * @return 21 | */ 22 | @ExceptionHandler(MethodArgumentNotValidException.class) 23 | public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){ 24 | //获取异常中随机一个异常信息 25 | String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage(); 26 | return JsonResult.fail(defaultMessage); 27 | } 28 | 29 | /** 30 | * get请求参数校验抛出的异常 31 | * @param e 32 | * @return 33 | */ 34 | @ExceptionHandler(BindException.class) 35 | public JsonResult bindExceptionHandler(BindException e){ 36 | //获取异常中随机一个异常信息 37 | String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage(); 38 | return JsonResult.fail(defaultMessage); 39 | } 40 | 41 | /** 42 | * 请求方法中校验抛出的异常 43 | * @param e 44 | * @return 45 | */ 46 | @ExceptionHandler(ConstraintViolationException.class) 47 | public JsonResult constraintViolationExceptionHandler(ConstraintViolationException e){ 48 | //获取异常中第一个错误信息 49 | String message = e.getConstraintViolations().iterator().next().getMessage(); 50 | return JsonResult.fail(message); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/util/JsonResult.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.util; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * @author dean.lee 9 | */ 10 | @Data 11 | public class JsonResult implements Serializable { 12 | private static final long serialVersionUID = -1946193220290386110L; 13 | 14 | public static final boolean SUCCESS = true; 15 | public static final boolean FAIL = false; 16 | 17 | private boolean status; 18 | private int code; 19 | private String msg; 20 | private Object data; 21 | 22 | public JsonResult(boolean status, int code, String msg, Object data) { 23 | this.status = status; 24 | this.code = code; 25 | this.msg = msg; 26 | this.data = data; 27 | } 28 | 29 | public static JsonResult success(Object data) { 30 | return new JsonResult(SUCCESS, 200, "ok", data); 31 | } 32 | 33 | public static JsonResult success(String msg) { 34 | return new JsonResult(SUCCESS, 200, msg, null); 35 | } 36 | 37 | public static JsonResult fail(String msg) { 38 | return fail(400, msg); 39 | } 40 | 41 | public static JsonResult fail(int code, String msg) { 42 | return new JsonResult(FAIL, code, msg, null); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /validation/src/main/java/demo/springboot/validation/validator/PhoneValidator.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.validation.validator; 2 | 3 | import demo.springboot.validation.annotation.Phone; 4 | 5 | import javax.validation.ConstraintValidator; 6 | import javax.validation.ConstraintValidatorContext; 7 | 8 | /** 9 | * @author dean.lee 10 | */ 11 | //校验注解的类必须实现ConstraintValidator,第一个泛型是注解,第二个泛型是校验参数的类型(手机号是String类型) 12 | public class PhoneValidator implements ConstraintValidator { 13 | 14 | private String regexp; 15 | 16 | //初始化方法 17 | @Override 18 | public void initialize(Phone constraintAnnotation) { 19 | //获取校验的手机号的格式 20 | this.regexp = constraintAnnotation.regexp(); 21 | } 22 | 23 | //value是@Phone所注解的字段值 24 | //校验,返回true则通过校验,返回false则校验失败,错误信息为注解中的message 25 | @Override 26 | public boolean isValid(String value, ConstraintValidatorContext context) { 27 | if(value == null){ 28 | return true; 29 | } 30 | 31 | return value.matches(regexp); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /web-start/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 11 | web-start 12 | web-start 13 | Demo project for Spring Boot 14 | 15 | 16 | 1.8 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | 26 | 27 | ${project.name} 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-maven-plugin 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /web-start/src/main/java/demo/springboot/webstart/WebStartApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.webstart; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class WebStartApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(WebStartApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /web-start/src/main/java/demo/springboot/webstart/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.webstart.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class TestController { 8 | 9 | @GetMapping("/test") 10 | public String test(){ 11 | return "hello"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /web-start/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | servlet: 4 | context-path: / 5 | -------------------------------------------------------------------------------- /websocket/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | demo.springboot.websocket 13 | websocket 14 | 15 | 16 | 1.8 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-websocket 23 | 24 | 25 | org.projectlombok 26 | lombok 27 | 28 | 29 | 30 | 31 | ${project.name} 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-maven-plugin 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/WebsocketApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class WebsocketApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(WebsocketApplication.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.config; 2 | 3 | import demo.springboot.websocket.handler.MyHandshakeHandler; 4 | import demo.springboot.websocket.handler.MyWebSocketHandler; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 8 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 9 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 10 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 11 | import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; 12 | 13 | @Configuration 14 | //开启消息代理,默认使用内置消息代理,也可以选择配置RabbitMQ等 15 | @EnableWebSocketMessageBroker 16 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 17 | @Autowired 18 | private MyWebSocketHandler myWebSocketHandler; 19 | @Autowired 20 | private MyHandshakeHandler myHandshakeHandler; 21 | 22 | @Override 23 | public void configureMessageBroker(MessageBrokerRegistry registry) { 24 | //启用/user /topic两个消息前缀,消息发送的前缀,也是前端订阅的前缀 25 | registry.enableSimpleBroker("/user", "/topic"); 26 | //当使用convertAndSendToUser发送消息时,前端订阅用/user开头。即一对一发送消息,使用/user为前缀订阅 27 | registry.setUserDestinationPrefix("/user"); 28 | //前端向服务端发送消息的前缀 29 | registry.setApplicationDestinationPrefixes("/im/"); 30 | } 31 | 32 | @Override 33 | public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) { 34 | //客户端和服务端进行连接的endpoint 35 | //如果使用移动端开发app,需要/im/conn/websocket连接 36 | stompEndpointRegistry.addEndpoint("/im/conn") 37 | .setHandshakeHandler(myHandshakeHandler)//设置连接校验 38 | .setAllowedOrigins("*")//跨域 39 | .withSockJS();//开启sockjs 40 | } 41 | 42 | @Override 43 | public void configureWebSocketTransport(WebSocketTransportRegistration registry) { 44 | //注册登陆退出 45 | registry.addDecoratorFactory(myWebSocketHandler); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/handler/MyHandshakeHandler.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.handler; 2 | 3 | import demo.springboot.websocket.principal.MyPrincipal; 4 | import org.springframework.http.server.ServerHttpRequest; 5 | import org.springframework.http.server.ServletServerHttpRequest; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.web.socket.WebSocketHandler; 8 | import org.springframework.web.socket.server.support.DefaultHandshakeHandler; 9 | 10 | import java.security.Principal; 11 | import java.util.Map; 12 | 13 | /** 14 | * 连接时校验用户信息,并返回重写的Principal 15 | */ 16 | @Component 17 | public class MyHandshakeHandler extends DefaultHandshakeHandler { 18 | 19 | @Override 20 | protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map attributes) { 21 | if (!(request instanceof ServletServerHttpRequest)) { 22 | return null; 23 | } 24 | ServletServerHttpRequest req = (ServletServerHttpRequest) request; 25 | //获取请求参数中携带的uid 26 | String uid = req.getServletRequest().getParameter("uid"); 27 | if(uid == null){ 28 | throw new RuntimeException("未登录"); 29 | } 30 | return new MyPrincipal(uid); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/handler/MyWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.handler; 2 | 3 | import org.springframework.stereotype.Component; 4 | import org.springframework.web.socket.CloseStatus; 5 | import org.springframework.web.socket.WebSocketHandler; 6 | import org.springframework.web.socket.WebSocketSession; 7 | import org.springframework.web.socket.handler.WebSocketHandlerDecorator; 8 | import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory; 9 | 10 | /** 11 | * 用户登录退出操作 12 | */ 13 | @Component 14 | public class MyWebSocketHandler implements WebSocketHandlerDecoratorFactory { 15 | 16 | @Override 17 | public WebSocketHandler decorate(WebSocketHandler handler) { 18 | return new WebSocketHandlerDecorator(handler) { 19 | //用户登录 20 | @Override 21 | public void afterConnectionEstablished(WebSocketSession session) throws Exception { 22 | String uid = session.getPrincipal().getName(); 23 | System.out.println(uid + "登陆"); 24 | super.afterConnectionEstablished(session); 25 | } 26 | 27 | //用户退出 28 | @Override 29 | public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { 30 | String uid = session.getPrincipal().getName(); 31 | System.out.println(uid + "退出"); 32 | 33 | super.afterConnectionClosed(session, closeStatus); 34 | } 35 | }; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/message/SendMsg.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.message; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotNull; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * 一对一发送的消息 10 | */ 11 | @Data 12 | public class SendMsg implements Serializable { 13 | //发送消息的用户id 14 | private String uid; 15 | 16 | //接收消息的用户id 17 | @NotNull(message = "未选择用户") 18 | private String toUid; 19 | 20 | //发送的文本消息 21 | @NotNull(message = "消息不能为空") 22 | private String content; 23 | } 24 | -------------------------------------------------------------------------------- /websocket/src/main/java/demo/springboot/websocket/principal/MyPrincipal.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.principal; 2 | 3 | import java.security.Principal; 4 | 5 | /** 6 | * 存储用户的信息 7 | */ 8 | public class MyPrincipal implements Principal { 9 | private String name; 10 | 11 | public MyPrincipal(String name){ 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public String getName() { 17 | return this.name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /websocket/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | root: error 4 | server: 5 | port: 8080 -------------------------------------------------------------------------------- /websocket/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 10 | 58 | 59 | 60 |

61 | 62 | 63 |
64 | 74 | 75 | -------------------------------------------------------------------------------- /websocket2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | springboot-demo 7 | demo.springboot 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | websocket2 13 | 14 | 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-websocket 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-redis 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | 31 | 32 | com.alibaba 33 | fastjson 34 | 1.2.68 35 | 36 | 37 | 38 | 39 | ${project.name} 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-maven-plugin 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/WebSocketApplication.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class WebSocketApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(WebSocketApplication.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/config/RedisMessageListenerConfig.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.config; 2 | 3 | import demo.springboot.websocket.redis.RedisReceiver; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.data.redis.connection.RedisConnectionFactory; 8 | import org.springframework.data.redis.listener.PatternTopic; 9 | import org.springframework.data.redis.listener.RedisMessageListenerContainer; 10 | import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; 11 | 12 | @Configuration 13 | public class RedisMessageListenerConfig { 14 | @Autowired 15 | private RedisReceiver redisReceiver; 16 | 17 | /** 18 | * 监听redis中的订阅信息 19 | * @param redisConnectionFactory 20 | * @return 21 | */ 22 | @Bean 23 | public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) { 24 | RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); 25 | redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory); 26 | //添加redis消息监听,监听im-topic消息主题的消息,使用messageListenerAdapter()中设置的类和方法处理消息 27 | redisMessageListenerContainer.addMessageListener(messageListenerAdapter(), new PatternTopic("im-topic")); 28 | //同上一样 29 | redisMessageListenerContainer.addMessageListener(messageAllListenerAdapter(), new PatternTopic("sys-topic")); 30 | return redisMessageListenerContainer; 31 | } 32 | 33 | /** 34 | * 添加订阅消息处理类,通过反射获取处理类中的处理方法 35 | * 即使用RedisReceiver类中的sendMsg方法处理消息 36 | * @return 37 | */ 38 | @Bean 39 | public MessageListenerAdapter messageListenerAdapter() { 40 | return new MessageListenerAdapter(redisReceiver, "sendMsg"); 41 | } 42 | 43 | @Bean 44 | public MessageListenerAdapter messageAllListenerAdapter(){ 45 | return new MessageListenerAdapter(redisReceiver, "sendAllMsg"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.config; 2 | 3 | import demo.springboot.websocket.handler.MyHandshakeHandler; 4 | import demo.springboot.websocket.handler.MyWebSocketHandler; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 8 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 9 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 10 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 11 | import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; 12 | 13 | @Configuration 14 | //开启消息代理,默认使用内置消息代理,也可以选择配置RabbitMQ等 15 | @EnableWebSocketMessageBroker 16 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 17 | @Autowired 18 | private MyWebSocketHandler myWebSocketHandler; 19 | @Autowired 20 | private MyHandshakeHandler myHandshakeHandler; 21 | 22 | @Override 23 | public void configureMessageBroker(MessageBrokerRegistry registry) { 24 | //启用/user /topic两个消息前缀,消息发送的前缀,也是前端订阅的前缀 25 | registry.enableSimpleBroker("/user", "/topic"); 26 | //当使用convertAndSendToUser发送消息时,前端订阅用/user开头。即一对一发送消息,使用/user为前缀订阅 27 | registry.setUserDestinationPrefix("/user"); 28 | //前端向服务端发送消息的前缀 29 | registry.setApplicationDestinationPrefixes("/im/"); 30 | } 31 | 32 | @Override 33 | public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) { 34 | //客户端和服务端进行连接的endpoint 35 | //如果使用移动端开发app,需要/im/conn/websocket连接 36 | stompEndpointRegistry.addEndpoint("/im/conn") 37 | .setHandshakeHandler(myHandshakeHandler)//设置连接校验 38 | .setAllowedOrigins("*")//跨域 39 | .withSockJS();//开启sockjs 40 | } 41 | 42 | @Override 43 | public void configureWebSocketTransport(WebSocketTransportRegistration registry) { 44 | //注册登陆退出 45 | registry.addDecoratorFactory(myWebSocketHandler); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/controller/ImController.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.controller; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import demo.springboot.websocket.message.SendMsg; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.redis.core.StringRedisTemplate; 7 | import org.springframework.messaging.handler.annotation.MessageMapping; 8 | import org.springframework.validation.annotation.Validated; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.security.Principal; 13 | import java.util.Set; 14 | 15 | @RestController 16 | public class ImController { 17 | @Autowired 18 | private StringRedisTemplate stringRedisTemplate; 19 | 20 | /** 21 | * 发送消息,一对一 22 | * Principal为连接websocket校验时返回的,可以直接在参数中使用 23 | * 24 | * @param msg 25 | * @param principal 26 | * @return 27 | */ 28 | @MessageMapping("/send2user") 29 | public String send2user(@Validated SendMsg msg, Principal principal) { 30 | String uid = principal.getName(); 31 | //当前发送信息的uid 32 | msg.setUid(uid); 33 | System.out.println(uid + ":" + msg); 34 | //获取在线的用户列表 35 | Set onlineUsers = stringRedisTemplate.opsForSet().members("online"); 36 | //判断发送的用户是否在线 37 | if (onlineUsers.contains(msg.getToUid())) { 38 | //如果用户在线,则将消息发送到redis im-topic主题消息中,所有连接同一个redis的应用并订阅im-topic主题都会收到这条消息。 39 | //然后都使用SimpMessagingTemplate发送消息到指定的订阅中 40 | //接收消息发送消息的类 RedisReceiver 41 | stringRedisTemplate.convertAndSend("im-topic", JSONObject.toJSONString(msg)); 42 | } else { 43 | //用户不在线,保存消息记录,用户上线后拉取,这里不做实现 44 | } 45 | return "success"; 46 | } 47 | 48 | /** 49 | * 发送消息,发送给所有订阅/topic/sys的用户 50 | * 广播消息只发送给在线的用户 51 | * @param msg 52 | * @return 53 | */ 54 | @GetMapping("/sendAll") 55 | public String sendAll(String msg){ 56 | System.out.println("广播消息:" + msg); 57 | //将消息发布到redis sys-topic主题中 58 | stringRedisTemplate.convertAndSend("sys-topic", msg); 59 | return "success"; 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/handler/MyHandshakeHandler.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.handler; 2 | 3 | import demo.springboot.websocket.principal.MyPrincipal; 4 | import org.springframework.http.server.ServerHttpRequest; 5 | import org.springframework.http.server.ServletServerHttpRequest; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.web.socket.WebSocketHandler; 8 | import org.springframework.web.socket.server.support.DefaultHandshakeHandler; 9 | 10 | import java.security.Principal; 11 | import java.util.Map; 12 | 13 | /** 14 | * 连接时校验用户信息,并返回重写的Principal 15 | */ 16 | @Component 17 | public class MyHandshakeHandler extends DefaultHandshakeHandler { 18 | 19 | @Override 20 | protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map attributes) { 21 | if (!(request instanceof ServletServerHttpRequest)) { 22 | return null; 23 | } 24 | ServletServerHttpRequest req = (ServletServerHttpRequest) request; 25 | //获取请求参数中携带的token 26 | String uid = req.getServletRequest().getParameter("uid"); 27 | if(uid == null){ 28 | throw new RuntimeException("未登录"); 29 | } 30 | return new MyPrincipal(uid); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/handler/MyWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.handler; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.redis.core.StringRedisTemplate; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.web.socket.CloseStatus; 7 | import org.springframework.web.socket.WebSocketHandler; 8 | import org.springframework.web.socket.WebSocketSession; 9 | import org.springframework.web.socket.handler.WebSocketHandlerDecorator; 10 | import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory; 11 | 12 | /** 13 | * 用户登录退出操作 14 | */ 15 | @Component 16 | public class MyWebSocketHandler implements WebSocketHandlerDecoratorFactory { 17 | @Autowired 18 | private StringRedisTemplate stringRedisTemplate; 19 | 20 | @Override 21 | public WebSocketHandler decorate(WebSocketHandler handler) { 22 | return new WebSocketHandlerDecorator(handler) { 23 | //用户登录 24 | @Override 25 | public void afterConnectionEstablished(WebSocketSession session) throws Exception { 26 | String uid = session.getPrincipal().getName(); 27 | System.out.println(uid + "登录"); 28 | //将用户存入到redis在线用户中 29 | stringRedisTemplate.opsForSet().add("online", uid); 30 | super.afterConnectionEstablished(session); 31 | } 32 | 33 | //用户退出 34 | @Override 35 | public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { 36 | String uid = session.getPrincipal().getName(); 37 | System.out.println(uid + "退出"); 38 | //将用户从redis在线用户中删除 39 | stringRedisTemplate.opsForSet().remove("online", uid); 40 | super.afterConnectionClosed(session, closeStatus); 41 | } 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/message/SendMsg.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.message; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotNull; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * 一对一发送的消息 10 | */ 11 | @Data 12 | public class SendMsg implements Serializable { 13 | //发送消息的用户id 14 | private String uid; 15 | 16 | //接收消息的用户id 17 | @NotNull(message = "未选择用户") 18 | private String toUid; 19 | 20 | //发送的文本消息 21 | @NotNull(message = "消息不能为空") 22 | private String content; 23 | } 24 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/principal/MyPrincipal.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.principal; 2 | 3 | import java.security.Principal; 4 | 5 | public class MyPrincipal implements Principal { 6 | private String name; 7 | 8 | public MyPrincipal(String name){ 9 | this.name = name; 10 | } 11 | 12 | @Override 13 | public String getName() { 14 | return this.name; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /websocket2/src/main/java/demo/springboot/websocket/redis/RedisReceiver.java: -------------------------------------------------------------------------------- 1 | package demo.springboot.websocket.redis; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import demo.springboot.websocket.message.SendMsg; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.messaging.simp.SimpMessagingTemplate; 7 | import org.springframework.stereotype.Component; 8 | 9 | /** 10 | * 处理订阅的消息 11 | */ 12 | @Component 13 | public class RedisReceiver { 14 | @Autowired 15 | private SimpMessagingTemplate simpMessagingTemplate; 16 | 17 | /** 18 | * 处理一对一消息 19 | * @param message 20 | */ 21 | public void sendMsg(String message) { 22 | SendMsg msg = JSONObject.parseObject(message, SendMsg.class); 23 | simpMessagingTemplate.convertAndSendToUser(msg.getToUid(), "msg", msg); 24 | } 25 | 26 | /** 27 | * 处理广播消息 28 | * @param message 29 | */ 30 | public void sendAllMsg(String message){ 31 | simpMessagingTemplate.convertAndSend("/topic/sys", message); 32 | } 33 | } -------------------------------------------------------------------------------- /websocket2/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | root: error 4 | spring: 5 | redis: 6 | host: 192.168.211.100 7 | port: 6379 8 | database: 1 9 | password: 10 | timeout: 5000ms 11 | server: 12 | port: 8080 -------------------------------------------------------------------------------- /websocket2/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 10 | 58 | 59 | 60 |
61 | 62 | 63 |
64 | 74 | 75 | --------------------------------------------------------------------------------