├── .gitignore ├── Chapter1-1-1 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter111Application.java │ │ └── controller │ │ └── HelloController.java │ └── resources │ └── application.yml ├── Chapter1-1-2 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter112Application.java │ │ ├── config │ │ └── UserProperties.java │ │ └── controller │ │ ├── HelloController.java │ │ └── UserController.java │ └── resources │ ├── application-dev.yml │ ├── application-pro.yml │ ├── application.yml │ └── user.properties ├── Chapter2-1-1 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter211Application.java │ │ ├── controller │ │ └── UserController.java │ │ ├── dao │ │ └── UserDao.java │ │ ├── entity │ │ └── User.java │ │ └── service │ │ ├── UserService.java │ │ └── impl │ │ └── UserServiceImpl.java │ └── resources │ └── application.yml ├── Chapter2-1-10 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter2110Application.java │ │ └── controller │ │ └── FileUploadController.java │ └── resources │ ├── application.yml │ └── templates │ └── index.html ├── Chapter2-1-11 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter2111Main.java │ │ ├── config │ │ └── RestTemplateConfig.java │ │ ├── controller │ │ ├── FileTestController.java │ │ ├── GetTestController.java │ │ └── PostTestController.java │ │ └── vo │ │ └── ResultVo.java │ └── resources │ └── application.yml ├── Chapter2-1-2 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter212Application.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ └── UserController.java │ │ └── entity │ │ └── User.java │ └── resources │ └── application.yml ├── Chapter2-1-3 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter213Application.java │ │ ├── Handler │ │ └── GlobalExceptionHandler.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ ├── BadExceptionController.java │ │ ├── BusinessController.java │ │ └── UglyExceptionController.java │ │ └── exception │ │ └── BusinessException.java │ └── resources │ └── application.yml ├── Chapter2-1-4 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter214Application.java │ │ └── controller │ │ ├── LogController.java │ │ └── off │ │ └── OffController.java │ └── resources │ └── application.yml ├── Chapter2-1-5 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter215Application.java │ │ └── controller │ │ └── LogController.java │ └── resources │ ├── application.yml │ └── config │ └── logback-spring.xml ├── Chapter2-1-6 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter216Application.java │ │ ├── aspect │ │ └── WebLogAspect.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ ├── UserController.java │ │ └── logging │ │ │ └── AopLogController.java │ │ └── entity │ │ └── User.java │ └── resources │ └── application.yml ├── Chapter2-1-7 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter217Application.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ └── UserController.java │ │ └── entity │ │ └── User.java │ └── resources │ ├── application.yml │ └── logback-spring.xml ├── Chapter2-1-8 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter218Application.java │ │ ├── annotation │ │ └── DateTime.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ └── UserController.java │ │ ├── entity │ │ └── User.java │ │ └── validator │ │ └── DateTimeValidator.java │ └── resources │ └── application.yml ├── Chapter2-1-9 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter219Application.java │ │ ├── common │ │ └── R.java │ │ ├── controller │ │ └── UserController.java │ │ └── entity │ │ └── User.java │ └── resources │ └── application.yml ├── Chapter3-1-1 ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── mkeeper │ ├── Chpater311Main.java │ ├── scheduled_executor │ └── ScheduledExecutorServiceDemo.java │ ├── spring_task │ ├── SpringTaskDemo.java │ └── config │ │ └── TaskSchedulerConfig.java │ └── timer │ └── TimerDemo.java ├── Chapter3-1-2 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter312Main.java │ │ └── quartz │ │ ├── config │ │ └── QuartzConfig.java │ │ └── task │ │ └── UploadTask.java │ └── resources │ └── application.yml ├── Chapter3-1-3 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter313Main.java │ │ ├── common │ │ └── R.java │ │ ├── config │ │ ├── ScheduleConfig.java │ │ └── SwaggerConfig.java │ │ ├── controller │ │ └── JobController.java │ │ ├── dao │ │ └── JobMapper.java │ │ ├── exception │ │ └── ServiceException.java │ │ ├── factory │ │ └── ScheduleJobFactory.java │ │ ├── job │ │ └── TestJob.java │ │ ├── listener │ │ └── ApplicationListener.java │ │ ├── model │ │ └── ScheduleJob.java │ │ ├── service │ │ └── JobService.java │ │ └── utils │ │ └── ScheduleUtil.java │ └── resources │ ├── application.yml │ ├── mapping │ └── JobMapper.xml │ └── quartz.sql ├── Chapter3-1-4 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter314Main.java │ │ ├── config │ │ └── XxlJobConfig.java │ │ └── job │ │ ├── DemoJobHandler.java │ │ └── ShardingJobHandler.java │ └── resources │ └── application.yml ├── Chapter3-1-5 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter315Main.java │ │ ├── config │ │ ├── DataflowJobConfig.java │ │ ├── JobEventConfig.java │ │ ├── RegistryCenterConfig.java │ │ └── SimpleJobConfig.java │ │ ├── fixture │ │ ├── entity │ │ │ └── Foo.java │ │ └── repository │ │ │ └── FooRepository.java │ │ └── job │ │ ├── dataflow │ │ └── SpringDataflowJob.java │ │ └── simple │ │ └── SpringSimpleJob.java │ └── resources │ └── application.yml ├── Chapter4-1-1 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter411Main.java │ │ │ ├── entity │ │ │ └── User.java │ │ │ └── service │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ └── UserServiceImpl.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── impl │ └── UserServiceImplTest.java ├── Chapter4-1-2 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter412Main.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── entity │ │ │ ├── User.java │ │ │ └── common │ │ │ │ ├── PageInfo.java │ │ │ │ └── R.java │ │ │ ├── mapper │ │ │ └── UserMapper.java │ │ │ └── service │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ └── UserServiceImpl.java │ └── resources │ │ ├── application.yml │ │ ├── generator │ │ └── generatorConfig.xml │ │ └── mapping │ │ └── UserMapper.xml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── impl │ └── UserServiceImplTest.java ├── Chapter4-1-3 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter413Main.java │ │ ├── config │ │ ├── MybatisPlusConfig.java │ │ └── WebConfig.java │ │ ├── controller │ │ └── UserController.java │ │ ├── entity │ │ ├── SuperEntity.java │ │ ├── User.java │ │ └── enums │ │ │ ├── AgeEnum.java │ │ │ └── PhoneEnum.java │ │ ├── generator │ │ └── MpGenerator.java │ │ ├── mapper │ │ ├── SuperMapper.java │ │ └── UserMapper.java │ │ └── service │ │ ├── IUserService.java │ │ └── impl │ │ └── UserServiceImpl.java │ └── resources │ ├── application.yml │ └── mapper │ └── UserMapper.xml ├── Chapter4-1-4 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter414Main.java │ │ │ ├── entity │ │ │ └── User.java │ │ │ └── repository │ │ │ └── UserRepository.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── mkeeper │ └── UserServiceImplTest.java ├── Chapter4-1-5 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter415Main.java │ │ ├── config │ │ ├── DataSourceConfig.java │ │ └── MybatisConfig.java │ │ ├── controller │ │ └── TestController.java │ │ ├── entity │ │ └── Stock.java │ │ └── mapper │ │ ├── one │ │ └── OneStockMapper.java │ │ └── two │ │ └── TwoStockMapper.java │ └── resources │ ├── application.yml │ └── mapping │ ├── one │ └── OneStockMapper.xml │ └── two │ └── TwoStockMapper.xml ├── Chapter4-1-6 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter416Main.java │ │ │ ├── entity │ │ │ ├── Order.java │ │ │ ├── OrderItem.java │ │ │ └── Stock.java │ │ │ ├── mapper │ │ │ ├── OrderItemMapper.java │ │ │ ├── OrderMapper.java │ │ │ └── StockMapper.java │ │ │ └── service │ │ │ └── DemoService.java │ └── resources │ │ ├── application.yml │ │ ├── demo_ds.sql │ │ └── mapping │ │ ├── OrderItemMapper.xml │ │ ├── OrderMapper.xml │ │ └── StockMapper.xml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── DemoServiceTest.java ├── Chapter4-1-7 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter417Main.java │ │ │ ├── entity │ │ │ ├── Order.java │ │ │ ├── OrderItem.java │ │ │ └── Stock.java │ │ │ ├── mapper │ │ │ ├── OrderItemMapper.java │ │ │ ├── OrderMapper.java │ │ │ └── StockMapper.java │ │ │ └── service │ │ │ └── DemoService.java │ └── resources │ │ ├── application.yml │ │ └── mapping │ │ ├── OrderItemMapper.xml │ │ ├── OrderMapper.xml │ │ └── StockMapper.xml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── DemoServiceTest.java ├── Chapter4-1-8 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter418Main.java │ │ │ ├── entity │ │ │ ├── Order.java │ │ │ └── OrderItem.java │ │ │ ├── mapper │ │ │ ├── OrderItemMapper.java │ │ │ └── OrderMapper.java │ │ │ └── service │ │ │ └── DemoService.java │ └── resources │ │ ├── application.yml │ │ ├── manual_schema.sql │ │ └── mapping │ │ ├── OrderItemMapper.xml │ │ └── OrderMapper.xml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── DemoServiceTest.java ├── Chapter4-1-9 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter419Main.java │ │ │ ├── entity │ │ │ └── Order.java │ │ │ ├── mapper │ │ │ └── OrderMapper.java │ │ │ └── service │ │ │ └── DemoService.java │ └── resources │ │ ├── application.yml │ │ ├── manual_schema.sql │ │ └── mapping │ │ └── OrderMapper.xml │ └── test │ └── java │ └── com │ └── mkeeper │ └── service │ └── DemoServiceTest.java ├── Chapter5-1-1 ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── Chapter511Main.java │ │ ├── controller │ │ └── TestController.java │ │ ├── entity │ │ └── Student.java │ │ └── service │ │ ├── DoingService.java │ │ ├── StudentService.java │ │ └── impl │ │ └── StudentServiceImpl.java │ └── resources │ └── application.yml ├── Chapter6-1-1 ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── mkeeper │ └── Chapter611Main.java ├── Chapter7-1-1 ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── Chapter711Main.java │ │ │ └── rocketmq │ │ │ ├── consumer │ │ │ └── RocketMQConsumer.java │ │ │ └── producer │ │ │ └── RocketMQProducer.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── mkeeper │ └── rocketmq │ └── RocketMQApplicationTests.java ├── Chapter8-1-1 ├── consumer │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── mkeeper │ │ │ │ ├── ConsumerApplication.java │ │ │ │ └── service │ │ │ │ └── ComputeService.java │ │ └── resources │ │ │ ├── application.yml │ │ │ └── dubbo.xml │ │ └── test │ │ └── java │ │ └── com │ │ └── mkeeper │ │ └── service │ │ └── ComputeServiceTest.java ├── pom.xml └── provider │ ├── pom.xml │ └── src │ └── main │ ├── java │ └── com │ │ └── mkeeper │ │ ├── ProviderApplication.java │ │ └── service │ │ ├── ComputeService.java │ │ └── impl │ │ └── ComputeServiceImpl.java │ └── resources │ ├── application.yml │ └── dubbo.xml ├── Chapter8-1-2 ├── dubbo-api │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── mkeeper │ │ └── dubbo │ │ └── api │ │ └── ComputeService.java ├── dubbo-consumer │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── DubboConsumerMain.java │ │ │ └── com │ │ │ └── mkeeper │ │ │ └── dubbo │ │ │ └── controller │ │ │ └── DubboController.java │ │ └── resources │ │ └── application.properties ├── dubbo-provider │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── mkeeper │ │ │ ├── DubboProviderMain.java │ │ │ └── dubbo │ │ │ └── service │ │ │ └── DefaultComputeService.java │ │ └── resources │ │ └── application.properties └── pom.xml └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ### 编译文件 ### 2 | target/ 3 | log 4 | logs 5 | 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .mvn 13 | .settings 14 | .springBeans 15 | .log 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | 23 | ### NetBeans ### 24 | nbproject/private/ 25 | build/ 26 | nbbuild/ 27 | dist/ 28 | nbdist/ 29 | .nb-gradle/ 30 | 31 | -------------------------------------------------------------------------------- /Chapter1-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter1-1-1 9 | 1.0-SNAPSHOT 10 | jar 11 | 12 | Chapter1-1-1 13 | Hello Spring Boot 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-parent 19 | 2.0.3.RELEASE 20 | 21 | 22 | 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-maven-plugin 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter1-1-1/src/main/java/com/mkeeper/Chapter111Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter111Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter111Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter1-1-1/src/main/java/com/mkeeper/controller/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | //@RestController 等同于 (@Controller 与 @ResponseBody) 7 | @RestController 8 | public class HelloController { 9 | 10 | // @GetMapping 等同于 (@RequestMapping(method = RequestMethod.GET)) 11 | @GetMapping("/hello") 12 | public String hello(){ 13 | return "Hello SpringBoot"; 14 | 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter1-1-1/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #server: 2 | #port: 8888 -------------------------------------------------------------------------------- /Chapter1-1-2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter1-1-2 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | ../Chapter2-1-1 13 | 14 | 15 | Chapter1-1-2 16 | Spring Boot常用配置介绍 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-parent 22 | 2.0.3.RELEASE 23 | 24 | 25 | 26 | UTF-8 27 | 1.8 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-web 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-configuration-processor 42 | true 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-maven-plugin 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/java/com/mkeeper/Chapter112Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter112Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter112Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/java/com/mkeeper/config/UserProperties.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.PropertySource; 7 | 8 | @Configuration 9 | //指定配置文件,如果不指定,默认解析“application.yml” 10 | @PropertySource("classpath:user.properties") 11 | //前缀 12 | @ConfigurationProperties(prefix = "company.user") 13 | public class UserProperties { 14 | 15 | private String name; 16 | private Integer age; 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public Integer getAge() { 27 | return age; 28 | } 29 | 30 | public void setAge(Integer age) { 31 | this.age = age; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "UserProperties {" + 37 | "name='" + name + '\'' + 38 | ", age=" + age + 39 | '}'; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/java/com/mkeeper/controller/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | //@RestController 等同于 (@Controller 与 @ResponseBody) 7 | @RestController 8 | public class HelloController { 9 | 10 | // @GetMapping 等同于 (@RequestMapping(method = RequestMethod.GET)) 11 | @GetMapping("/hello") 12 | public String hello(){ 13 | return "Hello SpringBoot"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.config.UserProperties; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | public class UserController { 12 | 13 | private static final Logger log = LoggerFactory.getLogger(UserController.class); 14 | 15 | @Autowired 16 | private UserProperties userProperties; 17 | 18 | @GetMapping("/user") 19 | public String user() { 20 | log.info("info:"); 21 | 22 | return userProperties.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | # 服务相关配置 2 | server: 3 | # 服务端口配置 4 | port: 8888 5 | # 服务根路径配置 6 | servlet: 7 | context-path: /dev 8 | 9 | # 开启debug模式 10 | debug: true 11 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/resources/application-pro.yml: -------------------------------------------------------------------------------- 1 | # 服务相关配置 2 | server: 3 | # 服务端口配置 4 | port: 8080 5 | # 服务根路径配置 6 | servlet: 7 | context-path: / 8 | 9 | # 开启debug模式 10 | debug: false 11 | 12 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | ## 多环境配置,激活哪套配置 2 | spring: 3 | profiles: 4 | active: dev 5 | 6 | 7 | -------------------------------------------------------------------------------- /Chapter1-1-2/src/main/resources/user.properties: -------------------------------------------------------------------------------- 1 | company.user.name=Mkeeper 2 | company.user.age=28 -------------------------------------------------------------------------------- /Chapter2-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | Chapter2-1-1 8 | 9 | Chapter1-1-2 10 | Spring Boot web开发 11 | 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.0.3.RELEASE 17 | 18 | 19 | 20 | UTF-8 21 | 1.8 22 | 23 | 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-configuration-processor 36 | true 37 | 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | 1.16.20 43 | provided 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/Chapter211Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter211Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter211Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.entity.User; 4 | import com.mkeeper.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.*; 7 | import java.util.List; 8 | @RequestMapping("/users") 9 | @RestController 10 | public class UserController { 11 | // 入口:处理相应URL 12 | 13 | @Autowired 14 | private UserService userService; 15 | 16 | @GetMapping("/{userId}") 17 | public User findByUserId(@PathVariable Integer userId){ 18 | // 处理“/users/{userId}”的Get请求,获取user信息 19 | // url中的id可通过@PathVariable绑定到函数的参数中 20 | return userService.findByUserId(userId); 21 | } 22 | 23 | @GetMapping("/") 24 | public List findList(){ 25 | // 处理“/users/”的Get请求,获取用户列表信息 26 | // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 27 | return userService.findList(); 28 | } 29 | 30 | @PostMapping("/") 31 | public User addUser(@RequestBody User user){ 32 | // 处理"/users/"的POST请求,用来创建User 33 | // 除了@RequestBody绑定参数之外,还可以通过@RequestParam从页面中传递参数 34 | return userService.addUser(user); 35 | } 36 | 37 | @PutMapping("/") 38 | public User updateUser(@RequestBody User user){ 39 | // 处理"/users/{id}"的PUT请求,用来更新User信息 40 | return userService.updateUser(user); 41 | } 42 | 43 | @DeleteMapping("/{userId}") 44 | public boolean deleteByUserId(@PathVariable Integer userId){ 45 | // 处理"/users/{id}"的DELETE请求,用来删除User 46 | return userService.deleteByUserId(userId); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.dao; 2 | 3 | import com.mkeeper.entity.User; 4 | import org.springframework.stereotype.Component; 5 | import java.util.*; 6 | 7 | @Component 8 | public class UserDao { 9 | // 数据层:查询数据库,这里为了简单用Map模拟 10 | 11 | private static Integer count = 0; 12 | 13 | // 线程安全的Map 14 | private static Map userMap = Collections.synchronizedMap(new HashMap<>()); 15 | 16 | static { 17 | // 静态代码块,第一次初始化类时被调用 18 | // 初始化userMap 19 | userMap.put(++count, User.builder().userId(count).name("Mkeeper").age(28).address("wuhan").build()); 20 | userMap.put(++count, User.builder().userId(count).name("Jam").age(22).address("beijing").build()); 21 | userMap.put(++count, User.builder().userId(count).name("Li").age(18).address("shanghai").build()); 22 | } 23 | 24 | public User findByUserId(Integer userId){ 25 | return userMap.get(userId); 26 | } 27 | 28 | public List findList(){ 29 | return new ArrayList<>(userMap.values()); 30 | } 31 | 32 | public User addUser(User user){ 33 | user.setUserId(++count); 34 | userMap.put(count, user); 35 | return user; 36 | } 37 | 38 | public User updateUser(User user){ 39 | userMap.put(user.getUserId(), user); 40 | return user; 41 | } 42 | 43 | public boolean deleteByUserId(Integer userId){ 44 | userMap.remove(userId); 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | @Builder 12 | public class User { 13 | private Integer userId; 14 | private String name; 15 | private Integer age; 16 | private String address; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.entity.User; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface UserService { 9 | // 服务层:处理业务逻辑 10 | 11 | User findByUserId(Integer userId); 12 | 13 | List findList(); 14 | 15 | User addUser(User user); 16 | 17 | User updateUser(User user); 18 | 19 | boolean deleteByUserId(Integer userId); 20 | } 21 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/java/com/mkeeper/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | import com.mkeeper.dao.UserDao; 4 | import com.mkeeper.entity.User; 5 | import com.mkeeper.service.UserService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | 12 | @Service 13 | public class UserServiceImpl implements UserService { 14 | 15 | @Autowired 16 | private UserDao userDao; 17 | 18 | @Override 19 | public User findByUserId(Integer userId) { 20 | return userDao.findByUserId(userId); 21 | } 22 | 23 | @Override 24 | public List findList() { 25 | return userDao.findList(); 26 | } 27 | 28 | @Override 29 | public User addUser(User user) { 30 | return userDao.addUser(user); 31 | } 32 | 33 | @Override 34 | public User updateUser(User user) { 35 | return userDao.updateUser(user); 36 | } 37 | 38 | @Override 39 | public boolean deleteByUserId(Integer userId) { 40 | return userDao.deleteByUserId(userId); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter2-1-1/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-1/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-10/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter2-1-10 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | Chapter2-1-10 14 | Spring Boot web开发 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 2.0.3.RELEASE 21 | 22 | 23 | 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | 37 | 38 | org.projectlombok 39 | lombok 40 | 1.16.20 41 | provided 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-thymeleaf 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-maven-plugin 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /Chapter2-1-10/src/main/java/com/mkeeper/Chapter2110Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter2110Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter2110Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-10/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | thymeleaf: 3 | # 禁用 thymeleaf 缓存 4 | cache: false 5 | servlet: 6 | multipart: 7 | # 是否支持批量上传 (默认值 true) 8 | enabled: true 9 | # 上传文件的临时目录 (一般情况下不用特意修改) 10 | location: 11 | # 上传文件最大为 10M (默认值 1M 根据自身业务自行控制即可) 12 | max-file-size: 10MB 13 | # 上传请求最大为 10M(默认值10M 根据自身业务自行控制即可) 14 | max-request-size: 10MB 15 | # 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改) 16 | file-size-threshold: 0 17 | # 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改) 18 | resolve-lazily: false -------------------------------------------------------------------------------- /Chapter2-1-10/src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 文件上传 7 | 8 | 9 | 10 |

单一文件上传示例

11 |
12 |
13 |

14 | 文件1: 15 | 16 |

17 |
18 |
19 | 20 |
21 |

批量文件上传示例

22 | 23 |
24 |
26 |

27 | 文件1: 28 |

29 |

30 | 文件2: 31 |

32 |

33 | 34 |

35 |
36 |
37 | 38 |
39 |

Base64文件上传

40 |
41 |
42 |

43 | BASE64编码: 44 | 45 |

46 |
47 |
48 | 49 | 50 | -------------------------------------------------------------------------------- /Chapter2-1-11/src/main/java/com/mkeeper/Chapter2111Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter2111Main { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter2111Main.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter2-1-11/src/main/java/com/mkeeper/controller/GetTestController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpEntity; 5 | import org.springframework.http.HttpHeaders; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RestController; 11 | import org.springframework.web.client.RestTemplate; 12 | 13 | import javax.annotation.Resource; 14 | import java.io.UnsupportedEncodingException; 15 | import java.net.URLEncoder; 16 | 17 | @Slf4j 18 | @RestController 19 | public class GetTestController { 20 | 21 | @Resource 22 | private RestTemplate restTemplate; 23 | 24 | //最简单的get操作 25 | @GetMapping("/baidu1/{key}") 26 | public String get1(@PathVariable String key) throws UnsupportedEncodingException { 27 | String encodeKey = URLEncoder.encode(key, "UTF-8"); 28 | 29 | String url = "http://www.baidu.com/s?bdorz_come=1&ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=" + encodeKey; 30 | 31 | return restTemplate.getForObject(url, String.class); //返回百度主站html 32 | } 33 | 34 | //需要自定义header头的get操作 35 | @GetMapping("/baidu2/{key}") 36 | public String get2(@PathVariable String key) throws UnsupportedEncodingException { 37 | HttpHeaders headers = new HttpHeaders(); 38 | 39 | headers.set("MyHeaderKey", "MyHeaderValue"); 40 | 41 | HttpEntity entity = new HttpEntity(headers); 42 | 43 | String encodeKey =URLEncoder.encode(key, "UTF-8"); 44 | 45 | String url = "http://www.baidu.com/s?bdorz_come=1&ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=" + encodeKey; 46 | 47 | ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); 48 | 49 | return response.getBody(); //返回百度主站html 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Chapter2-1-11/src/main/java/com/mkeeper/vo/ResultVo.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.vo; 2 | 3 | public class ResultVo { 4 | private Integer code; 5 | private String data; 6 | 7 | public boolean success(){ 8 | return 0 == code; 9 | } 10 | 11 | public String getData(){ 12 | return data; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Chapter2-1-11/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # yml配置的优先级高于java配置;如果yml配置和java配置同时存在,则yml配置会覆盖java配置 2 | ####restTemplate的yml配置开始#### 3 | --- 4 | spring: 5 | restTemplate: 6 | maxTotalConnect: 1000 #连接池的最大连接数,0代表不限;如果取0,需要考虑连接泄露导致系统崩溃的后果 7 | maxConnectPerRoute: 200 8 | connectTimeout: 3000 9 | readTimeout: 5000 10 | charset: UTF-8 11 | ####restTemplate的 yml配置开始#### -------------------------------------------------------------------------------- /Chapter2-1-2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter2-1-2 9 | 1.0-SNAPSHOT 10 | 11 | Chapter2-1-2 12 | Spring Boot web开发 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-parent 18 | 2.0.3.RELEASE 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-configuration-processor 38 | true 39 | 40 | 41 | 42 | org.projectlombok 43 | lombok 44 | 1.16.20 45 | provided 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-maven-plugin 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Chapter2-1-2/src/main/java/com/mkeeper/Chapter212Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter212Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter212Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter2-1-2/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-2/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.entity.User; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | @RequestMapping("/users") 8 | @RestController 9 | public class UserController { 10 | 11 | @GetMapping("/ok") 12 | public R ok(){ 13 | User user = new User(); 14 | user.setUserId(1); 15 | user.setName("Mkeeper"); 16 | user.setAge(28); 17 | 18 | return R.isOk().data(user); 19 | } 20 | 21 | @GetMapping("/fail") 22 | public R fail(){ 23 | return R.isFail(); 24 | } 25 | 26 | @GetMapping("/exception") 27 | public R exception(){ 28 | 29 | return R.isFail(new Exception("失败")); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter2-1-2/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | @Builder 12 | public class User { 13 | private Integer userId; 14 | private String name; 15 | private Integer age; 16 | private String address; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Chapter2-1-2/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-2/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/Chapter213Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter213Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter213Application.class, args); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/Handler/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.Handler; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.exception.BusinessException; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | import org.springframework.web.bind.annotation.RestControllerAdvice; 8 | 9 | // 如果要验证BadException 和 UglyException请注释@ControllerAdvice 10 | @RestControllerAdvice 11 | public class GlobalExceptionHandler { 12 | 13 | @ExceptionHandler(value = BusinessException.class) 14 | public R businessExceptionHandler(BusinessException exception) { 15 | return R.isFail(exception); 16 | } 17 | 18 | @ExceptionHandler(value = Exception.class) 19 | public R exceptionHandler(Exception exception) { 20 | return R.isFail(exception); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/controller/BadExceptionController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | /** 7 | * Created by Mkeeper on 2018/7/7. 8 | */ 9 | @RestController 10 | public class BadExceptionController { 11 | 12 | @GetMapping("/bad") 13 | public String bad(){ 14 | // todo 业务逻辑 15 | 16 | Object object = null; 17 | // 模拟空指针异常 18 | object.toString(); 19 | 20 | return "success"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/controller/BusinessController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.exception.BusinessException; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class BusinessController { 11 | 12 | @GetMapping("/business/{param}") 13 | public R business(@PathVariable String param){ 14 | 15 | if("ok".equals(param)){ 16 | return R.isOk(); 17 | } else { 18 | throw new BusinessException("business exception: param = " + param); 19 | } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/controller/UglyExceptionController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | /** 10 | * Created by Mkeeper on 2018/7/7. 11 | */ 12 | @RestController 13 | public class UglyExceptionController { 14 | 15 | @GetMapping("/ugly") 16 | public Map ugly(){ 17 | Map result = new HashMap<>(); 18 | // TODO 直接捕获所有代码块,然后在 cache 19 | 20 | try { 21 | int i = 10 / 0; 22 | result.put("code", "200"); 23 | result.put("data", "具体返回的结果集"); 24 | } catch (Exception e) { 25 | result.put("code", "500"); 26 | result.put("message", "请求错误"); 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/java/com/mkeeper/exception/BusinessException.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.exception; 2 | 3 | /** 4 | * 自定义异常 5 | */ 6 | public class BusinessException extends RuntimeException{ 7 | 8 | public BusinessException(String message) { 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter2-1-3/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-3/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-4/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter2-1-4 9 | 1.0-SNAPSHOT 10 | 11 | Chapter2-1-4 12 | Spring Boot web开发 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-parent 18 | 2.0.3.RELEASE 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | 36 | org.projectlombok 37 | lombok 38 | 1.16.20 39 | provided 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Chapter2-1-4/src/main/java/com/mkeeper/Chapter214Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter214Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter214Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-4/src/main/java/com/mkeeper/controller/LogController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @Slf4j 8 | @RestController 9 | public class LogController { 10 | 11 | //如果不想每次都写private final Logger logger = LoggerFactory.getLogger(XXX.class); 可以用注解@Slf4j 12 | //private final Logger logger = LoggerFactory.getLogger(LogController.class) 13 | 14 | @GetMapping("/log") 15 | public void log(){ 16 | log.debug(this.getClass().getSimpleName() + ": debug"); 17 | log.info(this.getClass().getSimpleName() + ": info"); 18 | log.warn(this.getClass().getSimpleName() + ": warn"); 19 | log.error(this.getClass().getSimpleName() + ": error"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter2-1-4/src/main/java/com/mkeeper/controller/off/OffController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller.off; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @Slf4j 8 | @RestController 9 | public class OffController { 10 | 11 | @GetMapping("/log/off") 12 | public void log(){ 13 | log.debug(this.getClass().getSimpleName() + ": debug"); 14 | log.info(this.getClass().getSimpleName() + ": info"); 15 | log.warn(this.getClass().getSimpleName() + ": warn"); 16 | log.error(this.getClass().getSimpleName() + ": error"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter2-1-4/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # 改配置配置只对 嵌入式容器、Spring、Hibernate生效 2 | debug: false 3 | 4 | logging: 5 | level: 6 | # org.springframework.web目录下日志级别debug 7 | org.springframework.web: debug 8 | # com.mkeeper目录下日志级别info 9 | com.mkeeper: info 10 | # com.mkeeper.controller.off目录下日志关闭 11 | com.mkeeper.controller.off: off 12 | 13 | # 颜色日志配置 14 | spring: 15 | output: 16 | ansi: 17 | enabled: detect 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter2-1-5/src/main/java/com/mkeeper/Chapter215Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter215Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter215Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-5/src/main/java/com/mkeeper/controller/LogController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @Slf4j 8 | @RestController 9 | public class LogController { 10 | 11 | @GetMapping("/log") 12 | public void log(){ 13 | log.debug(this.getClass().getSimpleName() + ": debug"); 14 | log.info(this.getClass().getSimpleName() + ": info"); 15 | log.warn(this.getClass().getSimpleName() + ": warn"); 16 | log.error(this.getClass().getSimpleName() + ": error"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter2-1-5/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # logback配置文件路径;如果配置文件放在根目录,则无需配置 2 | logging: 3 | config: classpath:config/logback-spring.xml 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/Chapter216Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter216Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter216Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/aspect/WebLogAspect.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.aspect; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.aspectj.lang.JoinPoint; 5 | import org.aspectj.lang.annotation.AfterReturning; 6 | import org.aspectj.lang.annotation.Aspect; 7 | import org.aspectj.lang.annotation.Before; 8 | import org.aspectj.lang.annotation.Pointcut; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.context.request.RequestContextHolder; 11 | import org.springframework.web.context.request.ServletRequestAttributes; 12 | 13 | import javax.servlet.http.HttpServletRequest; 14 | import java.util.Arrays; 15 | 16 | @Slf4j 17 | @Aspect 18 | @Component 19 | public class WebLogAspect { 20 | 21 | @Pointcut("execution(public * com.mkeeper.controller.logging..*.*(..))") 22 | public void webLog(){} 23 | 24 | 25 | 26 | @Before("webLog()") 27 | public void doBefore(JoinPoint joinPoint){ 28 | // 接收到请求,记录请求内容 29 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 30 | HttpServletRequest request = attributes.getRequest(); 31 | 32 | // 记录下请求内容 33 | log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); 34 | log.info("URL : " + request.getRequestURL().toString()); 35 | log.info("HTTP_METHOD : " + request.getMethod()); 36 | log.info("IP : " + request.getRemoteAddr()); 37 | log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); 38 | log.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); 39 | 40 | } 41 | 42 | @AfterReturning(returning = "ret", pointcut = "webLog()") 43 | public void doAfterReturning(Object ret){ 44 | // 处理完请求,返回内容 45 | log.info("RESPONSE : " + ret); 46 | log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.mkeeper.common.R; 5 | import com.mkeeper.entity.User; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @Slf4j 12 | @RestController 13 | public class UserController { 14 | 15 | @PostMapping("/user") 16 | public R addUser(@RequestBody User user){ 17 | log.info("user: {}", JSON.toJSONString(user)); 18 | 19 | R r = R.isOk().data(user); 20 | 21 | log.info("result: {}", JSON.toJSONString(user)); 22 | return r; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/controller/logging/AopLogController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller.logging; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.entity.User; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | 11 | @RestController 12 | @RequestMapping("/log") 13 | public class AopLogController { 14 | 15 | @PostMapping("/user") 16 | public R addUser(@RequestBody User user){ 17 | 18 | return R.isOk().data(user); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.Data; 4 | import org.hibernate.validator.constraints.Length; 5 | 6 | import javax.validation.constraints.Min; 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | public class User { 11 | 12 | @NotNull(message = "名字不能为空") 13 | @Length(min = 4, max = 10, message = "name 长度必须在 {min} - {max} 之间") 14 | private String name; 15 | 16 | @NotNull(message = "年龄不能为空") 17 | @Min(value = 18, message = "年龄不能小于18岁") 18 | private Integer age; 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter2-1-6/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-6/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-7/src/main/java/com/mkeeper/Chapter217Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter217Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter217Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-7/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-7/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.entity.User; 5 | import org.hibernate.validator.constraints.Length; 6 | import org.springframework.validation.BindingResult; 7 | import org.springframework.validation.annotation.Validated; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import javax.validation.constraints.NotBlank; 14 | 15 | @Validated 16 | @RestController 17 | public class UserController { 18 | 19 | @PostMapping("/user") 20 | public R addUser(@Validated @RequestBody User user, BindingResult br){ 21 | 22 | if(br.hasErrors()){ 23 | return R.isFail().msg(br.getFieldError().getDefaultMessage()); 24 | } else { 25 | 26 | return R.isOk().data(user); 27 | } 28 | } 29 | 30 | 31 | @GetMapping("/user") 32 | public R test2( 33 | @NotBlank(message = "name 不能为空") 34 | @Length(min = 2, max = 10, message = "name 长度必须在 {min} - {max} 之间") 35 | String name ) { 36 | 37 | return R.isOk().data(name); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Chapter2-1-7/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.Data; 4 | import org.hibernate.validator.constraints.Length; 5 | 6 | import javax.validation.constraints.Min; 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | public class User { 11 | 12 | @NotNull(message = "名字不能为空") 13 | @Length(min = 4, max = 10, message = "name 长度必须在 {min} - {max} 之间") 14 | private String name; 15 | 16 | @NotNull(message = "年龄不能为空") 17 | @Min(value = 18, message = "年龄不能小于18岁") 18 | private Integer age; 19 | 20 | 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Chapter2-1-7/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-7/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-8/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter2-1-8 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | Chapter2-1-8 14 | Spring Boot web开发 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 2.0.3.RELEASE 21 | 22 | 23 | 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.16.20 40 | provided 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/Chapter218Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter218Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter218Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/annotation/DateTime.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.annotation; 2 | 3 | 4 | import com.mkeeper.validator.DateTimeValidator; 5 | 6 | import javax.validation.Constraint; 7 | import javax.validation.Payload; 8 | import java.lang.annotation.ElementType; 9 | import java.lang.annotation.Retention; 10 | import java.lang.annotation.RetentionPolicy; 11 | import java.lang.annotation.Target; 12 | 13 | @Target({ElementType.FIELD, ElementType.PARAMETER}) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Constraint(validatedBy = DateTimeValidator.class) 16 | public @interface DateTime { 17 | 18 | String message() default "格式错误"; 19 | 20 | String format() default "yyyyMM"; 21 | 22 | Class[] groups() default {}; 23 | 24 | Class[] payload() default {}; 25 | 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.entity.User; 5 | import org.springframework.validation.BindingResult; 6 | import org.springframework.validation.annotation.Validated; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | public class UserController { 13 | 14 | @PostMapping("/user") 15 | public R addUser(@Validated @RequestBody User user, BindingResult br) { 16 | 17 | if (br.hasErrors()) { 18 | return R.isFail().msg(br.getFieldError().getDefaultMessage()); 19 | } else { 20 | 21 | return R.isOk().data(user); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import com.mkeeper.annotation.DateTime; 4 | import lombok.Data; 5 | import org.hibernate.validator.constraints.Length; 6 | 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | public class User { 11 | 12 | @NotNull(message = "名字不能为空") 13 | @Length(min = 4, max = 10, message = "name 长度必须在 {min} - {max} 之间") 14 | private String name; 15 | 16 | 17 | @NotNull(message = "生日不能为空") 18 | @DateTime(format = "yyyyMMdd", message = "格式错误,正确格式为:yyyyMMdd") 19 | private String birthday; 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/java/com/mkeeper/validator/DateTimeValidator.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.validator; 2 | 3 | import com.mkeeper.annotation.DateTime; 4 | 5 | import javax.validation.ConstraintValidator; 6 | import javax.validation.ConstraintValidatorContext; 7 | import java.text.SimpleDateFormat; 8 | 9 | public class DateTimeValidator implements ConstraintValidator { 10 | 11 | private DateTime dateTime; 12 | 13 | @Override 14 | public void initialize(DateTime dateTime) { 15 | this.dateTime = dateTime; 16 | } 17 | 18 | @Override 19 | public boolean isValid(String value, ConstraintValidatorContext context) { 20 | // 如果 value 为空则不进行格式验证,为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制,职责分离 21 | if (value == null) { 22 | return true; 23 | } 24 | 25 | String format = dateTime.format(); 26 | 27 | if (value.length() != format.length()) { 28 | return false; 29 | } 30 | 31 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); 32 | 33 | try { 34 | simpleDateFormat.parse(value); 35 | } catch (Exception e){ 36 | return false; 37 | } 38 | 39 | return true; 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter2-1-8/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-8/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter2-1-9/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter2-1-9 9 | 1.0-SNAPSHOT 10 | 11 | 12 | Chapter2-1-9 13 | Spring Boot web开发 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-parent 19 | 2.0.3.RELEASE 20 | 21 | 22 | 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.16.20 40 | provided 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-maven-plugin 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Chapter2-1-9/src/main/java/com/mkeeper/Chapter219Application.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Mkeeper 8 | */ 9 | @SpringBootApplication 10 | public class Chapter219Application { 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter219Application.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter2-1-9/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 通用响应体 9 | */ 10 | @Data 11 | public class R implements Serializable { 12 | 13 | private T data; //服务端数据 14 | private int status = 0; //状态码,0:成功,1:失败 15 | private String msg = ""; //描述信息 16 | 17 | public static R isOk() { 18 | return new R().msg("成功"); 19 | } 20 | 21 | public static R isFail() { 22 | return new R().status(1).msg("失败"); 23 | } 24 | 25 | public static R isFail(Throwable e) { 26 | return isFail().msg(e); 27 | } 28 | 29 | public R msg(Throwable e) { 30 | this.setMsg(e.toString()); 31 | return this; 32 | } 33 | 34 | public R data(T data) { 35 | this.setData(data); 36 | return this; 37 | } 38 | 39 | public R msg(String msg){ 40 | this.setMsg(msg); 41 | return this; 42 | } 43 | 44 | public R status(int status) { 45 | this.setStatus(status); 46 | return this; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter2-1-9/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.entity.User; 5 | import org.springframework.validation.BindingResult; 6 | import org.springframework.validation.annotation.Validated; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.PutMapping; 9 | import org.springframework.web.bind.annotation.RequestBody; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | public class UserController { 14 | 15 | @PostMapping("/user") 16 | public R addUser(@Validated(value = User.Default.class) @RequestBody User user, BindingResult br){ 17 | 18 | if(br.hasErrors()){ 19 | return R.isFail().msg(br.getFieldError().getDefaultMessage()); 20 | } else { 21 | 22 | return R.isOk().data(user); 23 | } 24 | } 25 | 26 | 27 | @PutMapping("/user") 28 | public R updateUser(@Validated(value = {User.Update.class, User.Default.class}) @RequestBody User user, 29 | BindingResult br) { 30 | 31 | if(br.hasErrors()){ 32 | return R.isFail().msg(br.getFieldError().getDefaultMessage()); 33 | } else { 34 | 35 | return R.isOk().data(user); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter2-1-9/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.Data; 4 | import org.hibernate.validator.constraints.Length; 5 | 6 | import javax.validation.constraints.Min; 7 | import javax.validation.constraints.NotNull; 8 | 9 | @Data 10 | public class User { 11 | 12 | public interface Default{} 13 | 14 | public interface Update{} 15 | 16 | 17 | @NotNull(message = "id不能为空" , groups = Update.class) 18 | private Long id; 19 | 20 | @NotNull(message = "名字不能为空", groups = Default.class) 21 | @Length(min = 4, max = 10, message = "name 长度必须在 {min} - {max} 之间", groups = Default.class) 22 | private String name; 23 | 24 | @NotNull(message = "年龄不能为空", groups = Default.class) 25 | @Min(value = 18, message = "年龄不能小于18岁", groups = Default.class) 26 | private Integer age; 27 | 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Chapter2-1-9/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter2-1-9/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter3-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter3-1-1 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | Chapter3-1-1 14 | Spring Boot 定时任务 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 2.0.3.RELEASE 21 | 22 | 23 | 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | 37 | 38 | org.projectlombok 39 | lombok 40 | 1.16.20 41 | provided 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-maven-plugin 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /Chapter3-1-1/src/main/java/com/mkeeper/Chpater311Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | 8 | @SpringBootApplication 9 | public class Chpater311Main { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chpater311Main.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter3-1-1/src/main/java/com/mkeeper/scheduled_executor/ScheduledExecutorServiceDemo.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.scheduled_executor; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ScheduledExecutorService; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | 9 | /** 10 | * 与Timer很类似,但它的效果更好,多线程并行处理定时任务时,Timer运行多个TimeTask时, 11 | * 只要其中有一个因任务报错没有捕获抛出的异常,其它任务便会自动终止运行,使用 ScheduledExecutorService 则可以规避这个问题 12 | * 13 | * @author Mkeeper 14 | * @create 2018/9/28 11:15 15 | */ 16 | public class ScheduledExecutorServiceDemo { 17 | 18 | public static void main(String[] args) { 19 | final ScheduledExecutorService service = Executors.newScheduledThreadPool(3); 20 | 21 | // 参数: 22 | // 1、具体执行的任务 23 | // 2、首次执行的延时时间 24 | // 3、任务执行间隔 25 | // 4、间隔时间单位 26 | service.scheduleAtFixedRate(() -> 27 | System.out.println("执行任务:" + LocalDateTime.now()), 28 | 0, 3, TimeUnit.SECONDS 29 | ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter3-1-1/src/main/java/com/mkeeper/spring_task/SpringTaskDemo.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.spring_task; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.scheduling.annotation.Async; 5 | import org.springframework.scheduling.annotation.Scheduled; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | /** 12 | * 基于 Spring 自带的 13 | */ 14 | @Component 15 | @Slf4j 16 | public class SpringTaskDemo { 17 | 18 | /** 19 | * cron: cron表达式,根据表达式循环执行,与fixedRate属性不同的是它是将时间进行了切割。 20 | * (@Scheduled(cron = "0/5 * * * * *")任务将在5、10、15、20...这种情况下进行工作) 21 | * fixedRate: 每隔多久执行一次,无视工作时间(@Scheduled(fixedRate = 1000) 假设第一次工作时间为2018-05-29 16:58:28,工作时长为3秒,那么下次任务的时候就是2018-05-29 16:58:31) 22 | * fixedDelay: 当前任务执行完毕后等待多久继续下次任务(@Scheduled(fixedDelay = 3000) 假设第一次任务工作时间为2018-05-29 16:54:33,工作时长为5秒,那么下次任务的时间就是2018-05-29 16:54:41) 23 | * initialDelay: 第一次执行延迟时间,只是做延迟的设定,与fixedDelay关系密切,配合使用,相辅相成。 24 | * 25 | */ 26 | @Async 27 | @Scheduled(cron = "0/1 * * * * *") 28 | public void scheduled1() throws InterruptedException { 29 | TimeUnit.SECONDS.sleep(3); 30 | log.info("schedule1 每1m秒执行一次: {}", LocalDateTime.now()); 31 | } 32 | 33 | @Scheduled(fixedRate = 1000) 34 | public void scheduled2() throws InterruptedException { 35 | TimeUnit.SECONDS.sleep(3); 36 | log.info("schedule2 每1m秒执行一次: {}", LocalDateTime.now()); 37 | } 38 | 39 | @Scheduled(fixedDelay = 3000) 40 | public void scheduled3() throws InterruptedException { 41 | TimeUnit.SECONDS.sleep(3); 42 | log.info("scheduled3 上次执行完毕后隔3秒继续执行:{}", LocalDateTime.now()); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Chapter3-1-1/src/main/java/com/mkeeper/spring_task/config/TaskSchedulerConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.spring_task.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.TaskScheduler; 6 | import org.springframework.scheduling.annotation.EnableAsync; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 9 | 10 | 11 | /** 12 | * 13 | * @EnableScheduling 注解表示开启对@Scheduled注解的解析;同时new ThreadPoolTaskScheduler()也是相当的关键, 14 | * 通过阅读过源码可以发现默认情况下的 private volatile int poolSize = 1; 15 | * 这就导致了多个任务的情况下容易出现竞争情况 16 | * (多个任务的情况下,如果第一个任务没执行完毕,后续的任务将会进入等待状态)。 17 | * 18 | * @EnableAsync 注解表示开启@Async注解的解析;作用就是将串行化的任务给并行化了。 19 | * (@Scheduled(cron = "0/1 * * * * *")假设第一次工作时间为2018-05-29 17:30:55, 20 | * 工作周期为3秒;如果不加@Async那么下一次工作时间就是2018-05-29 17:30:59; 21 | * 如果加了@Async 下一次工作时间就是2018-05-29 17:30:56) 22 | * 23 | */ 24 | 25 | @EnableAsync 26 | @EnableScheduling 27 | @Configuration 28 | public class TaskSchedulerConfig { 29 | 30 | /** 31 | * 很关键:默认情况下 TaskScheduler 的 poolSize = 1 32 | * 33 | * @return 线程池 34 | */ 35 | @Bean 36 | public TaskScheduler taskScheduler(){ 37 | ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); 38 | taskScheduler.setPoolSize(10); 39 | return taskScheduler; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Chapter3-1-1/src/main/java/com/mkeeper/timer/TimerDemo.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.timer; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.Timer; 5 | import java.util.TimerTask; 6 | 7 | /** 8 | * 基于 Timer 实现的定时调度,基本就是手撸代码,目前应用较少,不是很推荐 9 | * 10 | * @author Mkeeper 11 | * @create 2018/9/28 11:12 12 | */ 13 | public class TimerDemo { 14 | 15 | public static void main(String[] args) { 16 | TimerTask timerTask = new TimerTask() { 17 | @Override 18 | public void run() { 19 | System.out.println("执行任务: " + LocalDateTime.now()); 20 | } 21 | }; 22 | 23 | Timer timer = new Timer(); 24 | 25 | // timerTask:需要执行的任务 26 | // delay:延迟时间(以毫秒为单位) 27 | // period:间隔时间(以毫秒为单位) 28 | timer.schedule(timerTask, 5000, 3000); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter3-1-2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter3-1-2 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | Chapter3-1-2 14 | Spring Boot 定时任务 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 2.0.3.RELEASE 21 | 22 | 23 | 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | 37 | 38 | org.projectlombok 39 | lombok 40 | 1.16.20 41 | provided 42 | 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-quartz 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /Chapter3-1-2/src/main/java/com/mkeeper/Chapter312Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | public class Chapter312Main { 9 | public static void main(String[] args) { 10 | SpringApplication.run(Chapter312Main.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter3-1-2/src/main/java/com/mkeeper/quartz/config/QuartzConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.quartz.config; 2 | 3 | import com.mkeeper.quartz.task.UploadTask; 4 | import org.quartz.*; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | 9 | @Configuration 10 | public class QuartzConfig { 11 | 12 | //指定了具体需要执行的类,只不过具体的方法就是我们需要实现的excuteInternal 13 | @Bean 14 | public JobDetail uploadTaskDetail() { 15 | return JobBuilder.newJob(UploadTask.class) 16 | .withIdentity("uploadTask").storeDurably() 17 | .build(); 18 | } 19 | 20 | 21 | //uploadTaskTrigger指定了触发的规则 22 | @Bean 23 | public Trigger uploadTaskTrigger() { 24 | CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?"); 25 | return TriggerBuilder.newTrigger().forJob(uploadTaskDetail()) 26 | .withIdentity("uploadTask") 27 | .withSchedule(scheduleBuilder) 28 | .build(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter3-1-2/src/main/java/com/mkeeper/quartz/task/UploadTask.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.quartz.task; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.quartz.DisallowConcurrentExecution; 5 | import org.quartz.JobExecutionContext; 6 | import org.springframework.scheduling.quartz.QuartzJobBean; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | 11 | @DisallowConcurrentExecution //禁止任务并行 12 | @Slf4j 13 | public class UploadTask extends QuartzJobBean { 14 | 15 | @Override 16 | protected void executeInternal(JobExecutionContext jobExecutionContext){ 17 | try { 18 | log.info("任务开始"); 19 | TimeUnit.SECONDS.sleep(6); 20 | } catch (InterruptedException e) { 21 | log.info("任务异常"); 22 | } finally { 23 | log.info("任务结束"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter3-1-2/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter3-1-2/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/Chapter313Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.quartz.DisallowConcurrentExecution; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.scheduling.annotation.EnableScheduling; 7 | 8 | 9 | @SpringBootApplication 10 | @EnableScheduling 11 | @DisallowConcurrentExecution 12 | public class Chapter313Main { 13 | public static void main(String[] args) { 14 | SpringApplication.run(Chapter313Main.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | @Data 8 | public class R implements Serializable { 9 | 10 | private static final long serialVersionUID = -4577255781088498763L; 11 | private static final int OK = 0; 12 | private static final int FAIL = 1; 13 | private static final int UNAUTHORIZED = 2; 14 | 15 | private T data; //服务端数据 16 | private int status = OK; //状态码 17 | private String msg = ""; //描述信息 18 | 19 | //APIS 20 | public static R isOk() { 21 | return new R(); 22 | } 23 | 24 | public static R isFail() { 25 | return new R().status(FAIL); 26 | } 27 | 28 | public static R isFail(Throwable e) { 29 | return isFail().msg(e); 30 | } 31 | 32 | public R msg(Throwable e) { 33 | this.setMsg(e.toString()); 34 | return this; 35 | } 36 | 37 | public R data(T data) { 38 | this.setData(data); 39 | return this; 40 | } 41 | 42 | public R status(int status) { 43 | this.setStatus(status); 44 | return this; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/config/ScheduleConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.mkeeper.factory.ScheduleJobFactory; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.scheduling.quartz.SchedulerFactoryBean; 9 | 10 | import javax.sql.DataSource; 11 | 12 | @Configuration 13 | public class ScheduleConfig { 14 | @Autowired 15 | private ScheduleJobFactory scheduleJobFactory; 16 | 17 | @Bean 18 | @Qualifier("scheduleBean") 19 | public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("dataSource") DataSource dataSource) { 20 | SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); 21 | // 名称 22 | schedulerFactoryBean.setSchedulerName("TASK_EXECUTOR"); 23 | // 延迟10秒启动Scheduler 24 | schedulerFactoryBean.setStartupDelay(10); 25 | // 通过applicationContextSchedulerContextKey属性配置spring上下文 26 | schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContextKey"); 27 | // 设置是否任意一个已定义的Job会覆盖现有的Job。默认为false,即已定义的Job不会覆盖现有的Job。 28 | schedulerFactoryBean.setOverwriteExistingJobs(true); 29 | // 自动开始 30 | schedulerFactoryBean.setAutoStartup(true); 31 | // 数据源 32 | schedulerFactoryBean.setDataSource(dataSource); 33 | // 将JobFactory改为自定义的,否则在 Job 中注入 Bean 会失败 34 | schedulerFactoryBean.setJobFactory(scheduleJobFactory); 35 | return schedulerFactoryBean; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.spi.DocumentationType; 11 | import springfox.documentation.spring.web.plugins.Docket; 12 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 | 14 | @Configuration 15 | @EnableSwagger2 16 | public class SwaggerConfig { 17 | 18 | @Value("${swagger.enable:false}") 19 | private boolean enable; 20 | 21 | @Bean 22 | public Docket createRestApi() { 23 | return new Docket(DocumentationType.SWAGGER_2) 24 | .enable(enable) 25 | .apiInfo(apiInfo()) 26 | .select() 27 | .apis(RequestHandlerSelectors.basePackage("com.mkeeper.controller")) 28 | .paths(PathSelectors.any()) 29 | .build(); 30 | } 31 | private ApiInfo apiInfo() { 32 | return new ApiInfoBuilder() 33 | .title("Quartz定时任务单点持久化接口文档") 34 | .description("Quartz定时任务单点持久化") 35 | .version("1.0") 36 | .build(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/controller/JobController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.common.R; 4 | import com.mkeeper.exception.ServiceException; 5 | import com.mkeeper.model.ScheduleJob; 6 | import com.mkeeper.service.JobService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | @RestController 11 | @RequestMapping("/job") 12 | public class JobController { 13 | 14 | @Autowired 15 | private JobService jobService; 16 | 17 | @GetMapping 18 | public R getAllJob() { 19 | return R.isOk().data(jobService.getAllJob()); 20 | } 21 | 22 | @GetMapping("/{id}") 23 | public R getJob(@PathVariable("id") Long jobId) throws ServiceException { 24 | return R.isOk().data(jobService.select(jobId)); 25 | } 26 | 27 | @PutMapping("/update/{id}") 28 | public R updateJob(@PathVariable("id") Long jobId, @RequestBody ScheduleJob newScheduleJob) throws ServiceException { 29 | return R.isOk().data(jobService.update(jobId, newScheduleJob)); 30 | } 31 | 32 | @DeleteMapping("/delete/{id}") 33 | public R deleteJob(@PathVariable("id") Long jobId) throws ServiceException { 34 | return R.isOk().data(jobService.delete(jobId)); 35 | } 36 | 37 | @PostMapping("/add") 38 | public R saveJob(@RequestBody ScheduleJob newScheduleJob) throws ServiceException { 39 | return R.isOk().data(jobService.add(newScheduleJob)); 40 | } 41 | 42 | 43 | @GetMapping("/run/{id}") 44 | public R runJob(@PathVariable("id") Long jobId) throws ServiceException { 45 | return R.isOk().data(jobService.run(jobId)); 46 | } 47 | 48 | 49 | @GetMapping("/pause/{id}") 50 | public R pauseJob(@PathVariable("id") Long jobId) throws ServiceException { 51 | return R.isOk().data(jobService.pause(jobId)); 52 | } 53 | 54 | @GetMapping("/resume/{id}") 55 | public R resumeJob(@PathVariable("id") Long jobId) throws ServiceException { 56 | return R.isOk().data(jobService.resume(jobId)); 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/dao/JobMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.dao; 2 | 3 | import com.mkeeper.model.ScheduleJob; 4 | import org.apache.ibatis.annotations.Mapper; 5 | 6 | import java.util.List; 7 | 8 | @Mapper 9 | public interface JobMapper { 10 | ScheduleJob select(long id); 11 | 12 | Integer update(ScheduleJob scheduleJob); 13 | 14 | Integer insert(ScheduleJob scheduleJob); 15 | 16 | Integer delete(Long productId); 17 | 18 | List getAllJob(); 19 | 20 | List getAllEnableJob(); 21 | } -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/exception/ServiceException.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.exception; 2 | 3 | public class ServiceException extends Exception{ 4 | public ServiceException() { 5 | } 6 | 7 | public ServiceException(String message) { 8 | super(message); 9 | } 10 | 11 | public ServiceException(String message, Throwable cause) { 12 | super(message, cause); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/factory/ScheduleJobFactory.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.factory; 2 | 3 | import org.quartz.spi.TriggerFiredBundle; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.config.AutowireCapableBeanFactory; 6 | import org.springframework.scheduling.quartz.AdaptableJobFactory; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | public class ScheduleJobFactory extends AdaptableJobFactory { 11 | // 让不受spring管理的类具有spring自动注入的特性 12 | @Autowired 13 | private AutowireCapableBeanFactory autowireCapableBeanFactory; 14 | 15 | @Override 16 | protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { 17 | Object jobInstance = super.createJobInstance(bundle); 18 | autowireCapableBeanFactory.autowireBean(jobInstance); 19 | return jobInstance; 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/job/TestJob.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.job; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.quartz.Job; 5 | import org.quartz.JobExecutionContext; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Slf4j 9 | @Component 10 | public class TestJob implements Job { 11 | 12 | @Override 13 | public void execute(JobExecutionContext jobExecutionContext){ 14 | // Do what you want here 15 | log.info("Test job is executing at: " + System.currentTimeMillis()/1000); 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/listener/ApplicationListener.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.listener; 2 | 3 | import com.mkeeper.exception.ServiceException; 4 | import com.mkeeper.model.ScheduleJob; 5 | import com.mkeeper.service.JobService; 6 | import com.mkeeper.utils.ScheduleUtil; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.quartz.CronTrigger; 9 | import org.quartz.Scheduler; 10 | import org.springframework.boot.CommandLineRunner; 11 | import org.springframework.stereotype.Component; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.List; 15 | 16 | 17 | /** 18 | * 启动应用时运行定时任务 19 | * 20 | * @author mkeeper 21 | * @create 2018/10/19 10:05 22 | */ 23 | @Slf4j 24 | @Component 25 | public class ApplicationListener implements CommandLineRunner { 26 | 27 | @Resource 28 | private JobService jobService; 29 | 30 | @Resource 31 | private Scheduler scheduler; 32 | 33 | @Override 34 | public void run(String... args) { 35 | List scheduleJobList = jobService.getAllEnableJob(); 36 | for (ScheduleJob scheduleJob : scheduleJobList) { 37 | try { 38 | CronTrigger cronTrigger = ScheduleUtil.getCronTrigger(scheduler, scheduleJob); 39 | if (cronTrigger == null) { 40 | ScheduleUtil.createScheduleJob(scheduler, scheduleJob); 41 | } else { 42 | ScheduleUtil.updateScheduleJob(scheduler, scheduleJob); 43 | } 44 | log.info("Startup {}-{} success", scheduleJob.getJobGroup(), scheduleJob.getJobName()); 45 | } catch (ServiceException e) { 46 | log.error("Job ERROR", e); 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/java/com/mkeeper/model/ScheduleJob.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | import java.util.Date; 7 | 8 | 9 | // { 10 | // "className": "com.mkeeper.job.TestJob", 11 | // "cronExpression": "*/10 * * * * ?", 12 | // "jobName": "testJob", 13 | // "jobGroup": "TEST_GROUP", 14 | // "triggerName": "TEST_TRIGGER", 15 | // "triggerGroup": "TEST_GROUP", 16 | // "pause": true, 17 | // "enable": true, 18 | // "description": "test Job for SpringBoot", 19 | // } 20 | @Data 21 | public class ScheduleJob implements Serializable { 22 | 23 | private static final Long serialVersionUID = 1435515995276255188L; 24 | 25 | private Long id; 26 | 27 | private String className; 28 | 29 | private String cronExpression; 30 | 31 | private String jobName; 32 | 33 | private String jobGroup; 34 | 35 | private String triggerName; 36 | 37 | private String triggerGroup; 38 | 39 | private Boolean pause; 40 | 41 | private Boolean enable; 42 | 43 | private String description; 44 | 45 | private Date createTime; 46 | 47 | private Date lastUpdateTime; 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Chapter3-1-3/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #数据库连接池配置 2 | spring: 3 | datasource: 4 | name: mysql_test 5 | type: com.alibaba.druid.pool.DruidDataSource 6 | #druid相关配置 7 | druid: 8 | #监控统计拦截的filters 9 | filters: stat 10 | driver-class-name: com.mysql.jdbc.Driver 11 | #基本属性 12 | url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true 13 | username: root 14 | password: 123456 15 | #配置初始化大小/最小/最大 16 | initial-size: 1 17 | min-idle: 1 18 | max-active: 20 19 | #获取连接等待超时时间 20 | max-wait: 60000 21 | #间隔多久进行一次检测,检测需要关闭的空闲连接 22 | time-between-eviction-runs-millis: 60000 23 | #一个连接在池中最小生存的时间 24 | min-evictable-idle-time-millis: 300000 25 | validation-query: SELECT 'x' 26 | test-while-idle: true 27 | test-on-borrow: false 28 | test-on-return: false 29 | #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false 30 | pool-prepared-statements: false 31 | max-pool-prepared-statement-per-connection-size: 20 32 | #Quartz配置 33 | quartz: 34 | jdbc: 35 | initialize-schema: always 36 | job-store-type: jdbc 37 | 38 | ##Mybatis配置 39 | mybatis: 40 | #Mapper.xml所在的位置 41 | mapper-locations: classpath:mapping/*.xml 42 | #entity扫描的包名 43 | type-aliases-package: com.mkeeper.entity 44 | 45 | swagger: 46 | enable: true 47 | 48 | 49 | -------------------------------------------------------------------------------- /Chapter3-1-4/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter3-1-4 9 | 1.0-SNAPSHOT 10 | 11 | 12 | Chapter3-1-4 13 | xxl-job快速上手 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-parent 19 | 2.0.3.RELEASE 20 | 21 | 22 | 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.16.20 40 | provided 41 | 42 | 43 | 44 | 45 | com.xuxueli 46 | xxl-job-core 47 | 1.9.1 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-maven-plugin 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /Chapter3-1-4/src/main/java/com/mkeeper/Chapter314Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter314Main { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter314Main.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter3-1-4/src/main/java/com/mkeeper/config/XxlJobConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.xxl.job.core.executor.XxlJobExecutor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Slf4j 10 | @Configuration 11 | public class XxlJobConfig { 12 | 13 | @Value("${xxl.job.admin.addresses}") 14 | private String addresses; 15 | 16 | @Value("${xxl.job.executor.appName}") 17 | private String appName; 18 | 19 | @Value("${xxl.job.executor.ip}") 20 | private String ip; 21 | 22 | @Value("${xxl.job.executor.port}") 23 | private int port; 24 | 25 | @Value("${xxl.job.accessToken}") 26 | private String accessToken; 27 | 28 | @Value("${xxl.job.executor.logPath}") 29 | private String logPath; 30 | 31 | @Value("${xxl.job.executor.logRetentionDays}") 32 | private int logRetentionDays; 33 | 34 | @Bean(initMethod = "start", destroyMethod = "destroy") 35 | public XxlJobExecutor xxlJobExecutor() { 36 | log.info(">>>>>>>>>>> xxl-job config init."); 37 | XxlJobExecutor xxlJobExecutor = new XxlJobExecutor(); 38 | xxlJobExecutor.setAdminAddresses(addresses); 39 | xxlJobExecutor.setAppName(appName); 40 | xxlJobExecutor.setIp(ip); 41 | xxlJobExecutor.setPort(port); 42 | xxlJobExecutor.setAccessToken(accessToken); 43 | xxlJobExecutor.setLogPath(logPath); 44 | xxlJobExecutor.setLogRetentionDays(logRetentionDays); 45 | 46 | return xxlJobExecutor; 47 | } 48 | } -------------------------------------------------------------------------------- /Chapter3-1-4/src/main/java/com/mkeeper/job/DemoJobHandler.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.job; 2 | 3 | import com.xxl.job.core.biz.model.ReturnT; 4 | import com.xxl.job.core.handler.IJobHandler; 5 | import com.xxl.job.core.handler.annotation.JobHandler; 6 | import com.xxl.job.core.log.XxlJobLogger; 7 | import org.springframework.stereotype.Component; 8 | 9 | 10 | /** 11 | * 任务Handler示例(Bean模式) 12 | * 13 | */ 14 | @JobHandler(value="demoJobHandler") 15 | @Component 16 | public class DemoJobHandler extends IJobHandler { 17 | 18 | @Override 19 | public ReturnT execute(String param) { 20 | XxlJobLogger.log("XXL-JOB, Hello World."); 21 | 22 | return SUCCESS; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter3-1-4/src/main/java/com/mkeeper/job/ShardingJobHandler.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.job; 2 | 3 | import com.xxl.job.core.biz.model.ReturnT; 4 | import com.xxl.job.core.handler.IJobHandler; 5 | import com.xxl.job.core.handler.annotation.JobHandler; 6 | import com.xxl.job.core.log.XxlJobLogger; 7 | import com.xxl.job.core.util.ShardingUtil; 8 | import org.springframework.stereotype.Component; 9 | 10 | 11 | /** 12 | * 分片广播任务 13 | */ 14 | @JobHandler(value="shardingJobHandler") 15 | @Component 16 | public class ShardingJobHandler extends IJobHandler { 17 | 18 | @Override 19 | public ReturnT execute(String param) { 20 | 21 | // 分片参数 22 | ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo(); 23 | XxlJobLogger.log("分片参数:当前分片序号 = {0}, 总分片数 = {1}", shardingVO.getIndex(), shardingVO.getTotal()); 24 | 25 | // 业务逻辑 26 | for (int i = 0; i < shardingVO.getTotal(); i++) { 27 | if (i == shardingVO.getIndex()) { 28 | XxlJobLogger.log("第 {0} 片, 命中分片开始处理", i); 29 | } else { 30 | XxlJobLogger.log("第 {0} 片, 忽略", i); 31 | } 32 | } 33 | 34 | return SUCCESS; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter3-1-4/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | xxl: 2 | job: 3 | admin: 4 | ### xxl-job admin address list:调度中心部署跟地址:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调"。 5 | addresses: http://127.0.0.1:8080/xxl-job-admin-1.9.1 6 | executor: 7 | ### xxl-job executor address:执行器"AppName"和地址信息配置:AppName执行器心跳注册分组依据;地址信息用于"调度中心请求并触发任务"和"执行器注册"。 8 | ### 执行器默认端口为9999,执行器IP默认为空表示自动获取IP,多网卡时可手动设置指定IP,手动设置IP时将会绑定Host。单机部署多个执行器时,注意要配置不同执行器端口; 9 | appName: my-xxl-job-executor 10 | ip: 11 | port: 8889 12 | ### xxl-job log path:执行器运行日志文件存储的磁盘位置,需要对该路径拥有读写权限 13 | logPath: /data/applogs/xxl-job/jobhandler 14 | ### xxl-job log retention days:执行器Log文件定期清理功能,指定日志保存天数,日志文件过期自动删除。限制至少保持3天,否则功能不生效; 15 | logRetentionDays: -1 16 | ### xxl-job, access token:执行器通讯TOKEN,非空时启用 17 | accessToken: 18 | 19 | server: 20 | port: 8081 21 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/Chapter315Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter315Main{ 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter315Main.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/config/JobEventConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.dangdang.ddframe.job.event.JobEventConfiguration; 4 | import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | import javax.annotation.Resource; 9 | import javax.sql.DataSource; 10 | 11 | @Configuration 12 | public class JobEventConfig { 13 | 14 | @Resource 15 | private DataSource dataSource; 16 | 17 | @Bean 18 | public JobEventConfiguration jobEventConfiguration() { 19 | return new JobEventRdbConfiguration(dataSource); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/config/RegistryCenterConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration; 4 | import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | @ConditionalOnExpression("'${regCenter.serverList}'.length() > 0") 12 | public class RegistryCenterConfig { 13 | 14 | @Bean(initMethod = "init") 15 | public ZookeeperRegistryCenter regCenter(@Value("${regCenter.serverList}") final String serverList, 16 | @Value("${regCenter.namespace}") final String namespace) { 17 | return new ZookeeperRegistryCenter(new ZookeeperConfiguration(serverList, namespace)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/fixture/entity/Foo.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.fixture.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | public final class Foo implements Serializable { 6 | 7 | private static final long serialVersionUID = 2706842871078949451L; 8 | 9 | private final long id; 10 | 11 | private final String location; 12 | 13 | private Status status; 14 | 15 | public Foo(final long id, final String location, final Status status) { 16 | this.id = id; 17 | this.location = location; 18 | this.status = status; 19 | } 20 | 21 | public long getId() { 22 | return id; 23 | } 24 | 25 | public String getLocation() { 26 | return location; 27 | } 28 | 29 | public Status getStatus() { 30 | return status; 31 | } 32 | 33 | public void setStatus(final Status status) { 34 | this.status = status; 35 | } 36 | 37 | public String toString() { 38 | return String.format("id: %s, location: %s, status: %s", id, location, status); 39 | } 40 | 41 | public enum Status { 42 | TODO, 43 | COMPLETED 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/fixture/repository/FooRepository.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.fixture.repository; 2 | 3 | import com.mkeeper.fixture.entity.Foo; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | 11 | @Repository 12 | public class FooRepository { 13 | 14 | private Map data = new ConcurrentHashMap<>(300, 1); 15 | 16 | public FooRepository() { 17 | init(); 18 | } 19 | 20 | private void init() { 21 | addData(0L, 100L, "Beijing"); 22 | addData(100L, 200L, "Shanghai"); 23 | addData(200L, 300L, "Guangzhou"); 24 | } 25 | 26 | private void addData(final long idFrom, final long idTo, final String location) { 27 | for (long i = idFrom; i < idTo; i++) { 28 | data.put(i, new Foo(i, location, Foo.Status.TODO)); 29 | } 30 | } 31 | 32 | public List findTodoData(final String location, final int limit) { 33 | List result = new ArrayList<>(limit); 34 | int count = 0; 35 | for (Map.Entry each : data.entrySet()) { 36 | Foo foo = each.getValue(); 37 | if (foo.getLocation().equals(location) && foo.getStatus() == Foo.Status.TODO) { 38 | result.add(foo); 39 | count++; 40 | if (count == limit) { 41 | break; 42 | } 43 | } 44 | } 45 | return result; 46 | } 47 | 48 | public void setCompleted(final long id) { 49 | data.get(id).setStatus(Foo.Status.COMPLETED); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/job/dataflow/SpringDataflowJob.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.job.dataflow; 2 | 3 | import com.dangdang.ddframe.job.api.ShardingContext; 4 | import com.dangdang.ddframe.job.api.dataflow.DataflowJob; 5 | import com.mkeeper.fixture.entity.Foo; 6 | import com.mkeeper.fixture.repository.FooRepository; 7 | 8 | import javax.annotation.Resource; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | public class SpringDataflowJob implements DataflowJob { 14 | 15 | @Resource 16 | private FooRepository fooRepository; 17 | 18 | @Override 19 | public List fetchData(final ShardingContext shardingContext) { 20 | System.out.println(String.format("Item: %s | Time: %s | Thread: %s | %s", 21 | shardingContext.getShardingItem(), new SimpleDateFormat("HH:mm:ss").format(new Date()), Thread.currentThread().getId(), "DATAFLOW FETCH")); 22 | return fooRepository.findTodoData(shardingContext.getShardingParameter(), 10); 23 | } 24 | 25 | @Override 26 | public void processData(final ShardingContext shardingContext, final List data) { 27 | System.out.println(String.format("Item: %s | Time: %s | Thread: %s | %s", 28 | shardingContext.getShardingItem(), new SimpleDateFormat("HH:mm:ss").format(new Date()), Thread.currentThread().getId(), "DATAFLOW PROCESS")); 29 | for (Foo each : data) { 30 | fooRepository.setCompleted(each.getId()); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/java/com/mkeeper/job/simple/SpringSimpleJob.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.job.simple; 2 | 3 | import com.dangdang.ddframe.job.api.ShardingContext; 4 | import com.dangdang.ddframe.job.api.simple.SimpleJob; 5 | import com.mkeeper.fixture.entity.Foo; 6 | import com.mkeeper.fixture.repository.FooRepository; 7 | 8 | import javax.annotation.Resource; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | public class SpringSimpleJob implements SimpleJob { 14 | 15 | @Resource 16 | private FooRepository fooRepository; 17 | 18 | @Override 19 | public void execute(final ShardingContext shardingContext) { 20 | System.out.println(String.format("Item: %s | Time: %s | Thread: %s | %s", 21 | shardingContext.getShardingItem(), 22 | new SimpleDateFormat("HH:mm:ss").format(new Date()), 23 | Thread.currentThread().getId(), "SIMPLE")); 24 | List data = fooRepository.findTodoData(shardingContext.getShardingParameter(), 10); 25 | for (Foo each : data) { 26 | fooRepository.setCompleted(each.getId()); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter3-1-5/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # 数据源配置 2 | spring: 3 | datasource: 4 | url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8&verifyServerCertificate=false&useSSL=false&requireSSL=false 5 | driver-class-name: com.mysql.jdbc.Driver 6 | username: root 7 | password: 123456 8 | 9 | # zk配置 10 | regCenter: 11 | serverList: localhost:2181 12 | namespace: elastic-job-lite-springboot 13 | 14 | # 定时任务配置 15 | simpleJob: 16 | cron: 0/5 * * * * ? 17 | shardingTotalCount: 3 18 | shardingItemParameters: 0=Beijing,1=Shanghai,2=Guangzhou 19 | 20 | #dataflowJob: 21 | # cron: 0/5 * * * * ? 22 | # shardingTotalCount: 3 23 | # shardingItemParameters: 0=Beijing,1=Shanghai,2=Guangzhou 24 | 25 | -------------------------------------------------------------------------------- /Chapter4-1-1/src/main/java/com/mkeeper/Chapter411Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter411Main { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter411Main.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter4-1-1/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | 7 | /** 8 | * CREATE TABLE `t_user` ( 9 | * `user_id` INT ( 11 ) NOT NULL AUTO_INCREMENT, 10 | * `user_name` VARCHAR ( 255 ) NOT NULL, 11 | * `password` VARCHAR ( 255 ) NOT NULL, 12 | * `phone` VARCHAR ( 20 ) NOT NULL, 13 | * PRIMARY KEY ( `user_id` ) 14 | * ) ENGINE = INNODB AUTO_INCREMENT = 1018 DEFAULT CHARSET = utf8; 15 | */ 16 | @Data 17 | @Builder 18 | public class User { 19 | private Integer userId; 20 | private String userName; 21 | private String password; 22 | private String phone; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Chapter4-1-1/src/main/java/com/mkeeper/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.entity.User; 4 | 5 | public interface UserService { 6 | 7 | /** 8 | * 新增一个用户 9 | */ 10 | Integer create(User user); 11 | 12 | /** 13 | * 根据Name删除一个用户 14 | */ 15 | void deleteByName(String userName); 16 | 17 | /** 18 | * 获取用户总量 19 | */ 20 | Integer getAllUsers(); 21 | 22 | /** 23 | * 删除所有用户 24 | */ 25 | void deleteAllUsers(); 26 | 27 | /** 28 | * 先清空数据 29 | * 再新增数据 30 | * 要求再一个事物中执行 31 | */ 32 | void clearAdd(User user); 33 | } 34 | -------------------------------------------------------------------------------- /Chapter4-1-1/src/main/java/com/mkeeper/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | import com.mkeeper.entity.User; 4 | import com.mkeeper.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.jdbc.core.JdbcTemplate; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | public class UserServiceImpl implements UserService { 12 | 13 | @Autowired 14 | private JdbcTemplate jdbcTemplate; 15 | 16 | @Override 17 | public Integer create(User user) { 18 | return jdbcTemplate.update("insert into T_USER(USER_NAME, PASSWORD, PHONE) values (?, ?, ?)", 19 | user.getUserName(), user.getPassword(), user.getPhone()); 20 | } 21 | 22 | @Override 23 | public void deleteByName(String userName) { 24 | jdbcTemplate.update("delete from T_USER where USER_Name = ?", userName); 25 | } 26 | 27 | @Override 28 | public Integer getAllUsers() { 29 | return jdbcTemplate.queryForObject("select count(1) from T_USER", Integer.class); 30 | } 31 | 32 | @Override 33 | public void deleteAllUsers() { 34 | jdbcTemplate.update("delete from T_USER"); 35 | } 36 | 37 | @Transactional 38 | @Override 39 | public void clearAdd(User user) { 40 | this.deleteAllUsers(); 41 | this.create(user); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Chapter4-1-1/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:mysql://127.0.0.1:3306/springboot 4 | username: root 5 | password: 123456 6 | driver-class-name: com.mysql.jdbc.Driver 7 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/Chapter412Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.springframework.boot.Banner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | 9 | @Slf4j 10 | @SpringBootApplication 11 | @MapperScan("com.mkeeper.mapper") 12 | public class Chapter412Main { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication app = new SpringApplication(Chapter412Main.class); 16 | app.setBannerMode(Banner.Mode.OFF); 17 | app.run(args); 18 | log.info("Chapter4-1-2 is success!"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.entity.User; 4 | import com.mkeeper.entity.common.PageInfo; 5 | import com.mkeeper.entity.common.R; 6 | import com.mkeeper.service.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | 11 | @RestController 12 | @RequestMapping(value = "/user") 13 | public class UserController { 14 | 15 | @Autowired 16 | private UserService userService; 17 | 18 | @PostMapping 19 | public R addUser(@RequestBody User user){ 20 | userService.addUser(user); 21 | return R.isOk(); 22 | } 23 | 24 | @GetMapping("/all/{pageNum}/{pageSize}") 25 | public R findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){ 26 | return R.isOk().data(new PageInfo<>(userService.findByPage(pageNum, pageSize))); 27 | } 28 | 29 | @GetMapping("/{id}") 30 | public R findUserById(@PathVariable int id){ 31 | return R.isOk().data(userService.findById(id)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | 9 | /** 10 | * CREATE TABLE `t_user` ( 11 | * `user_id` int(11) NOT NULL AUTO_INCREMENT, 12 | * `user_name` varchar(255) NOT NULL, 13 | * `password` varchar(255) NOT NULL, 14 | * `phone` varchar(255) NOT NULL, 15 | * PRIMARY KEY (`user_id`) 16 | * ) ENGINE=InnoDB AUTO_INCREMENT=1088 DEFAULT CHARSET=utf8; 17 | */ 18 | 19 | 20 | @Data 21 | @Builder 22 | @NoArgsConstructor 23 | @AllArgsConstructor 24 | public class User { 25 | private Integer userId; 26 | 27 | private String userName; 28 | 29 | private String password; 30 | 31 | private String phone; 32 | } -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/entity/common/R.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity.common; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | @Data 8 | public class R implements Serializable { 9 | 10 | private static final long serialVersionUID = -4577255781088498763L; 11 | private static final int OK = 0; 12 | private static final int FAIL = 1; 13 | private static final int UNAUTHORIZED = 2; 14 | 15 | private T data; //服务端数据 16 | private int status = OK; //状态码 17 | private String msg = ""; //描述信息 18 | 19 | //APIS 20 | public static R isOk() { 21 | return new R(); 22 | } 23 | 24 | public static R isFail() { 25 | return new R().status(FAIL); 26 | } 27 | 28 | public static R isFail(Throwable e) { 29 | return isFail().msg(e); 30 | } 31 | 32 | public R msg(Throwable e) { 33 | this.setMsg(e.toString()); 34 | return this; 35 | } 36 | 37 | public R data(T data) { 38 | this.setData(data); 39 | return this; 40 | } 41 | 42 | public R status(int status) { 43 | this.setStatus(status); 44 | return this; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.mkeeper.entity.User; 5 | 6 | import java.util.List; 7 | 8 | public interface UserMapper { 9 | int deleteByPrimaryKey(Integer userId); 10 | 11 | int insert(User record); 12 | 13 | int insertSelective(User record); 14 | 15 | User selectByPrimaryKey(Integer userId); 16 | 17 | int updateByPrimaryKeySelective(User record); 18 | 19 | int updateByPrimaryKey(User record); 20 | 21 | List selectAllUser(); 22 | 23 | /** 24 | * 分页查询数据 25 | * @return 26 | */ 27 | Page findByPage(); 28 | 29 | /** 30 | * 批量插入 31 | * @param list 32 | * @return 33 | */ 34 | int insertList(List list); 35 | } -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.mkeeper.entity.User; 5 | 6 | import java.util.List; 7 | 8 | public interface UserService { 9 | 10 | int addUser(User user); 11 | 12 | Page findByPage(int pageNum, int pageSize); 13 | 14 | List findAll(); 15 | 16 | User findById(int id); 17 | 18 | int insertList(List list); 19 | } 20 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/java/com/mkeeper/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.github.pagehelper.PageHelper; 5 | import com.mkeeper.entity.User; 6 | import com.mkeeper.mapper.UserMapper; 7 | import com.mkeeper.service.UserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | @Service(value = "userService") 14 | public class UserServiceImpl implements UserService { 15 | 16 | @Autowired 17 | private UserMapper userMapper;//这里会报错,但是并不会影响 18 | 19 | @Override 20 | public int addUser(User user) { 21 | 22 | return userMapper.insertSelective(user); 23 | } 24 | 25 | /* 26 | * 这个方法中用到了我们开头配置依赖的分页插件pagehelper 27 | * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可; 28 | * pageNum 开始页数 29 | * pageSize 每页显示的数据条数 30 | * */ 31 | @Override 32 | public Page findByPage(int pageNum, int pageSize) { 33 | //将参数传给这个方法就可以实现物理分页了,非常简单。 34 | //只要这里设置,就物理分页,返回对应分页数据 35 | PageHelper.startPage(pageNum, pageSize); 36 | return userMapper.findByPage(); 37 | } 38 | 39 | @Override 40 | public List findAll() { 41 | return userMapper.selectAllUser(); 42 | } 43 | 44 | 45 | @Override 46 | public User findById(int id) { 47 | return userMapper.selectByPrimaryKey(id); 48 | } 49 | 50 | @Override 51 | public int insertList(List list) { 52 | return userMapper.insertList(list); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | name: mysql_test 4 | type: com.alibaba.druid.pool.DruidDataSource 5 | #druid相关配置 6 | druid: 7 | #监控统计拦截的filters 8 | filters: stat 9 | driver-class-name: com.mysql.jdbc.Driver 10 | #基本属性 11 | url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true 12 | username: root 13 | password: 123456 14 | #配置初始化大小/最小/最大 15 | initial-size: 1 16 | min-idle: 1 17 | max-active: 20 18 | #获取连接等待超时时间 19 | max-wait: 60000 20 | #间隔多久进行一次检测,检测需要关闭的空闲连接 21 | time-between-eviction-runs-millis: 60000 22 | #一个连接在池中最小生存的时间 23 | min-evictable-idle-time-millis: 300000 24 | validation-query: SELECT 'x' 25 | test-while-idle: true 26 | test-on-borrow: false 27 | test-on-return: false 28 | #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false 29 | pool-prepared-statements: false 30 | max-pool-prepared-statement-per-connection-size: 20 31 | 32 | 33 | mybatis: 34 | #Mapper.xml所在的位置 35 | mapper-locations: classpath:mapping/*.xml 36 | #entity扫描的包名 37 | type-aliases-package: com.mkeeper.entity 38 | 39 | #pagehelper分页插件配置 40 | pagehelper: 41 | helperDialect: mysql 42 | reasonable: true 43 | supportMethodsArguments: true 44 | params: count=countSql 45 | returnPageInfo: check 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Chapter4-1-2/src/test/java/com/mkeeper/service/impl/UserServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | import static org.junit.Assert.*; 8 | 9 | @RunWith(SpringRunner.class) 10 | @SpringBootTest 11 | public class UserServiceImplTest { 12 | 13 | 14 | @org.junit.Test 15 | public void addUser() { 16 | } 17 | 18 | @org.junit.Test 19 | public void findByPage() { 20 | } 21 | 22 | @org.junit.Test 23 | public void findAll() { 24 | } 25 | 26 | @org.junit.Test 27 | public void findById() { 28 | } 29 | 30 | @org.junit.Test 31 | public void insertList() { 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 4 | import com.fasterxml.jackson.annotation.JsonInclude; 5 | import com.fasterxml.jackson.databind.MapperFeature; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import com.fasterxml.jackson.databind.module.SimpleModule; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.http.converter.HttpMessageConverter; 10 | import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; 11 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 14 | 15 | import java.util.List; 16 | 17 | @ControllerAdvice 18 | @Configuration 19 | public class WebConfig extends WebMvcConfigurerAdapter { 20 | 21 | @Override 22 | public void configureMessageConverters(List> converters) { 23 | Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); 24 | builder.serializationInclusion(JsonInclude.Include.NON_NULL); 25 | ObjectMapper objectMapper = builder.build(); 26 | SimpleModule simpleModule = new SimpleModule(); 27 | simpleModule.addSerializer(Long.class, ToStringSerializer.instance); 28 | objectMapper.registerModule(simpleModule); 29 | objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// 忽略 transient 修饰的属性 30 | converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); 31 | super.configureMessageConverters(converters); 32 | } 33 | } -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/entity/SuperEntity.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import com.baomidou.mybatisplus.activerecord.Model; 4 | import com.baomidou.mybatisplus.annotations.TableId; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * 演示实体父类 10 | */ 11 | public class SuperEntity extends Model { 12 | /** 13 | * 主键ID , 这里故意演示注解可以无 14 | */ 15 | @TableId("test_id") 16 | private Long id; 17 | private Long tenantId; 18 | 19 | public Long getId() { 20 | return this.id; 21 | } 22 | 23 | public void setId(Long id) { 24 | this.id = id; 25 | } 26 | 27 | public Long getTenantId() { 28 | return tenantId; 29 | } 30 | 31 | public void setTenantId(Long tenantId) { 32 | this.tenantId = tenantId; 33 | } 34 | 35 | @Override 36 | protected Serializable pkVal() { 37 | return this.id; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/entity/enums/AgeEnum.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity.enums; 2 | 3 | import com.baomidou.mybatisplus.enums.IEnum; 4 | import com.fasterxml.jackson.annotation.JsonValue; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * 测试枚举 10 | */ 11 | public enum AgeEnum implements IEnum { 12 | ONE(1, "一岁"), 13 | TWO(2, "二岁"); 14 | 15 | private int value; 16 | private String desc; 17 | 18 | AgeEnum(final int value, final String desc) { 19 | this.value = value; 20 | this.desc = desc; 21 | } 22 | 23 | @Override 24 | public Serializable getValue() { 25 | return this.value; 26 | } 27 | 28 | @JsonValue 29 | public String getDesc(){ 30 | return this.desc; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/entity/enums/PhoneEnum.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity.enums; 2 | 3 | import com.baomidou.mybatisplus.enums.IEnum; 4 | import com.fasterxml.jackson.annotation.JsonValue; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * 运营商联系电话枚举 10 | */ 11 | public enum PhoneEnum implements IEnum { 12 | CMCC("10086", "中国移动"), 13 | CUCC("10010", "中国联通"), 14 | CT("10000", "中国电信"); 15 | 16 | private String value; 17 | private String desc; 18 | 19 | PhoneEnum(final String value, final String desc) { 20 | this.value = value; 21 | this.desc = desc; 22 | } 23 | 24 | @Override 25 | public Serializable getValue() { 26 | return this.value; 27 | } 28 | 29 | @JsonValue 30 | public String getDesc(){ 31 | return this.desc; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/mapper/SuperMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper; 2 | 3 | import com.baomidou.mybatisplus.mapper.BaseMapper; 4 | 5 | /** 6 | * 演示 mapper 父类,注意这个类不要让 mp 扫描到!! 7 | */ 8 | public interface SuperMapper extends BaseMapper { 9 | 10 | // 这里可以放一些公共的方法 11 | } 12 | -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper; 2 | 3 | import com.baomidou.mybatisplus.annotations.SqlParser; 4 | import com.mkeeper.entity.User; 5 | import org.apache.ibatis.annotations.Select; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * User 表数据库控制层接口 11 | */ 12 | public interface UserMapper extends SuperMapper { 13 | 14 | /** 15 | * 自定义注入方法 16 | */ 17 | int deleteAll(); 18 | 19 | /** 20 | * 注解 @SqlParser(filter = true) 过滤多租户解析 21 | */ 22 | @SqlParser(filter = true) 23 | @Select("select test_id as id, name, age, test_type from user") 24 | List selectListBySQL(); 25 | 26 | } -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/service/IUserService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.baomidou.mybatisplus.service.IService; 4 | import com.mkeeper.entity.User; 5 | 6 | import java.util.List; 7 | 8 | public interface IUserService extends IService { 9 | 10 | boolean deleteAll(); 11 | 12 | List selectListBySQL(); 13 | } -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/java/com/mkeeper/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | import com.baomidou.mybatisplus.service.impl.ServiceImpl; 4 | import com.mkeeper.entity.User; 5 | import com.mkeeper.mapper.UserMapper; 6 | import com.mkeeper.service.IUserService; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | @Service 12 | public class UserServiceImpl extends ServiceImpl implements IUserService { 13 | 14 | @Override 15 | public boolean deleteAll() { 16 | return retBool(baseMapper.deleteAll()); 17 | } 18 | 19 | @Override 20 | public List selectListBySQL() { 21 | return baseMapper.selectListBySQL(); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Chapter4-1-3/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | test_id AS testId, name, age, test_type AS testType, role, phone 8 | 9 | 10 | 11 | DELETE FROM USER 12 | 13 | -------------------------------------------------------------------------------- /Chapter4-1-4/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter4-1-4 9 | 1.0-SNAPSHOT 10 | 11 | Chapter4-1-3 12 | Spring Boot 数据库开发 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-parent 18 | 2.0.3.RELEASE 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | 34 | org.projectlombok 35 | lombok 36 | 1.16.20 37 | provided 38 | 39 | 40 | 41 | 42 | mysql 43 | mysql-connector-java 44 | runtime 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-data-jpa 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Chapter4-1-4/src/main/java/com/mkeeper/Chapter414Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | public class Chapter414Main { 9 | public static void main(String[] args) { 10 | SpringApplication.run(Chapter414Main.class); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter4-1-4/src/main/java/com/mkeeper/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.persistence.*; 9 | 10 | @Entity(name = "t_user") 11 | @Data 12 | @Builder 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | public class User { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Integer userId; 20 | @Column(nullable = false) 21 | private String userName; 22 | @Column(nullable = false) 23 | private String password; 24 | @Column(nullable = false) 25 | private String phone; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter4-1-4/src/main/java/com/mkeeper/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.repository; 2 | 3 | import com.mkeeper.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | 8 | public interface UserRepository extends JpaRepository { 9 | 10 | User findByUserName(String userName); 11 | 12 | User findByUserNameAndPhone(String name, String phone); 13 | 14 | @Query("from t_user u where u.userName=:name") 15 | User findUser(@Param("name") String name); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Chapter4-1-4/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:mysql://127.0.0.1:3306/springboot 4 | username: root 5 | password: 123456 6 | driver-class-name: com.mysql.jdbc.Driver 7 | jpa: 8 | hibernate: 9 | ddl-auto: validate 10 | show-sql: true -------------------------------------------------------------------------------- /Chapter4-1-4/src/test/java/com/mkeeper/UserServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import com.mkeeper.entity.User; 4 | import com.mkeeper.repository.UserRepository; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | import org.springframework.transaction.annotation.Transactional; 12 | 13 | import javax.annotation.Resource; 14 | 15 | @SpringBootTest 16 | @RunWith(SpringRunner.class) 17 | public class UserServiceImplTest { 18 | 19 | @Resource 20 | private UserRepository userRepository; 21 | 22 | 23 | @Before 24 | public void setUp() { 25 | // 准备,清空user表 26 | userRepository.deleteAll(); 27 | } 28 | 29 | @Transactional 30 | @Test 31 | public void test() { 32 | // 插入5个用户 33 | userRepository.save(User.builder().userName("a").password("123").phone("110").build()); 34 | userRepository.save(User.builder().userName("b").password("1234").phone("119").build()); 35 | userRepository.save(User.builder().userName("c").password("12345").phone("120").build()); 36 | userRepository.save(User.builder().userName("d").password("123456").phone("122").build()); 37 | userRepository.save(User.builder().userName("e").password("1234567").phone("135").build()); 38 | 39 | // 查数据库,应该有5个用户 40 | Assert.assertEquals(5, userRepository.findAll().size()); 41 | 42 | // 测试findByUserName 43 | Assert.assertEquals("110", userRepository.findByUserName("a").getPhone()); 44 | 45 | // 测试findByUserNameAndPhone 46 | Assert.assertEquals("1234", userRepository.findByUserNameAndPhone("b", "119").getPassword()); 47 | 48 | 49 | // 删除两个用户 50 | userRepository.delete(userRepository.findUser("a")); 51 | userRepository.delete(userRepository.findUser("b")); 52 | 53 | // 查数据库,应该有5个用户 54 | Assert.assertEquals(3, userRepository.findAll().size()); 55 | } 56 | 57 | 58 | 59 | } -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/Chapter415Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Chapter415Main { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Chapter415Main.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/config/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.config; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.annotation.Primary; 8 | 9 | import javax.sql.DataSource; 10 | 11 | 12 | @Configuration 13 | public class DataSourceConfig { 14 | 15 | @Value("${datasource1.url}") 16 | private String db1Url; 17 | @Value("${datasource1.username}") 18 | private String db1UserName; 19 | @Value("${datasource1.password}") 20 | private String db1Password; 21 | @Value("${datasource1.driver-class-name}") 22 | private String db1DriverClass; 23 | 24 | @Value("${datasource2.url}") 25 | private String db2Url; 26 | @Value("${datasource2.username}") 27 | private String db2UserName; 28 | @Value("${datasource2.password}") 29 | private String db2Password; 30 | @Value("${datasource2.driver-class-name}") 31 | private String db2DriverClass; 32 | 33 | 34 | @Bean(name = "dbOneDataSource") 35 | @Primary 36 | public DataSource dbOneDataSource() { 37 | return this.bulidDataSource(db1DriverClass, db1Url, db1UserName, db1Password); 38 | } 39 | 40 | 41 | 42 | 43 | @Bean(name = "dbTwoDataSource") 44 | //@ConfigurationProperties(prefix = "datasource2") 45 | public DataSource dbTwoDataSource() { 46 | return this.bulidDataSource(db2DriverClass, db2Url, db2UserName, db2Password); 47 | //return DataSourceBuilder.create().build(); 48 | } 49 | 50 | private DataSource bulidDataSource(String driverClass, String url, String username, String password) { 51 | DruidDataSource dataSource = new DruidDataSource(); 52 | dataSource.setDriverClassName(driverClass); 53 | dataSource.setUrl(url); 54 | dataSource.setUsername(username); 55 | dataSource.setPassword(password); 56 | return dataSource; 57 | } 58 | } -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.entity.Stock; 4 | import com.mkeeper.mapper.one.OneStockMapper; 5 | import com.mkeeper.mapper.two.TwoStockMapper; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | @RestController 14 | public class TestController { 15 | 16 | @Resource 17 | private OneStockMapper oneStockMapper; 18 | @Resource 19 | private TwoStockMapper twoStockMapper; 20 | 21 | 22 | @GetMapping("/find") 23 | public Map index(){ 24 | Map result = new HashMap<>(); 25 | Stock entity = oneStockMapper.selectByPrimaryKey(1); 26 | Stock twoEntity = twoStockMapper.selectByPrimaryKey(2); 27 | 28 | result.put("entity",entity); 29 | result.put("twoEntity",twoEntity); 30 | 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/entity/Stock.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | public class Stock { 4 | private Integer id; 5 | 6 | private String name; 7 | 8 | public Integer getId() { 9 | return id; 10 | } 11 | 12 | public void setId(Integer id) { 13 | this.id = id; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name == null ? null : name.trim(); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/mapper/one/OneStockMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper.one; 2 | 3 | import com.mkeeper.entity.Stock; 4 | import org.apache.ibatis.annotations.Mapper; 5 | 6 | @Mapper 7 | public interface OneStockMapper { 8 | int deleteByPrimaryKey(Integer id); 9 | 10 | int insert(Stock record); 11 | 12 | int insertSelective(Stock record); 13 | 14 | Stock selectByPrimaryKey(Integer id); 15 | 16 | int updateByPrimaryKeySelective(Stock record); 17 | 18 | int updateByPrimaryKey(Stock record); 19 | } -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/java/com/mkeeper/mapper/two/TwoStockMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper.two; 2 | 3 | import com.mkeeper.entity.Stock; 4 | import org.apache.ibatis.annotations.Mapper; 5 | 6 | @Mapper 7 | public interface TwoStockMapper { 8 | int deleteByPrimaryKey(Integer id); 9 | 10 | int insert(Stock record); 11 | 12 | int insertSelective(Stock record); 13 | 14 | Stock selectByPrimaryKey(Integer id); 15 | 16 | int updateByPrimaryKeySelective(Stock record); 17 | 18 | int updateByPrimaryKey(Stock record); 19 | } -------------------------------------------------------------------------------- /Chapter4-1-5/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | datasource1: 2 | url: jdbc:mysql://localhost:3306/demo_ds_0?useUnicode=true&characterEncoding=utf-8 3 | username: root 4 | password: 123456 5 | driver-class-name: com.mysql.jdbc.Driver 6 | 7 | datasource2: 8 | url: jdbc:mysql://localhost:3306/demo_ds_1?useUnicode=true&characterEncoding=utf-8 9 | username: root 10 | password: 123456 11 | driver-class-name: com.mysql.jdbc.Driver -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/Chapter416Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @MapperScan(basePackages = "com.mkeeper.mapper") 8 | @SpringBootApplication 9 | public class Chapter416Main { 10 | public static void main(String[] args) { 11 | SpringApplication.run(Chapter416Main.class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/entity/Order.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class Order { 5 | 6 | private long orderId; 7 | 8 | private int userId; 9 | 10 | private String status; 11 | 12 | public long getOrderId() { 13 | return orderId; 14 | } 15 | 16 | public void setOrderId(final long orderId) { 17 | this.orderId = orderId; 18 | } 19 | 20 | public int getUserId() { 21 | return userId; 22 | } 23 | 24 | public void setUserId(final int userId) { 25 | this.userId = userId; 26 | } 27 | 28 | public String getStatus() { 29 | return status; 30 | } 31 | 32 | public void setStatus(final String status) { 33 | this.status = status; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("order_id: %s, user_id: %s, status: %s", orderId, userId, status); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/entity/OrderItem.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class OrderItem { 5 | 6 | private long orderItemId; 7 | 8 | private long orderId; 9 | 10 | private int userId; 11 | 12 | private String status; 13 | 14 | public long getOrderItemId() { 15 | return orderItemId; 16 | } 17 | 18 | public void setOrderItemId(final long orderItemId) { 19 | this.orderItemId = orderItemId; 20 | } 21 | 22 | public long getOrderId() { 23 | return orderId; 24 | } 25 | 26 | public void setOrderId(final long orderId) { 27 | this.orderId = orderId; 28 | } 29 | 30 | public int getUserId() { 31 | return userId; 32 | } 33 | 34 | public void setUserId(final int userId) { 35 | this.userId = userId; 36 | } 37 | 38 | public String getStatus() { 39 | return status; 40 | } 41 | 42 | public void setStatus(final String status) { 43 | this.status = status; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return String.format("item_id:%s, order_id: %s, user_id: %s, status: %s", orderItemId, orderId, userId, status); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/entity/Stock.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Stock implements Serializable { 6 | private Integer id; 7 | 8 | private String name; 9 | 10 | private static final long serialVersionUID = 1L; 11 | 12 | public Integer getId() { 13 | return id; 14 | } 15 | 16 | public void setId(Integer id) { 17 | this.id = id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | @Override 29 | public boolean equals(Object that) { 30 | if (this == that) { 31 | return true; 32 | } 33 | if (that == null) { 34 | return false; 35 | } 36 | if (getClass() != that.getClass()) { 37 | return false; 38 | } 39 | Stock other = (Stock) that; 40 | return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) 41 | && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())); 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | final int prime = 31; 47 | int result = 1; 48 | result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); 49 | result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); 50 | return result; 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | StringBuilder sb = new StringBuilder(); 56 | sb.append(getClass().getSimpleName()); 57 | sb.append(" ["); 58 | sb.append("Hash = ").append(hashCode()); 59 | sb.append(", id=").append(id); 60 | sb.append(", name=").append(name); 61 | sb.append(", serialVersionUID=").append(serialVersionUID); 62 | sb.append("]"); 63 | return sb.toString(); 64 | } 65 | } -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/mapper/OrderItemMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.OrderItem; 6 | 7 | import java.util.List; 8 | 9 | 10 | public interface OrderItemMapper { 11 | 12 | void createIfNotExistsTable(); 13 | 14 | void truncateTable(); 15 | 16 | Long insert(OrderItem model); 17 | 18 | void delete(Long orderItemId); 19 | 20 | List selectAll(); 21 | 22 | void dropTable(); 23 | } 24 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/mapper/OrderMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.Order; 6 | 7 | public interface OrderMapper { 8 | 9 | void createIfNotExistsTable(); 10 | 11 | void truncateTable(); 12 | 13 | Long insert(Order model); 14 | 15 | void delete(Long orderId); 16 | 17 | void dropTable(); 18 | } 19 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/mapper/StockMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper; 2 | 3 | import com.mkeeper.entity.Stock; 4 | 5 | public interface StockMapper { 6 | int deleteByPrimaryKey(Integer id); 7 | 8 | int insert(Stock record); 9 | 10 | int insertSelective(Stock record); 11 | 12 | Stock selectByPrimaryKey(Integer id); 13 | 14 | int updateByPrimaryKeySelective(Stock record); 15 | 16 | int updateByPrimaryKey(Stock record); 17 | } -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/java/com/mkeeper/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.entity.Order; 4 | import com.mkeeper.entity.OrderItem; 5 | import com.mkeeper.entity.Stock; 6 | import com.mkeeper.mapper.OrderItemMapper; 7 | import com.mkeeper.mapper.OrderMapper; 8 | import com.mkeeper.mapper.StockMapper; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.annotation.Resource; 12 | 13 | @Service 14 | public class DemoService { 15 | 16 | @Resource 17 | private OrderMapper orderMapper; 18 | 19 | @Resource 20 | private StockMapper stockMapper; 21 | 22 | @Resource 23 | private OrderItemMapper orderItemMapper; 24 | 25 | public void demo() { 26 | for (int i = 1; i <= 10; i++) { 27 | 28 | Stock stock = new Stock(); 29 | stock.setId(i); 30 | stock.setName("name " + i); 31 | stockMapper.insert(stock); 32 | 33 | Order order = new Order(); 34 | order.setUserId(51 + i); 35 | order.setStatus("INSERT_TEST"); 36 | orderMapper.insert(order); 37 | long orderId = order.getOrderId(); 38 | 39 | OrderItem item = new OrderItem(); 40 | item.setOrderId(orderId); 41 | item.setUserId(51 + i); 42 | orderItemMapper.insert(item); 43 | } 44 | System.out.println(orderItemMapper.selectAll()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8002 3 | tomcat: 4 | max-threads: 500 5 | min-spare-threads: 50 6 | 7 | sharding: 8 | jdbc: 9 | datasource: 10 | names: ds 11 | ds: 12 | type: com.alibaba.druid.pool.DruidDataSource 13 | url: jdbc:mysql://localhost:3306/demo_ds 14 | username: root 15 | password: 123456 16 | driver-class-name: com.mysql.jdbc.Driver 17 | validationQuery: SELECT 1 FROM DUAL 18 | filters: stat,wall,log4j 19 | 20 | config: 21 | sharding: 22 | tables: 23 | t_order: 24 | actual-data-nodes: ds.t_order_${0..1} 25 | key-generator-column-name: order_id 26 | table-strategy: 27 | inline: 28 | sharding-column: user_id 29 | algorithm-expression: t_order_${user_id % 2} 30 | t_order_item: 31 | actual-data-nodes: ds.t_order_item_${0..2} 32 | key-generator-column-name: order_item_id 33 | table-strategy: 34 | inline: 35 | sharding-column: user_id 36 | algorithm-expression: t_order_item_${user_id % 3} 37 | props: 38 | sql.show: true 39 | 40 | mybatis: 41 | mapperLocations: classpath:mapping/**/*.xml -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/resources/mapping/OrderItemMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT AUTO_INCREMENT, order_id BIGINT, user_id INT NOT NULL, PRIMARY KEY (order_item_id)); 12 | 13 | 14 | 15 | TRUNCATE TABLE t_order_item; 16 | 17 | 18 | 19 | DROP TABLE IF EXISTS t_order_item; 20 | 21 | 22 | 23 | INSERT INTO t_order_item ( 24 | order_id, user_id 25 | ) 26 | VALUES ( 27 | #{orderId,jdbcType=INTEGER}, 28 | #{userId,jdbcType=INTEGER} 29 | ) 30 | 31 | 32 | 33 | DELETE FROM t_order_item WHERE order_id = #{orderId,jdbcType=INTEGER} 34 | 35 | 36 | 44 | 45 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/main/resources/mapping/OrderMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id)); 6 | 7 | 8 | 9 | TRUNCATE TABLE t_order; 10 | 11 | 12 | 13 | DROP TABLE IF EXISTS t_order; 14 | 15 | 16 | 17 | INSERT INTO t_order ( 18 | user_id, status 19 | ) 20 | VALUES ( 21 | #{userId,jdbcType=INTEGER}, 22 | #{status,jdbcType=VARCHAR} 23 | ) 24 | 25 | 26 | 27 | DELETE FROM t_order WHERE order_id = #{orderId,jdbcType=INTEGER} 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter4-1-6/src/test/java/com/mkeeper/service/DemoServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | import javax.annotation.Resource; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | @SpringBootTest 13 | @RunWith(SpringRunner.class) 14 | public class DemoServiceTest { 15 | 16 | @Resource 17 | private DemoService demoService; 18 | 19 | @Test 20 | public void demo() { 21 | demoService.demo(); 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/Chapter417Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @MapperScan(basePackages = "com.mkeeper.mapper") 8 | @SpringBootApplication 9 | public class Chapter417Main { 10 | public static void main(String[] args) { 11 | SpringApplication.run(Chapter417Main.class,args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/entity/Order.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class Order { 5 | 6 | private long orderId; 7 | 8 | private int userId; 9 | 10 | private String status; 11 | 12 | public long getOrderId() { 13 | return orderId; 14 | } 15 | 16 | public void setOrderId(final long orderId) { 17 | this.orderId = orderId; 18 | } 19 | 20 | public int getUserId() { 21 | return userId; 22 | } 23 | 24 | public void setUserId(final int userId) { 25 | this.userId = userId; 26 | } 27 | 28 | public String getStatus() { 29 | return status; 30 | } 31 | 32 | public void setStatus(final String status) { 33 | this.status = status; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("order_id: %s, user_id: %s, status: %s", orderId, userId, status); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/entity/OrderItem.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class OrderItem { 5 | 6 | private long orderItemId; 7 | 8 | private long orderId; 9 | 10 | private int userId; 11 | 12 | private String status; 13 | 14 | public long getOrderItemId() { 15 | return orderItemId; 16 | } 17 | 18 | public void setOrderItemId(final long orderItemId) { 19 | this.orderItemId = orderItemId; 20 | } 21 | 22 | public long getOrderId() { 23 | return orderId; 24 | } 25 | 26 | public void setOrderId(final long orderId) { 27 | this.orderId = orderId; 28 | } 29 | 30 | public int getUserId() { 31 | return userId; 32 | } 33 | 34 | public void setUserId(final int userId) { 35 | this.userId = userId; 36 | } 37 | 38 | public String getStatus() { 39 | return status; 40 | } 41 | 42 | public void setStatus(final String status) { 43 | this.status = status; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return String.format("item_id:%s, order_id: %s, user_id: %s, status: %s", orderItemId, orderId, userId, status); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/entity/Stock.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * stock 7 | * @author 8 | */ 9 | public class Stock implements Serializable { 10 | private Integer id; 11 | 12 | private String name; 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | public Integer getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Integer id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object that) { 34 | if (this == that) { 35 | return true; 36 | } 37 | if (that == null) { 38 | return false; 39 | } 40 | if (getClass() != that.getClass()) { 41 | return false; 42 | } 43 | Stock other = (Stock) that; 44 | return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) 45 | && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())); 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | final int prime = 31; 51 | int result = 1; 52 | result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); 53 | result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); 54 | return result; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | StringBuilder sb = new StringBuilder(); 60 | sb.append(getClass().getSimpleName()); 61 | sb.append(" ["); 62 | sb.append("Hash = ").append(hashCode()); 63 | sb.append(", id=").append(id); 64 | sb.append(", name=").append(name); 65 | sb.append(", serialVersionUID=").append(serialVersionUID); 66 | sb.append("]"); 67 | return sb.toString(); 68 | } 69 | } -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/mapper/OrderItemMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.OrderItem; 6 | 7 | import java.util.List; 8 | 9 | 10 | public interface OrderItemMapper { 11 | 12 | void createIfNotExistsTable(); 13 | 14 | void truncateTable(); 15 | 16 | Long insert(OrderItem model); 17 | 18 | void delete(Long orderItemId); 19 | 20 | List selectAll(); 21 | 22 | void dropTable(); 23 | } 24 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/mapper/OrderMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.Order; 6 | 7 | public interface OrderMapper { 8 | 9 | void createIfNotExistsTable(); 10 | 11 | void truncateTable(); 12 | 13 | Long insert(Order model); 14 | 15 | void delete(Long orderId); 16 | 17 | void dropTable(); 18 | } 19 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/mapper/StockMapper.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.mapper; 2 | 3 | import com.mkeeper.entity.Stock; 4 | 5 | public interface StockMapper { 6 | int deleteByPrimaryKey(Integer id); 7 | 8 | int insert(Stock record); 9 | 10 | int insertSelective(Stock record); 11 | 12 | Stock selectByPrimaryKey(Integer id); 13 | 14 | int updateByPrimaryKeySelective(Stock record); 15 | 16 | int updateByPrimaryKey(Stock record); 17 | } -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/java/com/mkeeper/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.entity.Order; 4 | import com.mkeeper.entity.OrderItem; 5 | import com.mkeeper.entity.Stock; 6 | import com.mkeeper.mapper.OrderItemMapper; 7 | import com.mkeeper.mapper.OrderMapper; 8 | import com.mkeeper.mapper.StockMapper; 9 | import org.springframework.stereotype.Service; 10 | 11 | import javax.annotation.Resource; 12 | 13 | @Service 14 | public class DemoService { 15 | 16 | @Resource 17 | private OrderMapper orderMapper; 18 | 19 | @Resource 20 | private OrderItemMapper orderItemMapper; 21 | 22 | @Resource 23 | private StockMapper stockMapper; 24 | 25 | public void demo() { 26 | for (int i = 1; i <= 10; i++) { 27 | 28 | Stock stock = new Stock(); 29 | stock.setId(i); 30 | stock.setName("name " + i); 31 | stockMapper.insert(stock); 32 | 33 | Order order = new Order(); 34 | order.setUserId(51 + i); 35 | order.setStatus("INSERT_TEST"); 36 | orderMapper.insert(order); 37 | long orderId = order.getOrderId(); 38 | 39 | OrderItem item = new OrderItem(); 40 | item.setOrderId(orderId); 41 | item.setUserId(51 + i); 42 | orderItemMapper.insert(item); 43 | } 44 | System.out.println(orderItemMapper.selectAll()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8002 3 | tomcat: 4 | max-threads: 500 5 | min-spare-threads: 50 6 | 7 | sharding: 8 | jdbc: 9 | datasource: 10 | names: ds_0,ds_1 11 | ds_0: 12 | type: com.alibaba.druid.pool.DruidDataSource 13 | url: jdbc:mysql://localhost:3306/demo_ds_0 14 | username: root 15 | password: 123456 16 | driver-class-name: com.mysql.jdbc.Driver 17 | validationQuery: SELECT 1 FROM DUAL 18 | filters: stat,wall,log4j 19 | ds_1: 20 | type: com.alibaba.druid.pool.DruidDataSource 21 | url: jdbc:mysql://localhost:3306/demo_ds_1 22 | username: root 23 | password: 123456 24 | driver-class-name: com.mysql.jdbc.Driver 25 | validationQuery: SELECT 1 FROM DUAL 26 | filters: stat,wall,log4j 27 | config: 28 | sharding: 29 | defaultDataSourceName: ds_0 30 | default-database-strategy: 31 | inline: 32 | sharding-column: user_id 33 | algorithm-expression: ds_${user_id % 2} 34 | tables: 35 | t_order: 36 | actual-data-nodes: ds_${0..1}.t_order 37 | key-generator-column-name: order_id 38 | t_order_item: 39 | actual-data-nodes: ds_${0..1}.t_order_item 40 | key-generator-column-name: order_item_id 41 | 42 | 43 | props: 44 | sql.show: true 45 | 46 | mybatis: 47 | mapperLocations: classpath:mapping/**/*.xml -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/resources/mapping/OrderItemMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT AUTO_INCREMENT, order_id BIGINT, user_id INT NOT NULL, PRIMARY KEY (order_item_id)); 12 | 13 | 14 | 15 | TRUNCATE TABLE t_order_item; 16 | 17 | 18 | 19 | DROP TABLE IF EXISTS t_order_item; 20 | 21 | 22 | 23 | INSERT INTO t_order_item ( 24 | order_id, user_id 25 | ) 26 | VALUES ( 27 | #{orderId,jdbcType=INTEGER}, 28 | #{userId,jdbcType=INTEGER} 29 | ) 30 | 31 | 32 | 33 | DELETE FROM t_order_item WHERE order_id = #{orderId,jdbcType=INTEGER} 34 | 35 | 36 | 44 | 45 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/main/resources/mapping/OrderMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id)); 6 | 7 | 8 | 9 | TRUNCATE TABLE t_order; 10 | 11 | 12 | 13 | DROP TABLE IF EXISTS t_order; 14 | 15 | 16 | 17 | INSERT INTO t_order ( 18 | user_id, status 19 | ) 20 | VALUES ( 21 | #{userId,jdbcType=INTEGER}, 22 | #{status,jdbcType=VARCHAR} 23 | ) 24 | 25 | 26 | 27 | DELETE FROM t_order WHERE order_id = #{orderId,jdbcType=INTEGER} 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter4-1-7/src/test/java/com/mkeeper/service/DemoServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | import javax.annotation.Resource; 9 | 10 | @SpringBootTest 11 | @RunWith(SpringRunner.class) 12 | public class DemoServiceTest { 13 | 14 | @Resource 15 | private DemoService demoService; 16 | 17 | @Test 18 | public void demo() { 19 | demoService.demo(); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/Chapter418Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @MapperScan(basePackages = "com.mkeeper.mapper") 8 | @SpringBootApplication 9 | public class Chapter418Main { 10 | public static void main(final String[] args) { 11 | SpringApplication.run(Chapter418Main.class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/entity/Order.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class Order { 5 | 6 | private long orderId; 7 | 8 | private int userId; 9 | 10 | private String status; 11 | 12 | public long getOrderId() { 13 | return orderId; 14 | } 15 | 16 | public void setOrderId(final long orderId) { 17 | this.orderId = orderId; 18 | } 19 | 20 | public int getUserId() { 21 | return userId; 22 | } 23 | 24 | public void setUserId(final int userId) { 25 | this.userId = userId; 26 | } 27 | 28 | public String getStatus() { 29 | return status; 30 | } 31 | 32 | public void setStatus(final String status) { 33 | this.status = status; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("order_id: %s, user_id: %s, status: %s", orderId, userId, status); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/entity/OrderItem.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class OrderItem { 5 | 6 | private long orderItemId; 7 | 8 | private long orderId; 9 | 10 | private int userId; 11 | 12 | private String status; 13 | 14 | public long getOrderItemId() { 15 | return orderItemId; 16 | } 17 | 18 | public void setOrderItemId(final long orderItemId) { 19 | this.orderItemId = orderItemId; 20 | } 21 | 22 | public long getOrderId() { 23 | return orderId; 24 | } 25 | 26 | public void setOrderId(final long orderId) { 27 | this.orderId = orderId; 28 | } 29 | 30 | public int getUserId() { 31 | return userId; 32 | } 33 | 34 | public void setUserId(final int userId) { 35 | this.userId = userId; 36 | } 37 | 38 | public String getStatus() { 39 | return status; 40 | } 41 | 42 | public void setStatus(final String status) { 43 | this.status = status; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return String.format("item_id:%s, order_id: %s, user_id: %s, status: %s", orderItemId, orderId, userId, status); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/mapper/OrderItemMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.OrderItem; 6 | 7 | import java.util.List; 8 | 9 | 10 | public interface OrderItemMapper { 11 | 12 | void createIfNotExistsTable(); 13 | 14 | void truncateTable(); 15 | 16 | Long insert(OrderItem model); 17 | 18 | void delete(Long orderItemId); 19 | 20 | List selectAll(); 21 | 22 | void dropTable(); 23 | } 24 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/mapper/OrderMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.Order; 6 | import org.apache.ibatis.annotations.Mapper; 7 | 8 | public interface OrderMapper { 9 | 10 | void createIfNotExistsTable(); 11 | 12 | void truncateTable(); 13 | 14 | Long insert(Order model); 15 | 16 | void delete(Long orderId); 17 | 18 | void dropTable(); 19 | } 20 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/java/com/mkeeper/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.entity.Order; 4 | import com.mkeeper.entity.OrderItem; 5 | import com.mkeeper.mapper.OrderItemMapper; 6 | import com.mkeeper.mapper.OrderMapper; 7 | import org.springframework.stereotype.Service; 8 | 9 | import javax.annotation.Resource; 10 | 11 | @Service 12 | public class DemoService { 13 | @Resource 14 | private OrderMapper orderMapper; 15 | 16 | @Resource 17 | private OrderItemMapper orderItemMapper; 18 | 19 | public void demo() { 20 | for (int i = 1; i <= 10; i++) { 21 | Order order = new Order(); 22 | order.setUserId(1); 23 | order.setOrderId(51 + i); 24 | order.setStatus("INSERT_TEST"); 25 | orderMapper.insert(order); 26 | long orderId = order.getOrderId(); 27 | 28 | OrderItem item = new OrderItem(); 29 | item.setOrderItemId(51 + i); 30 | item.setOrderId(orderId); 31 | item.setUserId(1); 32 | orderItemMapper.insert(item); 33 | } 34 | 35 | for (int i = 1; i <= 10; i++) { 36 | Order order = new Order(); 37 | order.setUserId(2); 38 | order.setOrderId(100 + i); 39 | order.setStatus("INSERT_TEST"); 40 | orderMapper.insert(order); 41 | long orderId = order.getOrderId(); 42 | 43 | OrderItem item = new OrderItem(); 44 | item.setOrderItemId(100 + i); 45 | item.setOrderId(orderId); 46 | item.setUserId(2); 47 | orderItemMapper.insert(item); 48 | } 49 | 50 | System.out.println(orderItemMapper.selectAll().size()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8002 3 | tomcat: 4 | max-threads: 500 5 | min-spare-threads: 50 6 | 7 | sharding: 8 | jdbc: 9 | datasource: 10 | names: ds_0,ds_1 11 | ds_0: 12 | type: com.alibaba.druid.pool.DruidDataSource 13 | url: jdbc:mysql://localhost:3306/demo_ds_0 14 | username: root 15 | password: 123456 16 | driver-class-name: com.mysql.jdbc.Driver 17 | validationQuery: SELECT 1 FROM DUAL 18 | filters: stat,wall,log4j 19 | ds_1: 20 | type: com.alibaba.druid.pool.DruidDataSource 21 | url: jdbc:mysql://localhost:3306/demo_ds_1 22 | username: root 23 | password: 123456 24 | driver-class-name: com.mysql.jdbc.Driver 25 | validationQuery: SELECT 1 FROM DUAL 26 | filters: stat,wall,log4j 27 | config: 28 | sharding: 29 | default-database-strategy: 30 | inline: 31 | sharding-column: user_id 32 | algorithm-expression: ds_${user_id % 2} 33 | tables: 34 | t_order: 35 | actual-data-nodes: ds_${0..1}.t_order_${0..1} 36 | key-generator-column-name: order_id 37 | table-strategy: 38 | inline: 39 | sharding-column: order_id 40 | algorithm-expression: t_order_${order_id % 2} 41 | t_order_item: 42 | actual-data-nodes: ds_${0..1}.t_order_item_${0..1} 43 | key-generator-column-name: order_item_id 44 | table-strategy: 45 | inline: 46 | sharding-column: order_item_id 47 | algorithm-expression: t_order_item_${order_item_id % 2} 48 | props: 49 | sql.show: true 50 | 51 | mybatis: 52 | mapperLocations: classpath:mapping/**/*.xml -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/resources/mapping/OrderItemMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT AUTO_INCREMENT, order_id BIGINT, user_id INT NOT NULL, PRIMARY KEY (order_item_id)); 12 | 13 | 14 | 15 | TRUNCATE TABLE t_order_item; 16 | 17 | 18 | 19 | DROP TABLE IF EXISTS t_order_item; 20 | 21 | 22 | 23 | INSERT INTO t_order_item ( 24 | order_item_id,order_id, user_id 25 | ) 26 | VALUES ( 27 | #{orderItemId,jdbcType=INTEGER}, 28 | #{orderId,jdbcType=INTEGER}, 29 | #{userId,jdbcType=INTEGER} 30 | ) 31 | 32 | 33 | 34 | DELETE FROM t_order_item WHERE order_id = #{orderId,jdbcType=INTEGER} 35 | 36 | 37 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/main/resources/mapping/OrderMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id)); 6 | 7 | 8 | 9 | TRUNCATE TABLE t_order; 10 | 11 | 12 | 13 | DROP TABLE IF EXISTS t_order; 14 | 15 | 16 | 17 | INSERT INTO t_order ( 18 | order_id, user_id, status 19 | ) 20 | VALUES ( 21 | #{orderId,jdbcType=INTEGER}, 22 | #{userId,jdbcType=INTEGER}, 23 | #{status,jdbcType=VARCHAR} 24 | ) 25 | 26 | 27 | 28 | DELETE FROM t_order WHERE order_id = #{orderId,jdbcType=INTEGER} 29 | 30 | 31 | -------------------------------------------------------------------------------- /Chapter4-1-8/src/test/java/com/mkeeper/service/DemoServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | import javax.annotation.Resource; 9 | 10 | @SpringBootTest 11 | @RunWith(SpringRunner.class) 12 | public class DemoServiceTest { 13 | 14 | @Resource 15 | private DemoService demoService; 16 | 17 | @Test 18 | public void test(){ 19 | demoService.demo(); 20 | } 21 | 22 | 23 | } -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/java/com/mkeeper/Chapter419Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @MapperScan(basePackages = "com.mkeeper.mapper") 8 | @SpringBootApplication 9 | public class Chapter419Main { 10 | public static void main(final String[] args) { 11 | SpringApplication.run(Chapter419Main.class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/java/com/mkeeper/entity/Order.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mkeeper.entity; 3 | 4 | public final class Order { 5 | 6 | private long orderId; 7 | 8 | private int userId; 9 | 10 | private String status; 11 | 12 | public long getOrderId() { 13 | return orderId; 14 | } 15 | 16 | public void setOrderId(final long orderId) { 17 | this.orderId = orderId; 18 | } 19 | 20 | public int getUserId() { 21 | return userId; 22 | } 23 | 24 | public void setUserId(final int userId) { 25 | this.userId = userId; 26 | } 27 | 28 | public String getStatus() { 29 | return status; 30 | } 31 | 32 | public void setStatus(final String status) { 33 | this.status = status; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return String.format("order_id: %s, user_id: %s, status: %s", orderId, userId, status); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/java/com/mkeeper/mapper/OrderMapper.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.mkeeper.mapper; 4 | 5 | import com.mkeeper.entity.Order; 6 | 7 | public interface OrderMapper { 8 | 9 | void createIfNotExistsTable(); 10 | 11 | void truncateTable(); 12 | 13 | Integer insert(Order model); 14 | 15 | Order findById(Integer orderId); 16 | 17 | void delete(Integer orderId); 18 | 19 | void dropTable(); 20 | } 21 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/java/com/mkeeper/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import com.mkeeper.mapper.OrderMapper; 4 | import org.springframework.stereotype.Service; 5 | 6 | import javax.annotation.Resource; 7 | 8 | @Service 9 | public class DemoService { 10 | @Resource 11 | private OrderMapper orderMapper; 12 | 13 | public void demo() { 14 | /*for (int i = 1; i <= 10; i++) { 15 | Order order = new Order(); 16 | order.setUserId(1); 17 | order.setOrderId(51 + i); 18 | order.setStatus("INSERT_TEST"); 19 | orderMapper.insert(order); 20 | }*/ 21 | 22 | System.out.println(orderMapper.findById(52)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8002 3 | tomcat: 4 | max-threads: 500 5 | min-spare-threads: 50 6 | 7 | sharding: 8 | jdbc: 9 | datasource: 10 | names: ds_master,ds_slave_0,ds_slave_1 11 | ds_master: 12 | type: com.alibaba.druid.pool.DruidDataSource 13 | url: jdbc:mysql://localhost:3306/demo_ds_master 14 | username: root 15 | password: 123456 16 | driver-class-name: com.mysql.jdbc.Driver 17 | validationQuery: SELECT 1 FROM DUAL 18 | filters: stat,wall,log4j 19 | ds_slave_0: 20 | type: com.alibaba.druid.pool.DruidDataSource 21 | url: jdbc:mysql://localhost:3306/demo_ds_slave_0 22 | username: root 23 | password: 123456 24 | driver-class-name: com.mysql.jdbc.Driver 25 | validationQuery: SELECT 1 FROM DUAL 26 | filters: stat,wall,log4j 27 | ds_slave_1: 28 | type: com.alibaba.druid.pool.DruidDataSource 29 | url: jdbc:mysql://localhost:3306/demo_ds_slave_1 30 | username: root 31 | password: 123456 32 | driver-class-name: com.mysql.jdbc.Driver 33 | validationQuery: SELECT 1 FROM DUAL 34 | filters: stat,wall,log4j 35 | 36 | config: 37 | masterslave: 38 | load-balance-algorithm-type: round_robin 39 | name: ds_ms 40 | master-data-source-name: ds_master 41 | slave-data-source-names: ds_slave_0,ds_slave_1 42 | 43 | props: 44 | sql.show: true 45 | 46 | mybatis: 47 | mapperLocations: classpath:mapping/**/*.xml 48 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/main/resources/mapping/OrderMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id)); 6 | 7 | 8 | 9 | TRUNCATE TABLE t_order; 10 | 11 | 12 | 13 | DROP TABLE IF EXISTS t_order; 14 | 15 | 16 | 17 | INSERT INTO t_order ( 18 | order_id, user_id, status 19 | ) 20 | VALUES ( 21 | #{orderId,jdbcType=INTEGER}, 22 | #{userId,jdbcType=INTEGER}, 23 | #{status,jdbcType=VARCHAR} 24 | ) 25 | 26 | 27 | 30 | 31 | 32 | DELETE FROM t_order WHERE order_id = #{orderId,jdbcType=INTEGER} 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chapter4-1-9/src/test/java/com/mkeeper/service/DemoServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | import javax.annotation.Resource; 9 | 10 | @SpringBootTest 11 | @RunWith(SpringRunner.class) 12 | public class DemoServiceTest { 13 | 14 | @Resource 15 | private DemoService demoService; 16 | 17 | @Test 18 | public void test(){ 19 | demoService.demo(); 20 | } 21 | 22 | 23 | } -------------------------------------------------------------------------------- /Chapter5-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter5-1-1 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | Chapter5-1-1 14 | Spring Boot 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 2.0.3.RELEASE 21 | 22 | 23 | 24 | UTF-8 25 | 1.8 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.16.20 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-cache 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/Chapter511Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | 7 | @EnableCaching 8 | @SpringBootApplication 9 | public class Chapter511Main { 10 | public static void main(String[] args){ 11 | SpringApplication.run(Chapter511Main.class, args); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.controller; 2 | 3 | import com.mkeeper.service.DoingService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | @RequestMapping 12 | public class TestController { 13 | @Autowired 14 | private DoingService doingService; 15 | 16 | @GetMapping("/doing/{a}/{b}") 17 | public Integer doing(@PathVariable Integer a, @PathVariable Integer b){ 18 | return doingService.add(a, b); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/entity/Student.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Student { 7 | 8 | private Integer id; 9 | 10 | private String name; 11 | 12 | private Integer age; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/service/DoingService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.cache.annotation.CacheConfig; 5 | import org.springframework.cache.annotation.Cacheable; 6 | import org.springframework.stereotype.Service; 7 | 8 | 9 | 10 | @CacheConfig(cacheNames = "myCache") 11 | @Service 12 | @Slf4j 13 | public class DoingService { 14 | 15 | @Cacheable(key = "targetClass + methodName + #a + #b") 16 | public Integer add(Integer a , Integer b){ 17 | log.info("开始计算"); 18 | return a + b; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/service/StudentService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | public interface StudentService { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/java/com/mkeeper/service/impl/StudentServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | public class StudentServiceImpl { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter5-1-1/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mkeeper6/SpringBoot-About/0db4cfce7598c1bfee8066f7cc668064c032262e/Chapter5-1-1/src/main/resources/application.yml -------------------------------------------------------------------------------- /Chapter6-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter6-1-1 9 | 1.0-SNAPSHOT 10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter6-1-1/src/main/java/com/mkeeper/Chapter611Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | public class Chapter611Main { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Chapter7-1-1/src/main/java/com/mkeeper/Chapter711Main.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @Slf4j 8 | @SpringBootApplication 9 | public class Chapter711Main { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(Chapter711Main.class, args); 13 | /*SpringApplication app = new SpringApplication(Chapter711Main.class); 14 | app.setBannerMode(Banner.Mode.OFF); 15 | app.run(args); 16 | log.info("Chapter7-1-1 is success!");*/ 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter7-1-1/src/main/java/com/mkeeper/rocketmq/producer/RocketMQProducer.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.rocketmq.producer; 2 | 3 | 4 | import org.apache.rocketmq.client.exception.MQClientException; 5 | import org.apache.rocketmq.client.producer.DefaultMQProducer; 6 | import org.apache.rocketmq.client.producer.SendResult; 7 | import org.apache.rocketmq.common.message.Message; 8 | import org.apache.rocketmq.remoting.common.RemotingHelper; 9 | 10 | public class RocketMQProducer{ 11 | 12 | public static void main(String[] args) throws MQClientException, InterruptedException { 13 | 14 | DefaultMQProducer producer = new DefaultMQProducer("example_group_name"); 15 | 16 | producer.setNamesrvAddr("192.168.162.129:9876"); 17 | 18 | producer.start(); 19 | 20 | for (int i = 0; i < 1000; i++) { 21 | try { 22 | /* 23 | * 注意:手动创建topic(sh bin/mqadmin updateTopic -n localhost:9876 -c DefaultCluster -t TopicTest) 24 | * Create a message instance, specifying topic, tag and message body. 25 | */ 26 | Message msg = new Message("TopicTest" /* Topic */, 27 | "TagA" /* Tag */, 28 | ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */ 29 | ); 30 | 31 | /* 32 | * Call send message to deliver message to one of brokers. 33 | */ 34 | SendResult sendResult = producer.send(msg); 35 | 36 | System.out.printf("%s%n", sendResult); 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | Thread.sleep(1000); 40 | } 41 | } 42 | 43 | producer.shutdown(); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Chapter7-1-1/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | apache: 2 | rocketmq: 3 | #消费者的组名 4 | consumer: 5 | PushConsumer: PushConsumer 6 | # 生产者的组名 7 | producer: 8 | producerGroup: Producer 9 | # NameServer地址 10 | namesrvAddr: 192.168.162.129:9876 11 | debug: true 12 | logging: 13 | level: debug 14 | -------------------------------------------------------------------------------- /Chapter7-1-1/src/test/java/com/mkeeper/rocketmq/RocketMQApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.rocketmq; 2 | 3 | public class RocketMQApplicationTests { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter8-1-1/consumer/src/main/java/com/mkeeper/ConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ImportResource; 6 | 7 | @SpringBootApplication 8 | @ImportResource({"classpath:dubbo.xml"}) 9 | public class ConsumerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ConsumerApplication.class, args); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /Chapter8-1-1/consumer/src/main/java/com/mkeeper/service/ComputeService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | public interface ComputeService { 4 | 5 | Integer add(int a, int b); 6 | 7 | } -------------------------------------------------------------------------------- /Chapter8-1-1/consumer/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #ZooKeeper 2 | dubbo: 3 | registry: 4 | address: localhost:2181 5 | 6 | logging: 7 | level: debug 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Chapter8-1-1/consumer/src/main/resources/dubbo.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter8-1-1/consumer/src/test/java/com/mkeeper/service/ComputeServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | import org.junit.Assert; 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.SpringJUnit4ClassRunner; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class ComputeServiceTest { 16 | 17 | @Autowired 18 | ComputeService computeService; 19 | 20 | @Test 21 | public void add() { 22 | Assert.assertEquals(new Integer(3), computeService.add(1, 2)); 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter8-1-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter8-1-1 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | Chapter8-1-1 13 | Spring Boot Dubbo 14 | 15 | 16 | consumer 17 | provider 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter8-1-1/provider/src/main/java/com/mkeeper/ProviderApplication.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.apache.log4j.Logger; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.ImportResource; 9 | 10 | import java.util.concurrent.CountDownLatch; 11 | 12 | @SpringBootApplication 13 | @ImportResource("classpath:dubbo.xml") 14 | public class ProviderApplication { 15 | 16 | private static final Logger logger = Logger.getLogger(ProviderApplication.class); 17 | 18 | 19 | @Bean 20 | public CountDownLatch closeLatch(){ 21 | return new CountDownLatch(1); 22 | } 23 | 24 | 25 | public static void main(String[] args) throws InterruptedException { 26 | ApplicationContext context = SpringApplication.run(ProviderApplication.class, args); 27 | 28 | logger.info("项目启动"); 29 | 30 | CountDownLatch closeLatch = context.getBean(CountDownLatch.class); 31 | 32 | closeLatch.await(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter8-1-1/provider/src/main/java/com/mkeeper/service/ComputeService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service; 2 | 3 | public interface ComputeService { 4 | 5 | Integer add(int a, int b); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Chapter8-1-1/provider/src/main/java/com/mkeeper/service/impl/ComputeServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.service.impl; 2 | 3 | import com.mkeeper.service.ComputeService; 4 | 5 | public class ComputeServiceImpl implements ComputeService { 6 | 7 | @Override 8 | public Integer add(int a, int b) { 9 | return a + b; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter8-1-1/provider/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #ZooKeeper 2 | dubbo: 3 | registry: 4 | address: localhost:2181 5 | 6 | logging: 7 | level: debug 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter8-1-1/provider/src/main/resources/dubbo.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | com.mkeeper 6 | 1.0.0 7 | jar 8 | 4.0.0 9 | 10 | dubbo-api 11 | 12 | 13 | 14 | UTF-8 15 | 1.8 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-api/src/main/java/com/mkeeper/dubbo/api/ComputeService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.dubbo.api; 2 | 3 | public interface ComputeService { 4 | 5 | Integer add(int a, int b); 6 | 7 | } -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | com.mkeeper 6 | 1.0.0 7 | jar 8 | 4.0.0 9 | 10 | dubbo-consumer 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-starter-parent 15 | 1.5.9.RELEASE 16 | 17 | 18 | 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | 35 | com.alibaba.boot 36 | dubbo-spring-boot-starter 37 | 0.1.1 38 | 39 | 40 | 41 | com.mkeeper 42 | dubbo-api 43 | 1.0.0 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-consumer/src/main/java/com/mkeeper/DubboConsumerMain.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DubboConsumerMain { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DubboConsumerMain.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-consumer/src/main/java/com/mkeeper/com/mkeeper/dubbo/controller/DubboController.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.com.mkeeper.dubbo.controller; 2 | 3 | import com.alibaba.dubbo.config.annotation.Reference; 4 | import com.mkeeper.dubbo.api.ComputeService; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class DubboController { 11 | 12 | @Reference( 13 | version = "${demo.service.version}", 14 | application = "${dubbo.application.id}", 15 | url = "dubbo://localhost:12345" 16 | ) 17 | private ComputeService computeService; 18 | 19 | @RequestMapping("/dubbo/add/{a}/{b}") 20 | public Integer sayHello(@PathVariable Integer a, @PathVariable Integer b) { 21 | return computeService.add(a, b); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Spring boot application 2 | spring.application.name = dubbo-consumer 3 | server.port = 8080 4 | management.port = 8081 5 | management.security.enabled = false 6 | 7 | # Service Version 8 | demo.service.version = 1.0.0 9 | 10 | # Dubbo Config properties 11 | ## ApplicationConfig Bean 12 | dubbo.application.id = dubbo-consumer 13 | dubbo.application.name = dubbo-consumer 14 | 15 | ## Legacy QOS Config 16 | dubbo.qos.port = 22223 17 | 18 | ## ProtocolConfig Bean 19 | dubbo.protocol.id = dubbo 20 | dubbo.protocol.name = dubbo 21 | dubbo.protocol.port = 12345 22 | 23 | # Dubbo Endpoint (default status is disable) 24 | endpoints.dubbo.enabled = true 25 | 26 | # Dubbo Health 27 | ## StatusChecker Name defaults (default : "memory", "load" ) 28 | management.health.dubbo.status.defaults = memory -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.mkeeper 7 | 1.0.0 8 | jar 9 | 4.0.0 10 | 11 | dubbo-provider 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 1.5.9.RELEASE 17 | 18 | 19 | 20 | UTF-8 21 | 1.8 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter 28 | 29 | 30 | 31 | com.alibaba.boot 32 | dubbo-spring-boot-starter 33 | 0.1.1 34 | 35 | 36 | 37 | com.alibaba.boot 38 | dubbo-spring-boot-actuator 39 | 0.1.1 40 | 41 | 42 | 43 | com.mkeeper 44 | dubbo-api 45 | 1.0.0 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-provider/src/main/java/com/mkeeper/DubboProviderMain.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | 6 | @SpringBootApplication 7 | public class DubboProviderMain { 8 | public static void main(String[] args) { 9 | new SpringApplicationBuilder(DubboProviderMain.class) 10 | .web(false) 11 | .run(args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-provider/src/main/java/com/mkeeper/dubbo/service/DefaultComputeService.java: -------------------------------------------------------------------------------- 1 | package com.mkeeper.dubbo.service; 2 | 3 | import com.alibaba.dubbo.config.annotation.Service; 4 | import com.mkeeper.dubbo.api.ComputeService; 5 | 6 | 7 | @Service( 8 | version = "${demo.service.version}", 9 | application = "${dubbo.application.id}", 10 | protocol = "${dubbo.protocol.id}", 11 | registry = "${dubbo.registry.id}" 12 | ) 13 | public class DefaultComputeService implements ComputeService { 14 | 15 | @Override 16 | public Integer add(int a, int b) { 17 | return a + b; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Chapter8-1-2/dubbo-provider/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Spring boot application 2 | spring.application.name = dubbo-provider 3 | server.port = 9090 4 | management.port = 9091 5 | management.security.enabled = false 6 | 7 | # Service Version 8 | demo.service.version = 1.0.0 9 | 10 | # Base packages to scan Dubbo Components (e.g @Service , @Reference) 11 | dubbo.scan.basePackages = com.mkeeper.dubbo.service 12 | 13 | 14 | # Dubbo Config properties 15 | ## ApplicationConfig Bean 16 | dubbo.application.id = dubbo-provider 17 | dubbo.application.name = dubbo-provider 18 | dubbo.application.qos.port=22222 19 | dubbo.application.qos.enable=true 20 | 21 | ## ProtocolConfig Bean 22 | dubbo.protocol.id = dubbo 23 | dubbo.protocol.name = dubbo 24 | dubbo.protocol.port = 12345 25 | dubbo.protocol.status = server 26 | 27 | ## RegistryConfig Bean 28 | dubbo.registry.id = my-registry 29 | dubbo.registry.address = N/A 30 | 31 | # Dubbo Endpoint (default status is disable) 32 | endpoints.dubbo.enabled = true 33 | 34 | # Dubbo Health 35 | ## StatusChecker Name defaults (default : "memory", "load" ) 36 | management.health.dubbo.status.defaults = memory 37 | ## StatusChecker Name extras (default : empty ) 38 | management.health.dubbo.status.extras = load,threadpool -------------------------------------------------------------------------------- /Chapter8-1-2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.mkeeper 8 | Chapter8-1-2 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | dubbo-api 13 | dubbo-provider 14 | dubbo-consumer 15 | 16 | 17 | 18 | --------------------------------------------------------------------------------