├── .gitignore ├── Async ├── .gitignore ├── .project ├── README.MD ├── async.iml ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── cml │ │ └── learn │ │ └── async │ │ ├── Application.java │ │ ├── AsyncService.java │ │ ├── AsyncThreadPoolConfiguration.java │ │ └── AsyncThreadPoolConfiguration2.java │ └── resources │ ├── application.properties │ └── logback.xml ├── DynamicDataSource ├── .classpath ├── .factorypath ├── .gitignore ├── .project ├── .settings │ ├── .jsdtscope │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.apt.core.prefs │ ├── org.eclipse.jdt.core.prefs │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.wst.common.component │ ├── org.eclipse.wst.common.project.facet.core.xml │ ├── org.eclipse.wst.jsdt.ui.superType.container │ ├── org.eclipse.wst.jsdt.ui.superType.name │ └── org.eclipse.wst.validation.prefs ├── .springBeans ├── LICENSE ├── README.md ├── boot.iml ├── db │ └── springbot.sql ├── pom.xml └── src │ ├── main │ ├── i18n │ │ ├── messages.properties │ │ ├── messages_en_US.properties │ │ └── messages_zh_CN.properties │ ├── java │ │ └── com │ │ │ └── cml │ │ │ └── springboot │ │ │ ├── BootApplication.java │ │ │ ├── framework │ │ │ ├── AsyncTaskConfig.java │ │ │ ├── Configuration.java │ │ │ ├── WebGlobalConfiguration.java │ │ │ ├── controller │ │ │ │ └── BaseController.java │ │ │ ├── db │ │ │ │ ├── DynamicDataSourceAutoConfiguration.java │ │ │ │ ├── DynamicDataSourceHolder.java │ │ │ │ ├── EnableDynamicDataSource.java │ │ │ │ └── TransactionAspect.java │ │ │ ├── deserializer │ │ │ │ └── DateTimeDeserializer.java │ │ │ ├── exception │ │ │ │ └── ExceptionHandler.java │ │ │ ├── interceptor │ │ │ │ ├── ParamInterceptor.java │ │ │ │ └── TokenInterceptor.java │ │ │ ├── mybatis │ │ │ │ ├── MybatisConfig.java │ │ │ │ ├── MybatisScanConfiguration.java │ │ │ │ ├── SpringBootVFS.java │ │ │ │ └── typehandler │ │ │ │ │ ├── JodaDateTimeTypeHandler.java │ │ │ │ │ └── JodaLocalTimeTypeHandler.java │ │ │ ├── response │ │ │ │ ├── BaseResponse.java │ │ │ │ ├── BaseResponseAdvise.java │ │ │ │ └── MethodResponseHandler.java │ │ │ ├── transaction │ │ │ │ └── TransactionService.java │ │ │ └── util │ │ │ │ ├── DateFormatter.java │ │ │ │ ├── DateUtil.java │ │ │ │ ├── LogUtil.java │ │ │ │ ├── MD5.java │ │ │ │ └── UUIDUtil.java │ │ │ └── sample │ │ │ ├── bean │ │ │ ├── LogBean.java │ │ │ ├── User.java │ │ │ └── UserResponse.java │ │ │ ├── controller │ │ │ ├── ModelAttributeController.java │ │ │ ├── SampleController.java │ │ │ └── UserController.java │ │ │ ├── db │ │ │ ├── LogMapper.java │ │ │ ├── UserMapper.java │ │ │ └── resource │ │ │ │ ├── log.sql.xml │ │ │ │ └── user.sql.xml │ │ │ └── service │ │ │ ├── LogService.java │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ ├── LogServiceImpl.java │ │ │ └── UserServiceImpl.java │ ├── resources │ │ ├── ValidationMessages.properties │ │ ├── banner.txt │ │ ├── config │ │ │ ├── application-jdbc.properties │ │ │ └── application.properties │ │ ├── log4j.properties │ │ └── public │ │ │ └── error │ │ │ └── 404.html │ └── webapp │ │ ├── WEB-INF │ │ └── jsp │ │ │ ├── test.jsp │ │ │ └── welcome.jsp │ │ ├── demo.html │ │ ├── demo.jsp │ │ ├── error.jsp │ │ ├── static │ │ └── demo.html │ │ ├── test.jsp │ │ └── upload.html │ └── test │ └── java │ └── com │ └── cml │ └── springboot │ └── controller │ └── test │ ├── DynamicDataSourceTest.java │ ├── HelloControllerIT.java │ └── HelloControllerTest.java ├── Kafka ├── .classpath ├── .gitignore ├── .project ├── Kafka.iml ├── README.md ├── pom.xml └── src │ └── main │ ├── i18n │ ├── messages.properties │ ├── messages_en_US.properties │ └── messages_zh_CN.properties │ ├── java │ └── com │ │ └── cml │ │ └── springboot │ │ ├── KafkaConfiguration.java │ │ ├── consumer │ │ ├── BootApplication.java │ │ └── Consumer.java │ │ ├── message │ │ └── TestMessage.java │ │ └── producer │ │ ├── Producer.java │ │ └── ProducerBootApplication.java │ ├── resources │ ├── banner.txt │ ├── config │ │ ├── application-consumer.properties │ │ └── application-producer.properties │ ├── log4j.properties │ └── public │ │ └── error │ │ └── 404.html │ └── test │ └── com │ └── cml │ └── springboot │ └── test │ ├── SpringKafkaTest.java │ └── TestConfiguration.java ├── LearnCache ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── cml │ └── learn │ └── CacheApplication.java ├── LearnTest ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── cml │ │ └── learn │ │ └── test │ │ ├── AService.java │ │ ├── BService.java │ │ ├── CService.java │ │ ├── DService.java │ │ └── Main.java │ └── test │ ├── java │ └── com │ │ └── cml │ │ └── learn │ │ └── test │ │ ├── AServiceMockTest.java │ │ ├── AServiceTest.java │ │ ├── BServiceTest.java │ │ ├── DServicePropertiesFileTest.java │ │ ├── DServicePropertiesTest.java │ │ ├── DServiceTest.java │ │ ├── MainTest.java │ │ └── MockSelectorTest.java │ └── resources │ └── application.properties ├── README.md ├── RabbitmqSpringBoot ├── .gitignore ├── .project ├── README.MD ├── classpath ├── pom.xml ├── screenshots │ ├── rabbit-admin.png │ └── receiver.png └── src │ └── main │ ├── java │ └── com │ │ └── cml │ │ └── learning │ │ └── rabbitmq │ │ └── spring │ │ ├── Application.java │ │ ├── RabbitConfiguration.java │ │ ├── constant │ │ └── PlaceHolderConst.java │ │ ├── model │ │ └── EmailModel.java │ │ ├── receiver │ │ └── MessageReceiver.java │ │ └── service │ │ ├── MailService.java │ │ └── MailServiceImpl.java │ └── resources │ ├── application.properties │ ├── config │ └── rabbitmq │ │ └── rabbitmq.properties │ └── logback-spring.xml ├── Redis ├── .gitignore ├── .project ├── README.MD ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── cml │ │ │ └── learn │ │ │ └── redis │ │ │ ├── Application.java │ │ │ ├── CacheConfiguration.java │ │ │ └── CacheService.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── cml │ └── learn │ └── redis │ └── test │ ├── BasicCacheTest.java │ └── ConcurrentCacheTest.java ├── RestMvc ├── .classpath ├── .factorypath ├── .gitignore ├── .project ├── .springBeans ├── LICENSE ├── README.md ├── boot.iml ├── db │ └── springbot.sql ├── pom.xml ├── screenshots │ └── structure.png └── src │ ├── main │ ├── i18n │ │ ├── messages.properties │ │ ├── messages_en_US.properties │ │ └── messages_zh_CN.properties │ ├── java │ │ └── com │ │ │ └── cml │ │ │ └── springboot │ │ │ ├── BootApplication.java │ │ │ ├── framework │ │ │ ├── AsyncTaskConfig.java │ │ │ ├── Configuration.java │ │ │ ├── WebGlobalConfiguration.java │ │ │ ├── argument │ │ │ │ ├── CacheableModelMethodProcessor.java │ │ │ │ └── CustomModelArgumentResolverConfiguration.java │ │ │ ├── controller │ │ │ │ └── BaseController.java │ │ │ ├── deserializer │ │ │ │ └── DateTimeDeserializer.java │ │ │ ├── exception │ │ │ │ └── ExceptionHandler.java │ │ │ ├── interceptor │ │ │ │ ├── ParamInterceptor.java │ │ │ │ └── TokenInterceptor.java │ │ │ ├── mybatis │ │ │ │ ├── MybatisConfig.java │ │ │ │ ├── MybatisScanConfiguration.java │ │ │ │ ├── SpringBootVFS.java │ │ │ │ └── typehandler │ │ │ │ │ ├── JodaDateTimeTypeHandler.java │ │ │ │ │ └── JodaLocalTimeTypeHandler.java │ │ │ ├── response │ │ │ │ ├── BaseResponse.java │ │ │ │ ├── BaseResponseAdvise.java │ │ │ │ └── MethodResponseHandler.java │ │ │ ├── rest │ │ │ │ ├── RestMvcAutoConfiguration.java │ │ │ │ ├── RestMvcTesst.java │ │ │ │ └── TestMvc.java │ │ │ ├── transaction │ │ │ │ └── TransactionService.java │ │ │ └── util │ │ │ │ ├── DateFormatter.java │ │ │ │ ├── DateUtil.java │ │ │ │ ├── LogUtil.java │ │ │ │ ├── MD5.java │ │ │ │ └── UUIDUtil.java │ │ │ └── sample │ │ │ ├── bean │ │ │ ├── LogBean.java │ │ │ ├── User.java │ │ │ └── UserResponse.java │ │ │ ├── controller │ │ │ ├── ModelAttributeController.java │ │ │ ├── SampleController.java │ │ │ └── UserController.java │ │ │ ├── db │ │ │ ├── LogMapper.java │ │ │ ├── UserMapper.java │ │ │ └── resource │ │ │ │ ├── log.sql.xml │ │ │ │ └── user.sql.xml │ │ │ └── service │ │ │ ├── LogService.java │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ ├── LogServiceImpl.java │ │ │ └── UserServiceImpl.java │ ├── resources │ │ ├── ValidationMessages.properties │ │ ├── banner.txt │ │ ├── config │ │ │ ├── application-jdbc.properties │ │ │ └── application.properties │ │ ├── log4j.properties │ │ └── public │ │ │ └── error │ │ │ └── 404.html │ └── webapp │ │ ├── WEB-INF │ │ └── jsp │ │ │ ├── test.jsp │ │ │ └── welcome.jsp │ │ ├── demo.html │ │ ├── demo.jsp │ │ ├── error.jsp │ │ ├── static │ │ └── demo.html │ │ ├── test.jsp │ │ └── upload.html │ └── test │ └── java │ └── com │ └── cml │ └── springboot │ └── controller │ └── test │ ├── HelloControllerIT.java │ └── HelloControllerTest.java ├── SpringBootWebFlux ├── README.MD ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── cml │ │ │ │ └── learn │ │ │ │ └── webflux │ │ │ │ ├── Application.java │ │ │ │ ├── controller │ │ │ │ └── WebFluxController.java │ │ │ │ ├── error │ │ │ │ ├── CustomExceptionHandler.java │ │ │ │ └── ErrorHandler.java │ │ │ │ └── filter │ │ │ │ ├── AccessLogFilter.java │ │ │ │ ├── LogUtils.java │ │ │ │ ├── PartnerServerHttpRequestDecorator.java │ │ │ │ ├── PartnerServerHttpResponseDecorator.java │ │ │ │ └── PayloadServerWebExchangeDecorator.java │ │ └── resources │ │ │ ├── application.properties │ │ │ └── logback.xml │ └── test │ │ └── java │ │ └── com │ │ └── cml │ │ └── webflux │ │ └── webclient │ │ ├── JsonContentTests.java │ │ ├── Person.java │ │ └── WebClientTest.java └── web-flux.iml ├── SpringJpa ├── .gitignore ├── .project ├── README.MD ├── db │ └── db.sql ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── cml │ │ │ └── learn │ │ │ └── jpa │ │ │ ├── Application.java │ │ │ ├── controller │ │ │ └── HelloWorldController.java │ │ │ ├── db │ │ │ ├── bean │ │ │ │ ├── Order.java │ │ │ │ └── User.java │ │ │ ├── read │ │ │ │ ├── OrderReadRepository.java │ │ │ │ └── UserReadRepository.java │ │ │ └── write │ │ │ │ ├── OrderRepository.java │ │ │ │ └── UserRepository.java │ │ │ ├── dto │ │ │ ├── OrderQueryDTO.java │ │ │ ├── OrderQueryDTO2.java │ │ │ ├── OrderQueryDTO3.java │ │ │ ├── UserEmailDTO.java │ │ │ ├── UserNickNameDTO.java │ │ │ └── UserProjection.java │ │ │ ├── framework │ │ │ ├── db │ │ │ │ ├── ReadDbConfig.java │ │ │ │ ├── WriteDbConfig.java │ │ │ │ └── converter │ │ │ │ │ └── DateToDateTimeConverter.java │ │ │ └── util │ │ │ │ └── MD5.java │ │ │ └── service │ │ │ └── UserService.java │ └── resources │ │ ├── application.properties │ │ └── logback.xml │ └── test │ └── java │ └── com │ └── cml │ └── learn │ └── jpa │ └── test │ ├── TransactionTest.java │ ├── UserCreateTest.java │ ├── UserProjectionQueryTest.java │ ├── UserQueryTest.java │ └── order │ ├── OrderCreateTest.java │ └── OrderQueryTest.java ├── SpringStarter ├── .classpath └── .settings │ ├── org.eclipse.core.resources.prefs │ └── org.eclipse.jdt.core.prefs ├── embedded-container ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── cml │ └── learn │ └── embedd │ └── container │ ├── Application.java │ ├── redis │ ├── RedisConfiguration.java │ └── RedisTest.java │ └── zookeeper │ ├── EmbeddedZooKeeper.java │ ├── EmbeddedZookeeperConfiguration.java │ └── EmbeddedZookeeperTest.java ├── flyway ├── flyway.iml ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── cml │ │ └── learn │ │ └── flyway │ │ ├── FlywayApplication.java │ │ └── repository │ │ ├── City.java │ │ └── CityRepository.java │ └── resources │ └── application.yaml ├── rabbitmq ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── README.MD ├── pom.xml ├── screenshots │ ├── rabbit-admin.png │ └── receiver.png └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── cml │ │ │ └── learning │ │ │ └── rabbitmq │ │ │ └── spring │ │ │ ├── model │ │ │ └── EmailModel.java │ │ │ ├── receiver │ │ │ ├── AbstractEmailReceiver.java │ │ │ ├── AbstractReceiver.java │ │ │ ├── DirectMessageReceiver.java │ │ │ ├── FanoutMessageReceiver.java │ │ │ ├── QueneMessageReceiver.java │ │ │ ├── TopicManualACKMessageReceiver.java │ │ │ └── TopicMessageReceiver.java │ │ │ └── service │ │ │ ├── MailService.java │ │ │ └── MailServiceImpl.java │ └── resources │ │ ├── config │ │ └── rabbitmq │ │ │ └── rabbitmq.properties │ │ ├── log4j.properties │ │ └── spring │ │ ├── application-rabbitmq-client.xml │ │ └── application-rabbitmq-listener.xml │ └── test │ └── java │ └── com │ └── cml │ └── learning │ └── rabbitmq │ └── spring │ ├── SpringIntegrationReceiverTest.java │ └── SpringIntegrationSendTest.java └── web ├── .factorypath ├── .gitignore ├── LICENSE ├── README.md ├── db └── springbot.sql ├── pom.xml ├── screenshots └── structure.png └── src ├── main ├── i18n │ ├── messages.properties │ ├── messages_en_US.properties │ └── messages_zh_CN.properties ├── java │ └── com │ │ └── cml │ │ └── springboot │ │ ├── BootApplication.java │ │ ├── framework │ │ ├── AsyncTaskConfig.java │ │ ├── Configuration.java │ │ ├── WebGlobalConfiguration.java │ │ ├── controller │ │ │ └── BaseController.java │ │ ├── deserializer │ │ │ └── DateTimeDeserializer.java │ │ ├── exception │ │ │ └── ExceptionHandler.java │ │ ├── interceptor │ │ │ ├── ParamInterceptor.java │ │ │ └── TokenInterceptor.java │ │ ├── mybatis │ │ │ ├── MybatisConfig.java │ │ │ ├── MybatisScanConfiguration.java │ │ │ ├── SpringBootVFS.java │ │ │ └── typehandler │ │ │ │ ├── JodaDateTimeTypeHandler.java │ │ │ │ └── JodaLocalTimeTypeHandler.java │ │ ├── response │ │ │ ├── BaseResponse.java │ │ │ ├── BaseResponseAdvise.java │ │ │ └── MethodResponseHandler.java │ │ ├── transaction │ │ │ └── TransactionService.java │ │ └── util │ │ │ ├── DateFormatter.java │ │ │ ├── DateUtil.java │ │ │ ├── LogUtil.java │ │ │ ├── MD5.java │ │ │ └── UUIDUtil.java │ │ └── sample │ │ ├── bean │ │ ├── LogBean.java │ │ ├── User.java │ │ └── UserResponse.java │ │ ├── controller │ │ ├── ModelAttributeController.java │ │ ├── SampleController.java │ │ └── UserController.java │ │ ├── db │ │ ├── LogMapper.java │ │ ├── UserMapper.java │ │ └── resource │ │ │ ├── log.sql.xml │ │ │ └── user.sql.xml │ │ └── service │ │ ├── LogService.java │ │ ├── UserService.java │ │ └── impl │ │ ├── LogServiceImpl.java │ │ └── UserServiceImpl.java ├── resources │ ├── ValidationMessages.properties │ ├── banner.txt │ ├── config │ │ ├── application-jdbc.properties │ │ └── application.properties │ ├── log4j.properties │ └── public │ │ └── error │ │ └── 404.html └── webapp │ ├── WEB-INF │ └── jsp │ │ ├── test.jsp │ │ └── welcome.jsp │ ├── demo.html │ ├── demo.jsp │ ├── error.jsp │ ├── static │ └── demo.html │ ├── test.jsp │ └── upload.html └── test └── java └── com └── cml └── springboot └── controller └── test ├── HelloControllerIT.java └── HelloControllerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | **/bin/ 3 | **/target/ 4 | **/logs/ 5 | **/transaction-logs/ 6 | **/.idea/ -------------------------------------------------------------------------------- /Async/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.settings/ 6 | .classpath -------------------------------------------------------------------------------- /Async/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Async 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | org.eclipse.wst.common.project.facet.core.nature 34 | 35 | 36 | -------------------------------------------------------------------------------- /Async/README.MD: -------------------------------------------------------------------------------- 1 | # Async项目说明 # 2 | Async线程池测试 3 | 4 | 5 | # 测试说明# 6 | 可以通过配置文件中的async.threadpool.enable进行配置开关线程池 7 | -------------------------------------------------------------------------------- /Async/src/main/java/com/cml/learn/async/AsyncThreadPoolConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.async; 2 | 3 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 7 | 8 | @ConditionalOnProperty(name = "async.threadpool.enable", matchIfMissing = false) 9 | @Configuration 10 | public class AsyncThreadPoolConfiguration { 11 | 12 | @Bean 13 | public ThreadPoolTaskExecutor taskExecutor() { 14 | ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); 15 | taskExecutor.setCorePoolSize(100); 16 | taskExecutor.setMaxPoolSize(500); 17 | taskExecutor.setThreadNamePrefix("async-thread-pool-"); 18 | return taskExecutor; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Async/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | async.threadpool.enable=false -------------------------------------------------------------------------------- /DynamicDataSource/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.apt_generated/ 6 | -------------------------------------------------------------------------------- /DynamicDataSource/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DynamicDataSource 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.wst.validation.validationbuilder 25 | 26 | 27 | 28 | 29 | org.eclipse.m2e.core.maven2Builder 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jem.workbench.JavaEMFNature 36 | org.eclipse.wst.common.modulecore.ModuleCoreNature 37 | org.springframework.ide.eclipse.core.springnature 38 | org.eclipse.jdt.core.javanature 39 | org.eclipse.m2e.core.maven2Nature 40 | org.eclipse.wst.common.project.facet.core.nature 41 | org.eclipse.wst.jsdt.core.jsNature 42 | 43 | 44 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/i18n=UTF-8 3 | encoding//src/main/java=UTF-8 4 | encoding//src/main/resources=UTF-8 5 | encoding//src/test/java=UTF-8 6 | encoding//src/test/resources=UTF-8 7 | encoding/=UTF-8 8 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.jdt.apt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.apt.aptEnabled=true 3 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /DynamicDataSource/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /DynamicDataSource/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | java:com.cml.springboot.main.BootApplication 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /DynamicDataSource/README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot Learning # 2 | 3 | 读写分离自动配置 4 | 详情介绍请看博客:http://blog.csdn.net/cml_blog/article/details/78224798 5 | 6 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/i18n/messages.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to default -------------------------------------------------------------------------------- /DynamicDataSource/src/main/i18n/messages_en_US.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to english -------------------------------------------------------------------------------- /DynamicDataSource/src/main/i18n/messages_zh_CN.properties: -------------------------------------------------------------------------------- 1 | welcome=\u6b22\u8fce\u6765\u5230\u4e2d\u56fd -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/BootApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.PropertySource; 9 | import org.springframework.context.annotation.PropertySources; 10 | import org.springframework.scheduling.annotation.EnableAsync; 11 | 12 | import com.cml.springboot.framework.db.EnableDynamicDataSource; 13 | 14 | @Configuration 15 | @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) 16 | @ComponentScan() 17 | @EnableAsync 18 | @PropertySources({ @PropertySource("classpath:config/application-jdbc.properties") }) 19 | @EnableDynamicDataSource 20 | public class BootApplication { 21 | 22 | // @Bean 23 | // public PropertyPlaceholderConfigurer placeHolder() { 24 | // 25 | // PropertyPlaceholderConfigurer configure = new 26 | // PropertyPlaceholderConfigurer(); 27 | // configure.setLocations(null); 28 | // 29 | // return configure; 30 | // } 31 | 32 | public static void main(String[] args) throws Exception { 33 | SpringApplication.run(BootApplication.class, args); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/AsyncTaskConfig.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | import java.util.concurrent.Executor; 4 | 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.scheduling.annotation.AsyncConfigurer; 11 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 12 | 13 | @Configuration 14 | public class AsyncTaskConfig implements AsyncConfigurer { 15 | 16 | protected static Log log = LogFactory.getLog(AsyncTaskConfig.class); 17 | 18 | @Value("${async.task.config.corePoolSize}") 19 | private Integer corePoolSize; 20 | @Value("${async.task.config.maxPoolSize}") 21 | private Integer maxPoolSize; 22 | 23 | @Override 24 | public Executor getAsyncExecutor() { 25 | 26 | log.info("<<>>====>corePoolSize:" + corePoolSize + ",maxPoolSize:" + maxPoolSize); 27 | 28 | ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor(); 29 | ex.setCorePoolSize(corePoolSize); 30 | ex.setMaxPoolSize(maxPoolSize); 31 | ex.initialize(); 32 | return ex; 33 | } 34 | 35 | @Override 36 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 37 | return null; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/Configuration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | public interface Configuration { 4 | interface Status { 5 | int STATUS_OK = 1; 6 | int STATUS_FAIL = 2; 7 | int STATUS_INVALID_TOKEN = 3; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.controller; 2 | 3 | import org.springframework.validation.Errors; 4 | import org.springframework.validation.ObjectError; 5 | 6 | import com.cml.springboot.framework.Configuration; 7 | 8 | public class BaseController { 9 | 10 | public static final int SUCCESS = Configuration.Status.STATUS_OK; 11 | public static final int FAIL = Configuration.Status.STATUS_FAIL; 12 | 13 | public static String getAllErrors(Errors errors) { 14 | StringBuilder builder = new StringBuilder(); 15 | for (ObjectError error : errors.getAllErrors()) { 16 | builder.append(error.getDefaultMessage()).append("\n"); 17 | } 18 | return builder.toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/db/DynamicDataSourceHolder.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.db; 2 | 3 | /** 4 | * 动态数据源处理 5 | * 6 | * @author cml 7 | * 8 | */ 9 | public class DynamicDataSourceHolder { 10 | private static ThreadLocal holderDataSource = new ThreadLocal<>(); 11 | 12 | public static void setDataSource(String dataSource) { 13 | holderDataSource.set(dataSource); 14 | } 15 | 16 | public static String getDataSource() { 17 | return holderDataSource.get(); 18 | } 19 | 20 | public static void clear() { 21 | holderDataSource.remove(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/db/EnableDynamicDataSource.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.db; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import org.springframework.context.annotation.Import; 10 | 11 | @Target(ElementType.TYPE) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Documented 14 | @Import(DynamicDataSourceAutoConfiguration.class) 15 | public @interface EnableDynamicDataSource { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/deserializer/DateTimeDeserializer.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.deserializer; 2 | 3 | import java.io.IOException; 4 | 5 | import org.joda.time.DateTime; 6 | import org.joda.time.format.DateTimeFormat; 7 | import org.joda.time.format.DateTimeFormatter; 8 | import org.springframework.format.datetime.joda.DateTimeFormatterFactory; 9 | 10 | import com.fasterxml.jackson.core.JsonGenerator; 11 | import com.fasterxml.jackson.core.JsonProcessingException; 12 | import com.fasterxml.jackson.databind.JsonSerializer; 13 | import com.fasterxml.jackson.databind.SerializerProvider; 14 | 15 | public class DateTimeDeserializer extends JsonSerializer { 16 | 17 | private String format = "yyyyMMddHHmmss"; 18 | 19 | public DateTimeDeserializer() { 20 | System.out.println("===================================================dddddddddddddddddddddddddddddddddddd"); 21 | } 22 | 23 | public DateTimeDeserializer(String format) { 24 | super(); 25 | this.format = format; 26 | } 27 | 28 | @Override 29 | public void serialize(DateTime value, JsonGenerator gen, SerializerProvider serializers) 30 | throws IOException, JsonProcessingException { 31 | if (null != value) { 32 | gen.writeString(value.toString(format)); 33 | } 34 | System.out.println("=============================="); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/mybatis/MybatisScanConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.mybatis.spring.annotation.MapperScan; 6 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | @AutoConfigureAfter(MybatisConfig.class) 11 | @MapperScan(basePackages = { "com.cml.springboot.sample.db" }, sqlSessionFactoryRef = "sqlSessionFactory") 12 | public class MybatisScanConfiguration { 13 | protected static Log log = LogFactory.getLog(MybatisScanConfiguration.class); 14 | 15 | public MybatisScanConfiguration() { 16 | log.info("*************************MybatisScanConfiguration***********************"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/mybatis/SpringBootVFS.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.apache.ibatis.io.VFS; 10 | import org.springframework.core.io.Resource; 11 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 12 | import org.springframework.core.io.support.ResourcePatternResolver; 13 | 14 | public class SpringBootVFS extends VFS { 15 | 16 | private final ResourcePatternResolver resourceResolver; 17 | 18 | public SpringBootVFS() { 19 | this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); 20 | } 21 | 22 | @Override 23 | public boolean isValid() { 24 | return true; 25 | } 26 | 27 | @Override 28 | protected List list(URL url, String path) throws IOException { 29 | Resource[] resources = resourceResolver.getResources("classpath*:" + path + "/**/*.class"); 30 | List resourcePaths = new ArrayList(); 31 | for (Resource resource : resources) { 32 | resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); 33 | } 34 | return resourcePaths; 35 | } 36 | 37 | private static String preserveSubpackageName(final URI uri, final String rootPath) { 38 | final String uriStr = uri.toString(); 39 | final int start = uriStr.indexOf(rootPath); 40 | return uriStr.substring(start); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/response/BaseResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | public class BaseResponse { 4 | private Integer code; 5 | private String message; 6 | 7 | public BaseResponse() { 8 | } 9 | 10 | public BaseResponse(Integer code, String message) { 11 | super(); 12 | this.code = code; 13 | this.message = message; 14 | } 15 | 16 | public Integer getCode() { 17 | return code; 18 | } 19 | 20 | public void setCode(Integer code) { 21 | this.code = code; 22 | } 23 | 24 | public String getMessage() { 25 | return message; 26 | } 27 | 28 | public void setMessage(String message) { 29 | this.message = message; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/response/BaseResponseAdvise.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.converter.HttpMessageConverter; 8 | import org.springframework.http.server.ServerHttpRequest; 9 | import org.springframework.http.server.ServerHttpResponse; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 12 | 13 | //@ControllerAdvice() 14 | public class BaseResponseAdvise implements ResponseBodyAdvice { 15 | 16 | private static Log log = LogFactory.getLog(BaseResponseAdvise.class); 17 | 18 | @Override 19 | public boolean supports(MethodParameter returnType, Class> converterType) { 20 | log.info("===>" + (returnType.getGenericParameterType() instanceof BaseResponse)); 21 | return returnType.getGenericParameterType() == BaseResponse.class; 22 | } 23 | 24 | @Override 25 | public BaseResponse beforeBodyWrite(BaseResponse body, MethodParameter returnType, MediaType selectedContentType, 26 | Class> selectedConverterType, ServerHttpRequest request, 27 | ServerHttpResponse response) { 28 | // body.setMessage("被我修改了"); 29 | return body; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/response/MethodResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.context.request.NativeWebRequest; 6 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 7 | import org.springframework.web.method.support.ModelAndViewContainer; 8 | 9 | @Component 10 | public class MethodResponseHandler implements HandlerMethodReturnValueHandler { 11 | 12 | @Override 13 | public boolean supportsReturnType(MethodParameter returnType) { 14 | System.out.println("=====================? supportsReturnType"); 15 | return true; 16 | } 17 | 18 | @Override 19 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, 20 | NativeWebRequest webRequest) throws Exception { 21 | System.out.println("====================> handleReturnValue"); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/transaction/TransactionService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.transaction; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.core.Ordered; 8 | import org.springframework.core.annotation.Order; 9 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 10 | import org.springframework.transaction.PlatformTransactionManager; 11 | import org.springframework.transaction.annotation.EnableTransactionManagement; 12 | 13 | import com.cml.springboot.framework.db.DynamicDataSourceAutoConfiguration.DynamicDataSource; 14 | import com.cml.springboot.framework.db.TransactionAspect; 15 | 16 | @AutoConfigureAfter(TransactionAspect.class) 17 | @Configuration 18 | @EnableTransactionManagement() 19 | public class TransactionService { 20 | 21 | @Autowired 22 | private DynamicDataSource dataSource; 23 | 24 | 25 | @Order(Ordered.LOWEST_PRECEDENCE) 26 | @Bean(name = "txManager") 27 | public PlatformTransactionManager txManager() { 28 | return new DataSourceTransactionManager(dataSource); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/util/LogUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | public class LogUtil { 4 | 5 | private static final String FORMAT_CONTROLLER = "《《《《%s》》》》====>%s"; 6 | 7 | public static String formatControllerLog(Object controller, String log) { 8 | return String.format(FORMAT_CONTROLLER, controller.getClass().getSimpleName(), log); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/util/MD5.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class MD5 { 6 | public static String getMD5(String source) { 7 | String s = null; 8 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 9 | 'a', 'b', 'c', 'd', 'e', 'f' }; 10 | try { 11 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 12 | md5.update(source.getBytes()); 13 | byte tmp[] = md5.digest(); 14 | char str[] = new char[16 * 2]; 15 | int k = 0; 16 | for (int i = 0; i < 16; i++) { 17 | byte byte0 = tmp[i]; 18 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 19 | str[k++] = hexDigits[byte0 & 0xf]; 20 | } 21 | s = new String(str); 22 | 23 | } catch (Exception ex) { 24 | ex.printStackTrace(); 25 | } 26 | return s; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/framework/util/UUIDUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class UUIDUtil { 6 | 7 | public static final String generateUUID() { 8 | return UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/bean/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.bean; 2 | 3 | import com.cml.springboot.framework.response.BaseResponse; 4 | 5 | public class UserResponse extends BaseResponse { 6 | private User user; 7 | 8 | public UserResponse(Integer code, String message, User user) { 9 | super(code, message); 10 | this.user = user; 11 | } 12 | 13 | public UserResponse(Integer code, User user) { 14 | super(code, null); 15 | this.user = user; 16 | } 17 | 18 | public User getUser() { 19 | return user; 20 | } 21 | 22 | public void setUser(User user) { 23 | this.user = user; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/controller/ModelAttributeController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.controller; 2 | 3 | import java.sql.SQLException; 4 | 5 | import javax.annotation.Resource; 6 | import javax.validation.Valid; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.ModelAttribute; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import com.cml.springboot.sample.bean.User; 16 | import com.cml.springboot.sample.service.UserService; 17 | 18 | /** 19 | * ModelAttribute demo 20 | * 21 | * @author team-lab 22 | * 23 | */ 24 | @Controller 25 | @RequestMapping("/model") 26 | public class ModelAttributeController { 27 | 28 | @Resource(name = "userServiceImpl") 29 | private UserService userService; 30 | 31 | @ModelAttribute("user") 32 | public User user(@RequestParam String token) throws SQLException { 33 | System.out.println("==================================================token:"+token); 34 | if (StringUtils.isBlank(token)) { 35 | return null; 36 | } 37 | return userService.findUserByToken(token); 38 | } 39 | 40 | @RequestMapping("/testA") 41 | @ResponseBody 42 | public String testA(@ModelAttribute() User user) { 43 | if (user == null) { 44 | return "user is null!!!!"; 45 | } 46 | return "user:" + user.getUsername() + "," + user.getNickName(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/db/LogMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogMapper { 6 | void insertLog(LogBean logbean); 7 | } 8 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/db/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserMapper { 8 | User getUserByToken(String token) throws SQLException; 9 | 10 | User getUser(User user); 11 | 12 | Integer updateToken(User loginUser); 13 | } 14 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/db/resource/log.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | INSERT INTO t_api_log ( 7 | call_day, 8 | parameters, 9 | return_status_code, 10 | returns, 11 | api_url, 12 | create_date, 13 | update_date 14 | 15 | ) 16 | VALUES ( 17 | #{callDayStr}, 18 | #{parameters}, 19 | #{returnStatusCode}, 20 | #{returns}, 21 | #{apiUrl}, 22 | #{createDate}, 23 | NOW() 24 | ) 25 | 26 | 27 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/db/resource/user.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | 35 | 36 | 37 | UPDATE 38 | t_user 39 | SET 40 | token = #{newToken}, 41 | update_date = NOW() 42 | WHERE 43 | token = #{token} 44 | 45 | 46 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/service/LogService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogService { 6 | void insertLog(LogBean logbean); 7 | 8 | void insertLogReadOnly(LogBean logbean); 9 | } 10 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/java/com/cml/springboot/sample/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserService { 8 | User findUserByToken(String token) throws SQLException; 9 | 10 | User login(User user) throws Exception; 11 | } 12 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/resources/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | user.empty.username=\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7axxxxx -------------------------------------------------------------------------------- /DynamicDataSource/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | I am a banner!!! -------------------------------------------------------------------------------- /DynamicDataSource/src/main/resources/config/application.properties: -------------------------------------------------------------------------------- 1 | endpoints.beans.id=springbeans 2 | endpoints.beans.sensitive=false 3 | endpoints.shutdown.enabled=true 4 | 5 | spring.datasource.initialize=false 6 | 7 | # \u81ea\u5b9a\u4e49\u7aef\u53e3 8 | server.port=8080 9 | 10 | #\u5173\u95edbanner\u8bbe\u7f6e 11 | spring.main.banner-mode=off 12 | 13 | #spring.resources.staticLocations=*\.html,/*.html 14 | #spring.devtools.restart.exclude=static/**,public/**,src/main/webapp/** 15 | 16 | spring.mvc.view.prefix=/ 17 | spring.mvc.view.suffix=.jsp 18 | application.message=Hello Phil 19 | 20 | 21 | #\u5f02\u6b65\u5904\u7406\u914d\u7f6e 22 | async.task.config.corePoolSize=5 23 | async.task.config.maxPoolSize=500 24 | 25 | #\u5f02\u5e38\u8fd4\u56de\u5904\u7406\u914d\u7f6e true\u8868\u793a\u4e0d\u5bf9\u5916\u66b4\u9732\u5f02\u5e38\u4fe1\u606f\uff0c\u53ea\u8fd4\u56de\u56fa\u5b9a\u7684${exception.response.messasge} 26 | exception.response.filter=true 27 | #exception.response.contentType=application/json 28 | exception.response.messasge=exception 29 | 30 | #log\u914d\u7f6e TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. 31 | #logging.file=logs/api.log 32 | #logging.path=logs %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} 33 | #logging.level.root=INFO 34 | #logging.level.org.springframework.web=DEBUG 35 | #logging.level.org.hibernate=ERROR 36 | 37 | 38 | #logging.config=classpath:log4j2.xml 39 | 40 | 41 | #\u52a8\u6001\u6570\u636e\u6e90\u914d\u7f6e 42 | dynamicDatasource.strategy.read=get,find,select 43 | dynamicDatasource.strategy.write=insert,update,delete,login 44 | dynamicDatasource.defaultDataSource=write -------------------------------------------------------------------------------- /DynamicDataSource/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J\u914d\u7f6e 2 | log4j.rootCategory=INFO,stdout,file 3 | log4j.logger.com.cml.springboot.framework.interceptor=INFO,logfile 4 | log4j.logger.org.mybatis.spring.SqlSessionFactoryBean=ALL,stdout,logfile 5 | 6 | ###\u663e\u793aSQL\u8bed\u53e5\u90e8\u5206 7 | log4j.logger.org.mybatis=ALL 8 | log4j.logger.org.apache=ALL 9 | log4j.logger.org.apache.ibatis.logging.jdbc=ALL 10 | log4j.logger.java.sql=ALL 11 | log4j.logger.com.cml.springboot=ALL 12 | 13 | # \u63a7\u5236\u53f0\u8f93\u51fa 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 17 | 18 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 19 | log4j.appender.file=org.apache.log4j.DailyRollingFileAppender 20 | log4j.appender.file.file=logs/springboot.log 21 | log4j.appender.file.DatePattern='.'yyyy-MM-dd 22 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 23 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 24 | 25 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 26 | log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender 27 | log4j.appender.logfile.file=logs/api.log 28 | log4j.appender.logfile.DatePattern='.'yyyy-MM-dd 29 | log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 30 | log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /DynamicDataSource/src/main/resources/public/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 404 8 | 9 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/WEB-INF/jsp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 234567890=-"src/main/webapp/test.jsp" 11 | 12 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/WEB-INF/jsp/welcome.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 5 | 6 | 7 | 8 | 9 | 10 | 11 | Spring URL: ${springUrl} at ${time} 12 |
13 | JSTL URL: ${url} 14 |
15 | Message: ${message} 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

master api demo

9 |

10 | 16 |

注:为了测试方便,将请求url设置为可接受get方式

17 | 18 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/demo.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 4 | 5 | 6 | 7 | 8 | Insert title here 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | errors 11 | 12 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/static/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

9 | 登录测试 10 | 登录测试 11 | 登录测试 12 | 13 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 23456789 test 11 | 12 | -------------------------------------------------------------------------------- /DynamicDataSource/src/main/webapp/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | upload 8 | 9 |
10 | 11 | 12 |
13 |
14 |
15 | 16 | 17 |
18 | 19 | -------------------------------------------------------------------------------- /DynamicDataSource/src/test/java/com/cml/springboot/controller/test/DynamicDataSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import com.cml.springboot.BootApplication; 10 | import com.cml.springboot.sample.bean.User; 11 | import com.cml.springboot.sample.service.UserService; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest(classes = BootApplication.class) 15 | public class DynamicDataSourceTest { 16 | 17 | @Autowired 18 | private UserService userService; 19 | 20 | @Test 21 | public void testLogin() throws Exception { 22 | User user = new User(); 23 | user.setUsername("11111111111"); 24 | user.setPassword("123456"); 25 | User loginUser = userService.login(user); 26 | System.out.println("登录结果:" + loginUser); 27 | } 28 | 29 | @Test 30 | public void testFindUser() throws Exception { 31 | User loginUser = userService.findUserByToken("xxx"); 32 | System.out.println("查询用户结果:" + loginUser); 33 | } 34 | } -------------------------------------------------------------------------------- /DynamicDataSource/src/test/java/com/cml/springboot/controller/test/HelloControllerIT.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import java.net.URL; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.context.embedded.LocalServerPort; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.web.client.TestRestTemplate; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | //@RunWith(SpringRunner.class) 16 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 | public class HelloControllerIT { 18 | 19 | @LocalServerPort 20 | private int port; 21 | 22 | private URL base; 23 | 24 | @Autowired 25 | private TestRestTemplate template; 26 | 27 | @Before 28 | public void setUp() throws Exception { 29 | this.base = new URL("http://localhost:" + port + "/"); 30 | } 31 | 32 | @Test 33 | public void getHello() throws Exception { 34 | ResponseEntity response = template.getForEntity(base.toString(), String.class); 35 | // assertThat(response.getBody(), equalTo("Hello World!")); 36 | } 37 | } -------------------------------------------------------------------------------- /DynamicDataSource/src/test/java/com/cml/springboot/controller/test/HelloControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | //@RunWith(SpringRunner.class) 12 | //@SpringBootTest 13 | //@AutoConfigureMockMvc 14 | public class HelloControllerTest { 15 | 16 | @Autowired 17 | private MockMvc mvc; 18 | 19 | @Test 20 | public void getHello() throws Exception { 21 | // mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) 22 | // .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); 23 | } 24 | } -------------------------------------------------------------------------------- /Kafka/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Kafka/.gitignore: -------------------------------------------------------------------------------- 1 | /.apt_generated/ 2 | -------------------------------------------------------------------------------- /Kafka/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Kafka 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /Kafka/README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot Learning # 2 | 3 | 此项目主要作为SpringBoot学习,和根据实际项目对SpringBoot进行配置改造 4 | 主要使用框架:SpringBoot(Spring,SpringMVC),Mybatis,ehcache,javamail 5 | 6 | # 项目结构 # 7 | - **程序入口** 8 | > com.cml.springboot.consumer.BootApplication 9 | 10 | - **核心配置** 11 | > com.cml.springboot.framework 是核心包,取代原有的xml配置,将xml配置等价转换为注解配置! 12 | 13 | - **demo代码** 14 | > com.cml.springboot.sample为测试使用的代码,主要结构为Controller,bean,db,service几个常用的包层级。 15 | 16 | - **db** 17 | > db文件夹下为demo工程的数据库ddl 18 | 19 | # 执行程序 # 20 | 详见:wiki Home page 21 | # 分支说明 # 22 | 23 | 1. master 24 | 25 | > 主要分支,模拟常用api功能。 26 | 27 | 2. branch_learn 28 | 29 | > 初始化分支,混杂各种spring boot学习代码,未做具体区分 30 | 31 | 3. branch_shiro 32 | 33 | > 整合shiro框架,实现授权,认证与自定义拦截器授权处理 34 | 35 | 4. deploy_jar_bugfind 36 | 37 | > 查找与解决打包jar后Mybatis扫描问题 38 | 39 | 5. branch_i18n 40 | 41 | > 国际化支持 42 | 43 | 6. branch_mail 44 | 45 | > 邮件发送功能整合,注意需要在config/application.properties配置邮箱服务密码 46 | 47 | 7. branch-mybatis-scanner 48 | 49 | > 添加Mybatis MapperScan动态扫描(占位符)功能 ,详情见博客:http://blog.csdn.net/cml_blog/article/details/65658654 50 | 51 | 8. branch-mybatis-generate 52 | 53 | > mybatis beans生成工具,默认日期类型为DateTime类型,入口类:com.cml.springboot.sample.mbg.MybatisGenerateEntrance 54 | 55 | 56 | #问题与解决 57 | 1、Mybatis打包jar后无法扫描到bean与mapper问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/53138851 58 | 2、163发送邮件功能问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/54235510 59 | 60 | # 当前分支(master)测试说明 # 61 | > 详见demo.html 62 | > 端口号为2222,可在config/application.properties 中server.port进行配置 63 | 64 | # 更多信息请查看wiki # 65 | 66 | 67 | -------------------------------------------------------------------------------- /Kafka/src/main/i18n/messages.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to default -------------------------------------------------------------------------------- /Kafka/src/main/i18n/messages_en_US.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to english -------------------------------------------------------------------------------- /Kafka/src/main/i18n/messages_zh_CN.properties: -------------------------------------------------------------------------------- 1 | welcome=\u6b22\u8fce\u6765\u5230\u4e2d\u56fd -------------------------------------------------------------------------------- /Kafka/src/main/java/com/cml/springboot/consumer/BootApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.consumer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.WebApplicationType; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Profile; 7 | import org.springframework.kafka.annotation.EnableKafka; 8 | import org.springframework.scheduling.annotation.EnableAsync; 9 | import org.springframework.scheduling.annotation.EnableScheduling; 10 | 11 | @SpringBootApplication 12 | @EnableScheduling 13 | @EnableKafka 14 | public class BootApplication { 15 | 16 | public static void main(String[] args) throws Exception { 17 | SpringApplication app = new SpringApplication(BootApplication.class); 18 | app.setWebApplicationType(WebApplicationType.NONE); 19 | // app.setWebEnvironment(false); 20 | app.run(args); 21 | // SpringApplication.run(BootApplication.class, args); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Kafka/src/main/java/com/cml/springboot/consumer/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.consumer; 2 | 3 | import com.cml.springboot.message.TestMessage; 4 | import org.apache.kafka.clients.consumer.ConsumerRecord; 5 | import org.springframework.kafka.annotation.KafkaListener; 6 | import org.springframework.scheduling.annotation.Async; 7 | import org.springframework.stereotype.Component; 8 | 9 | @Component 10 | class Consumer { 11 | 12 | // @KafkaListener(topics = "test2") 13 | // public void processMessage(String message) throws Exception { 14 | // System.out.println("processMessage receivced sample message [" + message + "] threadId:" + Thread.currentThread().getId()); 15 | // 16 | // } 17 | 18 | @KafkaListener(topics = "test2") 19 | public void processMessage2(TestMessage testMessage) throws Exception { 20 | System.out.println("processMessage2 receivced sample message [" + testMessage.toString() + "] threadId:" + Thread.currentThread().getId()); 21 | // Thread.sleep(100); 22 | // if (Math.random() < 0.5) 23 | // throw new Exception("出错了:" + testMessage.toString()); 24 | 25 | } 26 | // @KafkaListener(topics = "test2") 27 | // public void processMessage(ConsumerRecord message) throws Exception { 28 | // message.headers().forEach(t -> { 29 | // System.out.println("header:" + t.key() + ":" + new String(t.value())); 30 | // }); 31 | // System.out.println("Received sample message [" + message + "] threadId:" + Thread.currentThread().getId()); 32 | // 33 | // } 34 | 35 | } -------------------------------------------------------------------------------- /Kafka/src/main/java/com/cml/springboot/message/TestMessage.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.message; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | import java.io.Serializable; 7 | 8 | public class TestMessage implements Serializable { 9 | private int code; 10 | private String value; 11 | 12 | public TestMessage() { 13 | super(); 14 | } 15 | 16 | @JsonCreator 17 | public TestMessage(@JsonProperty("id") int code, @JsonProperty("value") String value) { 18 | super(); 19 | this.code = code; 20 | this.value = value; 21 | } 22 | 23 | public int getCode() { 24 | return code; 25 | } 26 | 27 | public void setCode(int code) { 28 | this.code = code; 29 | } 30 | 31 | public String getValue() { 32 | return value; 33 | } 34 | 35 | public void setValue(String value) { 36 | this.value = value; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "TestMessage [code=" + code + ", value=" + value + "]"; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Kafka/src/main/java/com/cml/springboot/producer/Producer.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.producer; 2 | 3 | import com.cml.springboot.message.TestMessage; 4 | import org.springframework.kafka.core.KafkaTemplate; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class Producer { 9 | 10 | private final KafkaTemplate kafkaTemplate; 11 | 12 | public Producer(KafkaTemplate kafkaTemplate) { 13 | super(); 14 | this.kafkaTemplate = kafkaTemplate; 15 | } 16 | 17 | // public void send(TestMessage message) { 18 | // this.kafkaTemplate.send("test2", message); 19 | // System.out.println("Sent sample message [" + message + "]"); 20 | // } 21 | 22 | public void send(String message) { 23 | this.kafkaTemplate.send("test2", message); 24 | System.out.println("11111111111 Sent sample str message [" + message + "]"); 25 | } 26 | 27 | public void send2(String message) { 28 | TestMessage testMessage = new TestMessage(11, message); 29 | this.kafkaTemplate.send("test2", testMessage); 30 | System.out.println("22222222222 Sent2 sample str message [" + testMessage + "]"); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Kafka/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | I am a banner!!! -------------------------------------------------------------------------------- /Kafka/src/main/resources/config/application-consumer.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/Kafka/src/main/resources/config/application-consumer.properties -------------------------------------------------------------------------------- /Kafka/src/main/resources/config/application-producer.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/Kafka/src/main/resources/config/application-producer.properties -------------------------------------------------------------------------------- /Kafka/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J\u914d\u7f6e 2 | log4j.rootCategory=INFO,stdout,file 3 | log4j.logger.com.cml.springboot.framework.interceptor=INFO,logfile 4 | log4j.logger.org.mybatis.spring.SqlSessionFactoryBean=ALL,stdout,logfile 5 | 6 | ###\u663e\u793aSQL\u8bed\u53e5\u90e8\u5206 7 | #log4j.logger.org.mybatis=ALL 8 | #log4j.logger.org.apache=ALL 9 | #log4j.logger.org.apache.ibatis.logging.jdbc=ALL 10 | #log4j.logger.java.sql=ALL 11 | #log4j.logger.com.cml.springboot=ALL 12 | 13 | # \u63a7\u5236\u53f0\u8f93\u51fa 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 17 | 18 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 19 | log4j.appender.file=org.apache.log4j.DailyRollingFileAppender 20 | log4j.appender.file.file=logs/springboot.log 21 | log4j.appender.file.DatePattern='.'yyyy-MM-dd 22 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 23 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 24 | 25 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 26 | log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender 27 | log4j.appender.logfile.file=logs/api.log 28 | log4j.appender.logfile.DatePattern='.'yyyy-MM-dd 29 | log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 30 | log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /Kafka/src/main/resources/public/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 404 8 | 9 | -------------------------------------------------------------------------------- /Kafka/src/main/test/com/cml/springboot/test/TestConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.test; 2 | 3 | public class TestConfiguration { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /LearnCache/src/main/java/com/cml/learn/CacheApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.cache.annotation.EnableCaching; 5 | 6 | @SpringBootApplication 7 | @EnableCaching 8 | public class CacheApplication { 9 | } 10 | -------------------------------------------------------------------------------- /LearnTest/src/main/java/com/cml/learn/test/AService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class AService { 8 | 9 | private CService cService; 10 | private BService bService; 11 | 12 | @Autowired 13 | public AService(CService cService, BService bService) { 14 | this.cService = cService; 15 | this.bService = bService; 16 | } 17 | 18 | public void doSmthing() { 19 | System.out.println("AService doSmthing"); 20 | System.out.println(bService.doSmthing()); 21 | System.out.println(cService.doSmthing()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LearnTest/src/main/java/com/cml/learn/test/BService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class BService { 7 | public String doSmthing() { 8 | return "ServiceBDoSmthing"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LearnTest/src/main/java/com/cml/learn/test/CService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class CService { 7 | public String doSmthing() { 8 | return "ServiceCDoSmthing"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LearnTest/src/main/java/com/cml/learn/test/DService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service 7 | public class DService { 8 | @Value("${config.username}") 9 | private String username; 10 | 11 | public String doSmthing() { 12 | return username+" doSmthing"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LearnTest/src/main/java/com/cml/learn/test/Main.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.springframework.boot.ApplicationRunner; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Bean; 7 | 8 | @SpringBootApplication 9 | public class Main { 10 | public static void main(String[] args) { 11 | SpringApplication.run(Main.class, args); 12 | } 13 | 14 | @Bean 15 | public ApplicationRunner applicationRunner() throws InterruptedException { 16 | System.out.println("===================模拟延迟--------------------"); 17 | Thread.sleep(30000); 18 | return args -> { 19 | System.out.println("===================模拟延迟启动--------------------"); 20 | }; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/AServiceMockTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.mockito.Mockito; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.mock.mockito.MockBean; 9 | import org.springframework.test.context.ContextConfiguration; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | @RunWith(SpringRunner.class) 13 | @ContextConfiguration(classes = { 14 | AService.class 15 | }) 16 | public class AServiceMockTest { 17 | @Autowired 18 | private AService aService; 19 | @MockBean 20 | private BService bService; 21 | @MockBean 22 | private CService cService; 23 | 24 | @Before 25 | public void setUp() { 26 | Mockito.when(bService.doSmthing()).thenReturn("mockBServce"); 27 | Mockito.when(cService.doSmthing()).thenReturn("mockCServce"); 28 | } 29 | 30 | @Test 31 | public void test() { 32 | aService.doSmthing(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/AServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.test.context.ContextConfiguration; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | @RunWith(SpringRunner.class) 10 | @ContextConfiguration(classes = { 11 | AService.class, 12 | BService.class, 13 | CService.class 14 | }) 15 | public class AServiceTest { 16 | @Autowired 17 | private AService aService; 18 | 19 | 20 | @Test 21 | public void test() { 22 | aService.doSmthing(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/BServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 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.test.context.ContextConfiguration; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @ContextConfiguration(classes = BService.class) 12 | public class BServiceTest { 13 | 14 | @Autowired 15 | private BService bService; 16 | 17 | @Test 18 | public void testDoSmthin() { 19 | String smthing = bService.doSmthing(); 20 | System.out.println("===============>" + smthing); 21 | Assert.assertTrue(smthing != null); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/DServicePropertiesFileTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 7 | import org.springframework.test.context.ContextConfiguration; 8 | import org.springframework.test.context.TestPropertySource; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | @RunWith(SpringRunner.class) 12 | @ContextConfiguration(classes = { 13 | DService.class, 14 | PropertySourcesPlaceholderConfigurer.class 15 | }) 16 | @TestPropertySource("classpath:application.properties") 17 | public class DServicePropertiesFileTest { 18 | @Autowired 19 | private DService dService; 20 | 21 | @Test 22 | public void test() { 23 | String result = dService.doSmthing(); 24 | System.out.println(result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/DServicePropertiesTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; 7 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 8 | import org.springframework.test.context.ContextConfiguration; 9 | import org.springframework.test.context.TestPropertySource; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | @RunWith(SpringRunner.class) 13 | @ContextConfiguration(classes = { 14 | DService.class, 15 | PropertySourcesPlaceholderConfigurer.class 16 | }, initializers = ConfigFileApplicationContextInitializer.class) 17 | public class DServicePropertiesTest { 18 | @Autowired 19 | private DService dService; 20 | 21 | @Test 22 | public void test() { 23 | String result = dService.doSmthing(); 24 | System.out.println(result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/DServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 7 | import org.springframework.test.context.ContextConfiguration; 8 | import org.springframework.test.context.TestPropertySource; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | @RunWith(SpringRunner.class) 12 | @ContextConfiguration(classes = { 13 | DService.class, 14 | PropertySourcesPlaceholderConfigurer.class 15 | }) 16 | @TestPropertySource(properties = {"config.username=myUsername"}) 17 | public class DServiceTest { 18 | @Autowired 19 | private DService dService; 20 | 21 | @Test 22 | public void test() { 23 | String result = dService.doSmthing(); 24 | System.out.println(result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LearnTest/src/test/java/com/cml/learn/test/MainTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.test; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest(classes = Main.class) 12 | public class MainTest { 13 | @Autowired 14 | private AService aService; 15 | 16 | @Before 17 | public void before() { 18 | System.out.println("start============="); 19 | } 20 | 21 | @Test 22 | public void testStartUp() { 23 | aService.doSmthing(); 24 | System.out.println("--------------测试----------"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LearnTest/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | config.username=properties username -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot Learning # 2 | 3 | 此项目主要作为SpringBoot学习,和根据实际项目对SpringBoot进行配置改造 4 | 主要使用框架:SpringBoot(Spring,SpringMVC),MyBatis,Ehcache,Rabbitmq,JavaMail。 5 | 项目持续维护中... 6 | 7 | # 全新的参数缓存框架 8 | 9 | 一个专注于提升管理页面开发难度的参数缓存框架,简化参数保存流程,支持分布式与集群拓展,详见:https://github.com/cmlbeliever/cacheable-search 10 | 11 | # 博客资源 # 12 | - Mybatis打包jar后无法扫描到bean与mapper问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/53138851 13 | - 163发送邮件功能问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/54235510 14 | 15 | # 项目结构 # 16 | - web项目整合了多种web项目需求功能,详情[点我跳转](../../tree/master/web "点我跳转") 17 | - rabbitmq项目是对rabbitmq框架整合Spring的学习与研发的工程,详情[点我跳转](../../tree/master/rabbitmq "点我跳转") 18 | - RabbitmqSpringBoot项目是对rabbitmq框架整合SpringBoot的学习与研发的工程,详情[点我跳转](../../tree/master/RabbitmqSpringBoot "点我跳转") 19 | - DynamicDataSource项目是db自动对读写分离整合SpringBoot的学习与研发的工程,详情[点我跳转](../../tree/master/DynamicDataSource "点我跳转") 20 | - SpringJpa项目是使用Spring-Data-Jpa,进行数据操作,实现读写分离功能。详情[点我跳转](../../tree/master/SpringJpa "点我跳转") 21 | - Async: Async使用与线程池测试详情[点我跳转](../../tree/master/Async "点我跳转") 22 | 23 | # rabbitmq工程说明 # 24 | 以Spring与Spring的方式整合rabbitmq 25 | 26 | # RabbitmqSpringBoot # 27 | 以Spring与SpringBoot的方式整合rabbitmq 28 | 29 | # web工程说明 # 30 | 整合了web开发常用的功能与框架,如Shiro,I18n,邮件,mybatis等功能。 31 | 32 | # DynamicDataSource工程说明 # 33 | 通过AbstractRoutingDataSource对DB动态读写分离,博客地址:http://blog.csdn.net/cml_blog/article/details/78224798 34 | 35 | # Async工程说明 # 36 | @Async 使用场景和线程使用说明,博客地址:https://blog.csdn.net/cml_blog/article/details/80849728 37 | 38 | #web工程问题与解决# 39 | - Mybatis打包jar后无法扫描到bean与mapper问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/53138851 40 | - 163发送邮件功能问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/54235510 41 | 42 | 43 | # 更多信息请查看wiki # 44 | 45 | 46 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.settings/ 6 | .classpath -------------------------------------------------------------------------------- /RabbitmqSpringBoot/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | RabbitmqSpringBoot 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | org.eclipse.wst.common.project.facet.core.nature 34 | 35 | 36 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/README.MD: -------------------------------------------------------------------------------- 1 | # rabbitmq项目说明 # 2 | 通过pringBoot方式整合,完成rabbitmq基本消息发送与接收功能,TODO 3 | 4 | # 项目运行要求 # 5 | - 正确安装好rabbitmq 6 | - 正确配置好config/rabbitmq/rabbitmq.properties中rabbitmq连接信息 7 | 8 | # 基于docker的rabbitmq环境安装 # 9 | 1. 获取镜像: docker pull rabbitmq:management 10 | 2. 执行镜像 11 | docker run -d --name rabbitmq --publish 5671:5671 \ 12 | --publish 5672:5672 --publish 4369:4369 --publish 25672:25672 --publish 15671:15671 --publish 15672:15672 \rabbitmq:management 13 | 1. 查看docker容器ip:docker-machine ip 14 | 2. 根据获取的ip,在浏览器上访问:http://${ip}:15672 打开管理页面,则说明rabbitmq安装成功 15 | ![](screenshots/rabbit-admin.png) 16 | 17 | # 整合SpringBoot工程说明 # 18 | 19 | # src/main/resource说明 # 20 | 1. config/rabbitmq/rabbitmq.properties是对rabbitmq的基本信息配置 21 | 2. application.properties 是SpringBoot配置文件 22 | 3. logback-spring.xml为log配置文件,默认为INFO级别的控制台输出。 23 | 24 | # 项目运行 # 25 | - 直接运行Application类,可以看到控制台发送消息与接收消息的log。发送Rabbitmq消息,已有fanout,direct,topic。 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/classpath: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/RabbitmqSpringBoot/classpath -------------------------------------------------------------------------------- /RabbitmqSpringBoot/screenshots/rabbit-admin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/RabbitmqSpringBoot/screenshots/rabbit-admin.png -------------------------------------------------------------------------------- /RabbitmqSpringBoot/screenshots/receiver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/RabbitmqSpringBoot/screenshots/receiver.png -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/java/com/cml/learning/rabbitmq/spring/constant/PlaceHolderConst.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.constant; 2 | 3 | public interface PlaceHolderConst { 4 | interface Queues { 5 | String manualTopicQueue = "${rabbitmq.exchange.manualTopic.queue}"; 6 | String mailDirectQueue = "${rabbitmq.exchange.direct.queue}"; 7 | String mailFanoutQueue = "${rabbitmq.exchange.fanout.queue}"; 8 | } 9 | 10 | interface Exchanges { 11 | String mailFanoutExchange = "${rabbitmq.exchange.fanout}"; 12 | String manualTopicExchange = "${rabbitmq.exchange.manualTopic}"; 13 | String maildirectExchange = "${rabbitmq.exchange.direct}"; 14 | } 15 | 16 | interface Routes { 17 | String mailTopicRoute = "${rabbitmq.exchange.manualTopic.route}"; 18 | String mailDirectRoute = "${rabbitmq.exchange.direct.route}"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/java/com/cml/learning/rabbitmq/spring/model/EmailModel.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.model; 2 | 3 | public class EmailModel { 4 | private String to; 5 | private String title; 6 | private String content; 7 | 8 | public String getTo() { 9 | return to; 10 | } 11 | 12 | public void setTo(String to) { 13 | this.to = to; 14 | } 15 | 16 | public String getTitle() { 17 | return title; 18 | } 19 | 20 | public void setTitle(String title) { 21 | this.title = title; 22 | } 23 | 24 | public String getContent() { 25 | return content; 26 | } 27 | 28 | public void setContent(String content) { 29 | this.content = content; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "EmailModel [to=" + to + ", title=" + title + ", content=" + content + "]"; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/java/com/cml/learning/rabbitmq/spring/service/MailService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.service; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public interface MailService { 6 | void sendTopicEmail(String routeKey,EmailModel model); 7 | 8 | void sendDirectEmail(String routeKey,EmailModel model); 9 | 10 | void sendFanoutEmail(String routeKey,EmailModel model); 11 | } 12 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/java/com/cml/learning/rabbitmq/spring/service/MailServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.service; 2 | 3 | import org.springframework.amqp.core.AmqpTemplate; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.stereotype.Component; 7 | 8 | import com.cml.learning.rabbitmq.spring.constant.PlaceHolderConst; 9 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 10 | 11 | @Component 12 | public class MailServiceImpl implements MailService { 13 | @Autowired 14 | private AmqpTemplate template; 15 | 16 | @Value(PlaceHolderConst.Exchanges.manualTopicExchange) 17 | private String topicExchange; 18 | @Value(PlaceHolderConst.Exchanges.maildirectExchange) 19 | private String directExchange; 20 | @Value(PlaceHolderConst.Exchanges.mailFanoutExchange) 21 | private String fanoutExchange; 22 | 23 | public MailServiceImpl(AmqpTemplate template) { 24 | super(); 25 | this.template = template; 26 | } 27 | 28 | @Override 29 | public void sendTopicEmail(String routeKey, EmailModel model) { 30 | template.convertAndSend(topicExchange, routeKey, model); 31 | } 32 | 33 | @Override 34 | public void sendDirectEmail(String routeKey, EmailModel model) { 35 | template.convertAndSend(directExchange, routeKey, model); 36 | } 37 | 38 | @Override 39 | public void sendFanoutEmail(String routeKey, EmailModel model) { 40 | template.convertAndSend(fanoutExchange, routeKey, model); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.rabbitmq.host=192.168.99.100 2 | spring.rabbitmq.port=5672 3 | spring.rabbitmq.username=guest 4 | spring.rabbitmq.password=guest 5 | 6 | #logging.level.root=INFO 7 | -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/resources/config/rabbitmq/rabbitmq.properties: -------------------------------------------------------------------------------- 1 | rabbitmq.host=192.168.99.100 2 | rabbitmq.username=guest 3 | rabbitmq.password=guest 4 | rabbitmq.channelCacheSize=25 5 | rabbitmq.exchange=myexchange2 6 | 7 | #MANUAL TOPIC\u6D88\u606F 8 | rabbitmq.exchange.manualTopic=manualTopic 9 | rabbitmq.exchange.manualTopic.queue=manualTopicQueue 10 | rabbitmq.exchange.manualTopic.route=mailManul.* 11 | 12 | #direct\u5F62\u5F0F\u6D88\u606F\u53D1\u9001 13 | rabbitmq.exchange.direct=maildirect 14 | rabbitmq.exchange.direct.queue=mailDirectQueue 15 | rabbitmq.exchange.direct.route=mail 16 | 17 | #Fanout\u5F62\u5F0F\u6D88\u606F 18 | rabbitmq.exchange.fanout=mailFanout 19 | rabbitmq.exchange.fanout.queue=mailFanoutQueue -------------------------------------------------------------------------------- /RabbitmqSpringBoot/src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 10 | ${APP_NAME} 11 | 12 | 13 | 14 | 15 | ${ENCODER_PATTERN} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Redis/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.settings/ 6 | .classpath -------------------------------------------------------------------------------- /Redis/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | redis 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.m2e.core.maven2Builder 20 | 21 | 22 | 23 | 24 | org.springframework.ide.eclipse.core.springbuilder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | org.eclipse.wst.common.project.facet.core.nature 34 | 35 | 36 | -------------------------------------------------------------------------------- /Redis/README.MD: -------------------------------------------------------------------------------- 1 | # Redis项目说明 # 2 | 通过pringBoot方式整合,完成Redis基本消息发送与接收功能 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Redis/src/main/java/com/cml/learn/redis/Application.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.redis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | public static void main(String[] args) throws Exception { 9 | SpringApplication.run(Application.class, args); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Redis/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster. 2 | #spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from. 3 | #spring.redis.database=0 # Database index used by the connection factory. 4 | #spring.redis.host=localhost # Redis server host. 5 | #spring.redis.password= # Login password of the redis server. 6 | #spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. 7 | #spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. 8 | #spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. 9 | #spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. 10 | #spring.redis.port=6379 # Redis server port. 11 | #spring.redis.sentinel.master= # Name of Redis server. 12 | #spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs. 13 | #spring.redis.timeout=0 # Connection timeout in milliseconds. 14 | spring.redis.host=192.168.99.100 15 | spring.redis.timeout=10000 16 | debug=false 17 | spring.cache.type=redis 18 | 19 | spring.cache.cache-names=name -------------------------------------------------------------------------------- /Redis/src/test/java/com/cml/learn/redis/test/BasicCacheTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.redis.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import com.cml.learn.redis.Application; 10 | import com.cml.learn.redis.CacheService; 11 | 12 | /** 13 | * 缓存删除与测试 14 | * @author cml 15 | * 16 | */ 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest(classes = Application.class) 19 | public class BasicCacheTest { 20 | @Autowired 21 | private CacheService service; 22 | 23 | @Test 24 | public void testBasicCache() { 25 | System.out.println("update:" + service.updateUsername("username")); 26 | System.out.println("select:" + service.getName4()); 27 | service.deleteCache(); 28 | System.out.println("cache deleted!!!"); 29 | System.out.println("select:" + service.getName4()); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Redis/src/test/java/com/cml/learn/redis/test/ConcurrentCacheTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.redis.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import com.cml.learn.redis.Application; 10 | import com.cml.learn.redis.CacheService; 11 | 12 | /** 13 | * 高并发下缓存测试 14 | * 15 | * @author cml 16 | * 17 | */ 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(classes = Application.class) 20 | public class ConcurrentCacheTest { 21 | @Autowired 22 | private CacheService service; 23 | 24 | @Test 25 | public void testConcurrentCache() throws Exception { 26 | final int index = 8; 27 | for (int i = 0; i < 10; i++) { 28 | new Thread(new Runnable() { 29 | 30 | @Override 31 | public void run() { 32 | System.out.println(service.getUser("key" + index)); 33 | } 34 | }).start(); 35 | } 36 | Thread.sleep(10000); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RestMvc/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.idea/ 6 | /.settings/ -------------------------------------------------------------------------------- /RestMvc/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | RestMvc 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | org.eclipse.wst.common.project.facet.core.nature 34 | 35 | 36 | -------------------------------------------------------------------------------- /RestMvc/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | java:com.cml.springboot.main.BootApplication 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /RestMvc/README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot Learning # 2 | 3 | 此项目主作为各种技术调试使用,请忽略 -------------------------------------------------------------------------------- /RestMvc/screenshots/structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/RestMvc/screenshots/structure.png -------------------------------------------------------------------------------- /RestMvc/src/main/i18n/messages.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to default -------------------------------------------------------------------------------- /RestMvc/src/main/i18n/messages_en_US.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to english -------------------------------------------------------------------------------- /RestMvc/src/main/i18n/messages_zh_CN.properties: -------------------------------------------------------------------------------- 1 | welcome=\u6b22\u8fce\u6765\u5230\u4e2d\u56fd -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/BootApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 6 | import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; 7 | import org.springframework.context.annotation.ComponentScan; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.PropertySource; 10 | import org.springframework.context.annotation.PropertySources; 11 | import org.springframework.scheduling.annotation.EnableAsync; 12 | 13 | @Configuration 14 | @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) 15 | @ComponentScan() 16 | @EnableAsync 17 | @PropertySources({ @PropertySource("classpath:config/application-jdbc.properties") }) 18 | public class BootApplication { 19 | 20 | // @Bean 21 | // public PropertyPlaceholderConfigurer placeHolder() { 22 | // 23 | // PropertyPlaceholderConfigurer configure = new 24 | // PropertyPlaceholderConfigurer(); 25 | // configure.setLocations(null); 26 | // 27 | // return configure; 28 | // } 29 | 30 | public static void main(String[] args) throws Exception { 31 | SpringApplication.run(BootApplication.class, args); 32 | // WebMvcAutoConfiguration 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/AsyncTaskConfig.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | import java.util.concurrent.Executor; 4 | 5 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.scheduling.annotation.AsyncConfigurer; 9 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 10 | 11 | @Configuration 12 | public class AsyncTaskConfig implements AsyncConfigurer { 13 | 14 | @Value("${async.task.config.corePoolSize}") 15 | private Integer corePoolSize; 16 | @Value("${async.task.config.maxPoolSize}") 17 | private Integer maxPoolSize; 18 | 19 | @Override 20 | public Executor getAsyncExecutor() { 21 | 22 | ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor(); 23 | ex.setCorePoolSize(corePoolSize); 24 | ex.setMaxPoolSize(maxPoolSize); 25 | ex.initialize(); 26 | return ex; 27 | } 28 | 29 | @Override 30 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 31 | return null; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/Configuration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | public interface Configuration { 4 | interface Status { 5 | int STATUS_OK = 1; 6 | int STATUS_FAIL = 2; 7 | int STATUS_INVALID_TOKEN = 3; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/argument/CacheableModelMethodProcessor.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.argument; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.ui.Model; 5 | import org.springframework.ui.ModelMap; 6 | import org.springframework.web.bind.support.WebDataBinderFactory; 7 | import org.springframework.web.context.request.NativeWebRequest; 8 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 9 | import org.springframework.web.method.support.ModelAndViewContainer; 10 | 11 | public class CacheableModelMethodProcessor implements HandlerMethodArgumentResolver { 12 | 13 | @Override 14 | public boolean supportsParameter(MethodParameter parameter) { 15 | return Model.class.isAssignableFrom(parameter.getParameterType()); 16 | } 17 | 18 | @Override 19 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, 20 | WebDataBinderFactory binderFactory) throws Exception { 21 | ModelMap map = mavContainer.getModel(); 22 | System.out.println("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"); 23 | webRequest.setAttribute("dddddddddddd", map, NativeWebRequest.SCOPE_REQUEST); 24 | return map; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/argument/CustomModelArgumentResolverConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.argument; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import javax.annotation.PostConstruct; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 12 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; 13 | 14 | /** 15 | * 添加自定义argumentResolver可以覆盖系统默认处理 16 | * 17 | * @author cml 18 | * 19 | */ 20 | @Component 21 | public class CustomModelArgumentResolverConfiguration { 22 | 23 | @Autowired 24 | private RequestMappingHandlerAdapter requestMappingHandlerAdapter; 25 | 26 | /** 27 | * 覆盖系统默认的处理器 28 | */ 29 | @PostConstruct 30 | public void afterProperties() { 31 | List argumentResolvers = new ArrayList<>(requestMappingHandlerAdapter.getArgumentResolvers()); 32 | argumentResolvers.add(0, new CacheableModelMethodProcessor()); 33 | requestMappingHandlerAdapter.setArgumentResolvers(argumentResolvers); 34 | } 35 | 36 | @Bean 37 | public RequestMappingHandlerAdapter adapter(RequestMappingHandlerAdapter adapter) { 38 | List argumentResolvers = new ArrayList<>(adapter.getArgumentResolvers()); 39 | argumentResolvers.add(0, new CacheableModelMethodProcessor()); 40 | adapter.setArgumentResolvers(argumentResolvers); 41 | return adapter; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.controller; 2 | 3 | import org.springframework.validation.Errors; 4 | import org.springframework.validation.ObjectError; 5 | 6 | import com.cml.springboot.framework.Configuration; 7 | 8 | public class BaseController { 9 | 10 | public static final int SUCCESS = Configuration.Status.STATUS_OK; 11 | public static final int FAIL = Configuration.Status.STATUS_FAIL; 12 | 13 | public static String getAllErrors(Errors errors) { 14 | StringBuilder builder = new StringBuilder(); 15 | for (ObjectError error : errors.getAllErrors()) { 16 | builder.append(error.getDefaultMessage()).append("\n"); 17 | } 18 | return builder.toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/deserializer/DateTimeDeserializer.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.deserializer; 2 | 3 | import java.io.IOException; 4 | 5 | import org.joda.time.DateTime; 6 | import org.joda.time.format.DateTimeFormat; 7 | import org.joda.time.format.DateTimeFormatter; 8 | import org.springframework.format.datetime.joda.DateTimeFormatterFactory; 9 | 10 | import com.fasterxml.jackson.core.JsonGenerator; 11 | import com.fasterxml.jackson.core.JsonProcessingException; 12 | import com.fasterxml.jackson.databind.JsonSerializer; 13 | import com.fasterxml.jackson.databind.SerializerProvider; 14 | 15 | public class DateTimeDeserializer extends JsonSerializer { 16 | 17 | private String format = "yyyyMMddHHmmss"; 18 | 19 | public DateTimeDeserializer() { 20 | System.out.println("===================================================dddddddddddddddddddddddddddddddddddd"); 21 | } 22 | 23 | public DateTimeDeserializer(String format) { 24 | super(); 25 | this.format = format; 26 | } 27 | 28 | @Override 29 | public void serialize(DateTime value, JsonGenerator gen, SerializerProvider serializers) 30 | throws IOException, JsonProcessingException { 31 | if (null != value) { 32 | gen.writeString(value.toString(format)); 33 | } 34 | System.out.println("=============================="); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/mybatis/MybatisScanConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.mybatis.spring.annotation.MapperScan; 6 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | @AutoConfigureAfter(MybatisConfig.class) 11 | @MapperScan(basePackages = { "com.cml.springboot.sample.db" }, sqlSessionFactoryRef = "sqlSessionFactory") 12 | public class MybatisScanConfiguration { 13 | protected static Log log = LogFactory.getLog(MybatisScanConfiguration.class); 14 | 15 | public MybatisScanConfiguration() { 16 | log.info("*************************MybatisScanConfiguration***********************"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/mybatis/SpringBootVFS.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.apache.ibatis.io.VFS; 10 | import org.springframework.core.io.Resource; 11 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 12 | import org.springframework.core.io.support.ResourcePatternResolver; 13 | 14 | public class SpringBootVFS extends VFS { 15 | 16 | private final ResourcePatternResolver resourceResolver; 17 | 18 | public SpringBootVFS() { 19 | this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); 20 | } 21 | 22 | @Override 23 | public boolean isValid() { 24 | return true; 25 | } 26 | 27 | @Override 28 | protected List list(URL url, String path) throws IOException { 29 | Resource[] resources = resourceResolver.getResources("classpath*:" + path + "/**/*.class"); 30 | List resourcePaths = new ArrayList(); 31 | for (Resource resource : resources) { 32 | resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); 33 | } 34 | return resourcePaths; 35 | } 36 | 37 | private static String preserveSubpackageName(final URI uri, final String rootPath) { 38 | final String uriStr = uri.toString(); 39 | final int start = uriStr.indexOf(rootPath); 40 | return uriStr.substring(start); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/response/BaseResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | public class BaseResponse { 4 | private Integer code; 5 | private String message; 6 | 7 | public BaseResponse() { 8 | } 9 | 10 | public BaseResponse(Integer code, String message) { 11 | super(); 12 | this.code = code; 13 | this.message = message; 14 | } 15 | 16 | public Integer getCode() { 17 | return code; 18 | } 19 | 20 | public void setCode(Integer code) { 21 | this.code = code; 22 | } 23 | 24 | public String getMessage() { 25 | return message; 26 | } 27 | 28 | public void setMessage(String message) { 29 | this.message = message; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/response/BaseResponseAdvise.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.converter.HttpMessageConverter; 8 | import org.springframework.http.server.ServerHttpRequest; 9 | import org.springframework.http.server.ServerHttpResponse; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 12 | 13 | //@ControllerAdvice() 14 | public class BaseResponseAdvise implements ResponseBodyAdvice { 15 | 16 | private static Log log = LogFactory.getLog(BaseResponseAdvise.class); 17 | 18 | @Override 19 | public boolean supports(MethodParameter returnType, Class> converterType) { 20 | log.info("===>" + (returnType.getGenericParameterType() instanceof BaseResponse)); 21 | return returnType.getGenericParameterType() == BaseResponse.class; 22 | } 23 | 24 | @Override 25 | public BaseResponse beforeBodyWrite(BaseResponse body, MethodParameter returnType, MediaType selectedContentType, 26 | Class> selectedConverterType, ServerHttpRequest request, 27 | ServerHttpResponse response) { 28 | // body.setMessage("被我修改了"); 29 | return body; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/response/MethodResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.context.request.NativeWebRequest; 6 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 7 | import org.springframework.web.method.support.ModelAndViewContainer; 8 | 9 | @Component 10 | public class MethodResponseHandler implements HandlerMethodReturnValueHandler { 11 | 12 | @Override 13 | public boolean supportsReturnType(MethodParameter returnType) { 14 | System.out.println("=====================? supportsReturnType"); 15 | return true; 16 | } 17 | 18 | @Override 19 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, 20 | NativeWebRequest webRequest) throws Exception { 21 | System.out.println("====================> handleReturnValue"); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/rest/RestMvcAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.rest; 2 | 3 | import javax.annotation.PostConstruct; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 10 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 11 | 12 | @Component 13 | @Configuration 14 | public class RestMvcAutoConfiguration { 15 | @Autowired 16 | RequestMappingHandlerMapping mapping; 17 | 18 | @PostConstruct 19 | public void config() throws Exception, SecurityException { 20 | RequestMappingInfo info = RequestMappingInfo.paths("/test/hh/name").mappingName("mine").build(); 21 | mapping.registerMapping(info, new TestMvc(), TestMvc.class.getDeclaredMethod("testA", String.class)); 22 | System.out.println("===========xxxxxxxxxxxxxxxxxxxxxxxxxxx=============="); 23 | } 24 | // 25 | // @Bean 26 | // public RequestMappingHandlerMapping handlerMapping() throws Exception { 27 | // RequestMappingHandlerMapping mapping = new 28 | // RequestMappingHandlerMapping(); 29 | // RequestMappingInfo info = 30 | // RequestMappingInfo.paths("/test/hh/name").mappingName("mine").build(); 31 | // mapping.registerMapping(info, new TestMvc(), 32 | // TestMvc.class.getDeclaredMethod("testA", String.class)); 33 | // System.out.println("===========xxxxxxxxxxxxxxxxxxxxxxxxxxx=============="); 34 | // return mapping; 35 | // } 36 | } 37 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/rest/RestMvcTesst.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.rest; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.TYPE) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface RestMvcTesst { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/rest/TestMvc.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.rest; 2 | 3 | import org.springframework.web.bind.annotation.ResponseBody; 4 | 5 | @RestMvcTesst 6 | public class TestMvc { 7 | @ResponseBody 8 | public String testA(String name) { 9 | return "dddd" + name; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/transaction/TransactionService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.transaction; 2 | 3 | import javax.annotation.Resource; 4 | import javax.sql.DataSource; 5 | 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 9 | import org.springframework.transaction.PlatformTransactionManager; 10 | import org.springframework.transaction.annotation.EnableTransactionManagement; 11 | 12 | @Configuration 13 | @EnableTransactionManagement() 14 | public class TransactionService { 15 | 16 | @Resource 17 | private DataSource dataSource; 18 | 19 | @Bean(name = "txManager") 20 | public PlatformTransactionManager txManager() { 21 | return new DataSourceTransactionManager(dataSource); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/util/LogUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | public class LogUtil { 4 | 5 | private static final String FORMAT_CONTROLLER = "《《《《%s》》》》====>%s"; 6 | 7 | public static String formatControllerLog(Object controller, String log) { 8 | return String.format(FORMAT_CONTROLLER, controller.getClass().getSimpleName(), log); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/util/MD5.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class MD5 { 6 | public static String getMD5(String source) { 7 | String s = null; 8 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 9 | 'a', 'b', 'c', 'd', 'e', 'f' }; 10 | try { 11 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 12 | md5.update(source.getBytes()); 13 | byte tmp[] = md5.digest(); 14 | char str[] = new char[16 * 2]; 15 | int k = 0; 16 | for (int i = 0; i < 16; i++) { 17 | byte byte0 = tmp[i]; 18 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 19 | str[k++] = hexDigits[byte0 & 0xf]; 20 | } 21 | s = new String(str); 22 | 23 | } catch (Exception ex) { 24 | ex.printStackTrace(); 25 | } 26 | return s; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/framework/util/UUIDUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class UUIDUtil { 6 | 7 | public static final String generateUUID() { 8 | return UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/bean/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.bean; 2 | 3 | import com.cml.springboot.framework.response.BaseResponse; 4 | 5 | public class UserResponse extends BaseResponse { 6 | private User user; 7 | 8 | public UserResponse(Integer code, String message, User user) { 9 | super(code, message); 10 | this.user = user; 11 | } 12 | 13 | public UserResponse(Integer code, User user) { 14 | super(code, null); 15 | this.user = user; 16 | } 17 | 18 | public User getUser() { 19 | return user; 20 | } 21 | 22 | public void setUser(User user) { 23 | this.user = user; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/controller/ModelAttributeController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.controller; 2 | 3 | import java.sql.SQLException; 4 | 5 | import javax.annotation.Resource; 6 | import javax.validation.Valid; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.ModelAttribute; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import com.cml.springboot.sample.bean.User; 16 | import com.cml.springboot.sample.service.UserService; 17 | 18 | /** 19 | * ModelAttribute demo 20 | * 21 | * @author team-lab 22 | * 23 | */ 24 | @Controller 25 | @RequestMapping("/model") 26 | public class ModelAttributeController { 27 | 28 | @Resource(name = "userServiceImpl") 29 | private UserService userService; 30 | 31 | @ModelAttribute("user") 32 | public User user(@RequestParam String token) throws SQLException { 33 | System.out.println("==================================================token:"+token); 34 | if (StringUtils.isBlank(token)) { 35 | return null; 36 | } 37 | return userService.findUserByToken(token); 38 | } 39 | 40 | @RequestMapping("/testA") 41 | @ResponseBody 42 | public String testA(@ModelAttribute() User user) { 43 | if (user == null) { 44 | return "user is null!!!!"; 45 | } 46 | return "user:" + user.getUsername() + "," + user.getNickName(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/db/LogMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogMapper { 6 | void insertLog(LogBean logbean); 7 | } 8 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/db/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserMapper { 8 | User getUserByToken(String token) throws SQLException; 9 | 10 | User getUser(User user); 11 | 12 | Integer updateToken(User loginUser); 13 | } 14 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/db/resource/log.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | INSERT INTO t_api_log ( 7 | call_day, 8 | parameters, 9 | return_status_code, 10 | returns, 11 | api_url, 12 | create_date, 13 | update_date 14 | 15 | ) 16 | VALUES ( 17 | #{callDayStr}, 18 | #{parameters}, 19 | #{returnStatusCode}, 20 | #{returns}, 21 | #{apiUrl}, 22 | #{createDate}, 23 | NOW() 24 | ) 25 | 26 | 27 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/db/resource/user.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | 35 | 36 | 37 | UPDATE 38 | t_user 39 | SET 40 | token = #{newToken} 41 | WHERE 42 | token = #{token} 43 | 44 | 45 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/service/LogService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogService { 6 | void insertLog(LogBean logbean); 7 | 8 | void insertLogReadOnly(LogBean logbean); 9 | } 10 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserService { 8 | User findUserByToken(String token) throws SQLException; 9 | 10 | User login(User user) throws Exception; 11 | } 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/service/impl/LogServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service.impl; 2 | 3 | import org.joda.time.DateTime; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.scheduling.annotation.Async; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.cml.springboot.sample.bean.LogBean; 10 | import com.cml.springboot.sample.db.LogMapper; 11 | import com.cml.springboot.sample.service.LogService; 12 | 13 | @Service("logServiceImpl") 14 | @Transactional 15 | public class LogServiceImpl implements LogService { 16 | 17 | @Autowired 18 | private LogMapper logMapper; 19 | 20 | @Override 21 | @Async 22 | public void insertLog(LogBean logbean) { 23 | System.out.println("LogServiceImpl.insertLog threadId:" + Thread.currentThread().getId() + "," 24 | + Thread.currentThread().getName()); 25 | logbean.setCreateDate(new DateTime()); 26 | logMapper.insertLog(logbean); 27 | } 28 | 29 | @Transactional(readOnly = true) 30 | @Override 31 | public void insertLogReadOnly(LogBean logbean) { 32 | logbean.setCreateDate(new DateTime()); 33 | logMapper.insertLog(logbean); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /RestMvc/src/main/java/com/cml/springboot/sample/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service.impl; 2 | 3 | import java.sql.SQLException; 4 | 5 | import javax.transaction.Transactional; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.cml.springboot.framework.util.MD5; 11 | import com.cml.springboot.framework.util.UUIDUtil; 12 | import com.cml.springboot.sample.bean.User; 13 | import com.cml.springboot.sample.db.UserMapper; 14 | import com.cml.springboot.sample.service.UserService; 15 | 16 | @Transactional 17 | @Component("userServiceImpl") 18 | public class UserServiceImpl implements UserService { 19 | 20 | @Autowired 21 | private UserMapper userMapper; 22 | 23 | @Override 24 | public User findUserByToken(String token) throws SQLException { 25 | return userMapper.getUserByToken(token); 26 | } 27 | 28 | @Override 29 | public User login(User user) throws Exception { 30 | 31 | user.setPassword(MD5.getMD5(user.getPassword())); 32 | 33 | User loginUser = userMapper.getUser(user); 34 | if (null != loginUser) { 35 | String newToken = UUIDUtil.generateUUID(); 36 | // 重新生成token 37 | user.setNewToken(newToken); 38 | user.setToken(loginUser.getToken()); 39 | int updateCount = userMapper.updateToken(user); 40 | 41 | if (updateCount > 0) { 42 | loginUser.setToken(newToken); 43 | return loginUser; 44 | } 45 | 46 | } 47 | return null; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /RestMvc/src/main/resources/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | user.empty.username=\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7axxxxx -------------------------------------------------------------------------------- /RestMvc/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | I am a banner!!! -------------------------------------------------------------------------------- /RestMvc/src/main/resources/config/application-jdbc.properties: -------------------------------------------------------------------------------- 1 | #-----------mybatis--------------- 2 | #db.mybatis.mapper-locations=classpath*:com/cml/springboot/sample/db/resource/* 3 | #db.mybatis.type-aliases-package=com.cml.springboot.sample.bean 4 | #db.mybatis.type-handler-package=com.cml.springboot.framework.mybatis.typehandler 5 | 6 | 7 | db.mybatis.mapperLocations=classpath*:com/cml/springboot/sample/db/resource/* 8 | db.mybatis.typeAliasesPackage=com.cml.springboot.sample.bean 9 | db.mybatis.typeHandlerPackage=com.cml.springboot.framework.mybatis.typehandler 10 | 11 | db.mybatis.jdbc.driverClassName=com.mysql.jdbc.Driver 12 | db.mybatis.jdbc.url=jdbc:mysql://localhost/springboot?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull 13 | db.mybatis.jdbc.username=root 14 | db.mybatis.jdbc.password=1234 15 | 16 | # \u6700\u5927\u63a5\u7d9a\u6570 17 | db.mybatis.jdbc.maxActive=20 18 | #\u672a\u4f7f\u7528\u306e\u63a5\u7d9a\u3092\u4fdd\u6301\u3059\u308b\u6700\u5927\u6570 19 | db.mybatis.jdbc.maxIdle=2 20 | #\u672a\u4f7f\u7528\u306e\u63a5\u7d9a\u3092\u4fdd\u6301\u3059\u308b\u6700\u5c0f\u6570 21 | db.mybatis.jdbc.minIdle=2 22 | db.mybatis.jdbc.maxWait=1000 23 | #\u521d\u59cb\u521b\u5efa\u8fde\u63a5\u6570 24 | db.mybatis.jdbc.initialSize=2 25 | db.mybatis.jdbc.validationQuery=SELECT 1 26 | 27 | #-----------mybatis--------------- -------------------------------------------------------------------------------- /RestMvc/src/main/resources/config/application.properties: -------------------------------------------------------------------------------- 1 | endpoints.beans.id=springbeans 2 | endpoints.beans.sensitive=false 3 | endpoints.shutdown.enabled=true 4 | 5 | spring.datasource.initialize=false 6 | 7 | # \u81ea\u5b9a\u4e49\u7aef\u53e3 8 | server.port=2222 9 | 10 | #\u5173\u95EDbanner\u8BBE\u7F6E 11 | spring.main.banner-mode=off 12 | 13 | #spring.resources.staticLocations=*\.html,/*.html 14 | #spring.devtools.restart.exclude=static/**,public/**,src/main/webapp/** 15 | 16 | spring.mvc.view.prefix=/ 17 | spring.mvc.view.suffix=.jsp 18 | application.message=Hello Phil 19 | 20 | 21 | #\u5f02\u6b65\u5904\u7406\u914d\u7f6e 22 | async.task.config.corePoolSize=5 23 | async.task.config.maxPoolSize=500 24 | 25 | #\u5f02\u5e38\u8fd4\u56de\u5904\u7406\u914d\u7f6e true\u8868\u793a\u4e0d\u5bf9\u5916\u66b4\u9732\u5f02\u5e38\u4fe1\u606f\uff0c\u53ea\u8fd4\u56de\u56fa\u5b9a\u7684${exception.response.messasge} 26 | exception.response.filter=true 27 | #exception.response.contentType=application/json 28 | exception.response.messasge=exception 29 | 30 | #log\u914d\u7f6e TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. 31 | #logging.file=logs/api.log 32 | #logging.path=logs %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} 33 | #logging.level.root=INFO 34 | #logging.level.org.springframework.web=DEBUG 35 | #logging.level.org.hibernate=ERROR 36 | 37 | 38 | #logging.config=classpath:log4j2.xml -------------------------------------------------------------------------------- /RestMvc/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J\u914d\u7f6e 2 | log4j.rootCategory=info,stdout,file 3 | log4j.logger.com.cml.springboot.framework.interceptor=INFO,logfile 4 | log4j.logger.org.mybatis.spring.SqlSessionFactoryBean=ALL,stdout,logfile 5 | 6 | ###\u663e\u793aSQL\u8bed\u53e5\u90e8\u5206 7 | log4j.logger.org.mybatis=ALL 8 | log4j.logger.org.apache=ALL 9 | log4j.logger.org.apache.ibatis.logging.jdbc=ALL 10 | log4j.logger.java.sql=ALL 11 | log4j.logger.com.cml.springboot=ALL 12 | 13 | # \u63a7\u5236\u53f0\u8f93\u51fa 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 17 | 18 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 19 | log4j.appender.file=org.apache.log4j.DailyRollingFileAppender 20 | log4j.appender.file.file=logs/springboot.log 21 | log4j.appender.file.DatePattern='.'yyyy-MM-dd 22 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 23 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 24 | 25 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 26 | log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender 27 | log4j.appender.logfile.file=logs/api.log 28 | log4j.appender.logfile.DatePattern='.'yyyy-MM-dd 29 | log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 30 | log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /RestMvc/src/main/resources/public/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 404 8 | 9 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/WEB-INF/jsp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 234567890=-"src/main/webapp/test.jsp" 11 | 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/WEB-INF/jsp/welcome.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 5 | 6 | 7 | 8 | 9 | 10 | 11 | Spring URL: ${springUrl} at ${time} 12 |
13 | JSTL URL: ${url} 14 |
15 | Message: ${message} 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

master api demo

9 |

10 | 16 |

注:为了测试方便,将请求url设置为可接受get方式

17 | 18 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/demo.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 4 | 5 | 6 | 7 | 8 | Insert title here 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | errors 11 | 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/static/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

9 | 登录测试 10 | 登录测试 11 | 登录测试 12 | 13 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 23456789 test 11 | 12 | -------------------------------------------------------------------------------- /RestMvc/src/main/webapp/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | upload 8 | 9 |
10 | 11 | 12 |
13 |
14 |
15 | 16 | 17 |
18 | 19 | -------------------------------------------------------------------------------- /RestMvc/src/test/java/com/cml/springboot/controller/test/HelloControllerIT.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import java.net.URL; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.context.embedded.LocalServerPort; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.web.client.TestRestTemplate; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | //@RunWith(SpringRunner.class) 16 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 | public class HelloControllerIT { 18 | 19 | @LocalServerPort 20 | private int port; 21 | 22 | private URL base; 23 | 24 | @Autowired 25 | private TestRestTemplate template; 26 | 27 | @Before 28 | public void setUp() throws Exception { 29 | this.base = new URL("http://localhost:" + port + "/"); 30 | } 31 | 32 | @Test 33 | public void getHello() throws Exception { 34 | ResponseEntity response = template.getForEntity(base.toString(), String.class); 35 | // assertThat(response.getBody(), equalTo("Hello World!")); 36 | } 37 | } -------------------------------------------------------------------------------- /RestMvc/src/test/java/com/cml/springboot/controller/test/HelloControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | //@RunWith(SpringRunner.class) 12 | //@SpringBootTest 13 | //@AutoConfigureMockMvc 14 | public class HelloControllerTest { 15 | 16 | @Autowired 17 | private MockMvc mvc; 18 | 19 | @Test 20 | public void getHello() throws Exception { 21 | // mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) 22 | // .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); 23 | } 24 | } -------------------------------------------------------------------------------- /SpringBootWebFlux/README.MD: -------------------------------------------------------------------------------- 1 | # SpringJpa项目说明 # 2 | 通过SpringBoot方式整合,测试实现demo 3 | 4 | # 初始化配置# 5 | 将工程中db目录下的db.sql导入到对应的mysql数据,注意这里需要导入到两个数据库(读和写库) 6 | 7 | # 测试说明# 8 | 各种测试case都已经放在了测试包下(src/test/java)根据类名和注释可以自行测试 9 | 10 | -------------------------------------------------------------------------------- /SpringBootWebFlux/src/main/java/com/cml/learn/webflux/error/CustomExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.webflux.error; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ExceptionHandler; 5 | import org.springframework.web.bind.annotation.ResponseStatus; 6 | import org.springframework.web.bind.annotation.RestControllerAdvice; 7 | 8 | @RestControllerAdvice 9 | public class CustomExceptionHandler { 10 | 11 | @ExceptionHandler(Exception.class) 12 | @ResponseStatus(code = HttpStatus.OK) 13 | public String handleCustomException(Exception e) { 14 | return "出错啦:" + e.getMessage(); 15 | } 16 | } -------------------------------------------------------------------------------- /SpringBootWebFlux/src/main/java/com/cml/learn/webflux/filter/AccessLogFilter.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.webflux.filter; 2 | 3 | import org.slf4j.LoggerFactory; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.server.ServerWebExchange; 6 | import org.springframework.web.server.WebFilter; 7 | import org.springframework.web.server.WebFilterChain; 8 | import reactor.core.publisher.Mono; 9 | 10 | /** 11 | * @Auther: cml 12 | * @Date: 2018-12-19 09:48 13 | * @Description: 14 | */ 15 | @Component 16 | public class AccessLogFilter implements WebFilter { 17 | 18 | private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass()); 19 | 20 | @Override 21 | public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { 22 | final ServerWebExchange ex = new PayloadServerWebExchangeDecorator(exchange); 23 | return chain.filter(ex).doOnError(t -> { 24 | logger.info("onError:" + t); 25 | }).doOnSuccess(t -> { 26 | logger.info("success:" + t); 27 | }).doFinally(t -> { 28 | logger.info("finally-->" + ((PartnerServerHttpResponseDecorator) ex.getResponse()).getBody() + ":" + Thread.currentThread().getId() + ":" + Thread.currentThread().getName()); 29 | }); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /SpringBootWebFlux/src/main/java/com/cml/learn/webflux/filter/PayloadServerWebExchangeDecorator.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.webflux.filter; 2 | 3 | import org.springframework.http.server.reactive.ServerHttpRequest; 4 | import org.springframework.http.server.reactive.ServerHttpResponse; 5 | import org.springframework.web.server.ServerWebExchange; 6 | import org.springframework.web.server.ServerWebExchangeDecorator; 7 | 8 | public class PayloadServerWebExchangeDecorator extends ServerWebExchangeDecorator { 9 | 10 | private PartnerServerHttpRequestDecorator requestDecorator; 11 | 12 | private PartnerServerHttpResponseDecorator responseDecorator; 13 | 14 | public PayloadServerWebExchangeDecorator(ServerWebExchange delegate) { 15 | super(delegate); 16 | requestDecorator = new PartnerServerHttpRequestDecorator(delegate.getRequest()); 17 | responseDecorator = new PartnerServerHttpResponseDecorator(delegate.getResponse()); 18 | } 19 | 20 | @Override 21 | public ServerHttpRequest getRequest() { 22 | return requestDecorator; 23 | } 24 | 25 | @Override 26 | public ServerHttpResponse getResponse() { 27 | return responseDecorator; 28 | } 29 | } -------------------------------------------------------------------------------- /SpringBootWebFlux/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/SpringBootWebFlux/src/main/resources/application.properties -------------------------------------------------------------------------------- /SpringBootWebFlux/src/test/java/com/cml/webflux/webclient/Person.java: -------------------------------------------------------------------------------- 1 | package com.cml.webflux.webclient; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | class Person { 7 | 8 | private String name; 9 | 10 | 11 | // No-arg constructor for XML 12 | public Person() { 13 | } 14 | 15 | @JsonCreator 16 | public Person(@JsonProperty("name") String name) { 17 | this.name = name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public String getName() { 25 | return this.name; 26 | } 27 | 28 | @Override 29 | public boolean equals(Object other) { 30 | if (this == other) return true; 31 | if (other == null || getClass() != other.getClass()) return false; 32 | Person person = (Person) other; 33 | return getName().equals(person.getName()); 34 | } 35 | 36 | @Override 37 | public int hashCode() { 38 | return getName().hashCode(); 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "Person[name='" + name + "']"; 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /SpringJpa/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.settings/ 6 | .classpath -------------------------------------------------------------------------------- /SpringJpa/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | SpringJpa 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.common.project.facet.core.builder 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.springframework.ide.eclipse.core.springbuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.m2e.core.maven2Builder 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.ide.eclipse.core.springnature 31 | org.eclipse.jdt.core.javanature 32 | org.eclipse.m2e.core.maven2Nature 33 | org.eclipse.wst.common.project.facet.core.nature 34 | 35 | 36 | -------------------------------------------------------------------------------- /SpringJpa/README.MD: -------------------------------------------------------------------------------- 1 | # SpringJpa项目说明 # 2 | 通过SpringBoot方式整合,测试实现demo 3 | 4 | # 初始化配置# 5 | 将工程中db目录下的db.sql导入到对应的mysql数据,注意这里需要导入到两个数据库(读和写库) 6 | 7 | # 测试说明# 8 | 各种测试case都已经放在了测试包下(src/test/java)根据类名和注释可以自行测试 9 | 10 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/controller/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | import com.cml.learn.jpa.db.bean.User; 10 | import com.cml.learn.jpa.db.read.UserReadRepository; 11 | import com.cml.learn.jpa.service.UserService; 12 | 13 | @Controller 14 | @RequestMapping("/") 15 | public class HelloWorldController { 16 | @Autowired 17 | private UserService userService; 18 | 19 | @Autowired 20 | private UserReadRepository userReadRepository; 21 | 22 | @RequestMapping 23 | @ResponseBody 24 | public String test(long id, String nickName) throws Exception { 25 | userService.modifyUser(id, nickName); 26 | return "数据操作完成,只读数据库数据:" + userReadRepository.findOne(id); 27 | } 28 | 29 | @RequestMapping("/users/{id}") 30 | @ResponseBody 31 | User test(@PathVariable long id) throws Exception { 32 | User user = userReadRepository.findOne(id); 33 | return user; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/db/read/OrderReadRepository.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.db.read; 2 | 3 | import org.springframework.cache.annotation.Cacheable; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.CrudRepository; 6 | 7 | import com.cml.learn.jpa.db.bean.Order; 8 | import com.cml.learn.jpa.dto.OrderQueryDTO; 9 | import com.cml.learn.jpa.dto.OrderQueryDTO2; 10 | import com.cml.learn.jpa.dto.OrderQueryDTO3; 11 | 12 | public interface OrderReadRepository extends CrudRepository { 13 | 14 | @Query("select orderName , user.userId ,user.username from Order where id = ?1") 15 | T findOrderWithUserNameByOrderId(Long id, Class target); 16 | 17 | /** 18 | * 注意使用bean作为projection时需要手动设置字段别名(加AS) 19 | * 20 | * @param id 21 | * @return 22 | */ 23 | @Query("select orderName as orderName, user.userId as userId,user.username as username from Order where id = ?1") 24 | OrderQueryDTO findOrderWithUserNameByOrderId2(Long id); 25 | 26 | T findOrderNameWithAnyTypeById(Long id, Class target); 27 | 28 | OrderQueryDTO2 findOrderNameById(Long id); 29 | 30 | /** 31 | * 获取用户和订单部分信息 32 | * 33 | * @param id 34 | * @return 35 | */ 36 | OrderQueryDTO3 findOrderAndUserById(Long id); 37 | 38 | T findOrderAndUserWithAnyTypeById(Long id, Class t); 39 | 40 | @Cacheable(value = "simpleCache",key="'users' + #root.args[0]") 41 | Order findById(Long id); 42 | } 43 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/db/read/UserReadRepository.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.db.read; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.CrudRepository; 7 | 8 | import com.cml.learn.jpa.db.bean.User; 9 | 10 | /** 11 | * 用户信息相关 12 | * 13 | * @author cml 14 | * 15 | */ 16 | public interface UserReadRepository extends CrudRepository { 17 | /** 18 | * 自定义查询字段,注意这里查询使用的是bean对应的属性字段而不是数据库字段 19 | * @param username 20 | * @return 21 | */ 22 | @Query("select userId from User where username = ?1") 23 | Long findUserIdByUsername(String username); 24 | } 25 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/db/write/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.db.write; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import com.cml.learn.jpa.db.bean.Order; 6 | 7 | public interface OrderRepository extends CrudRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/db/write/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.db.write; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.repository.CrudRepository; 6 | 7 | import com.cml.learn.jpa.db.bean.User; 8 | 9 | /** 10 | * 用户信息相关 11 | * 12 | * @author cml 13 | * 14 | */ 15 | public interface UserRepository extends CrudRepository { 16 | 17 | /** 18 | * 获取根据昵称升序的第一条数据 19 | * 20 | * @return 21 | */ 22 | User findFirstByOrderByNicknameAsc(); 23 | 24 | Page findAll(Pageable page); 25 | 26 | T findByUserId(Integer id, Class result); 27 | } 28 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/OrderQueryDTO.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | public interface OrderQueryDTO { 4 | 5 | public Long getUserId(); 6 | 7 | public String getOrderName(); 8 | 9 | public String getUsername(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/OrderQueryDTO2.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | public class OrderQueryDTO2 { 4 | 5 | private String orderName; 6 | 7 | public OrderQueryDTO2(String orderName) { 8 | super(); 9 | this.orderName = orderName; 10 | } 11 | 12 | public void setOrderName(String orderName) { 13 | this.orderName = orderName; 14 | } 15 | 16 | public String getOrderName() { 17 | return orderName; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/OrderQueryDTO3.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | public interface OrderQueryDTO3 { 4 | public UserProjection getUser(); 5 | 6 | public String getOrderName(); 7 | } 8 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/UserEmailDTO.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | /** 4 | * 只需要获取用户邮箱等信息 5 | * 6 | * @author cml 7 | * 8 | */ 9 | public class UserEmailDTO { 10 | private final String userEmail; 11 | 12 | public UserEmailDTO(String userEmail) { 13 | super(); 14 | this.userEmail = userEmail; 15 | } 16 | 17 | public String getUserEmail() { 18 | return userEmail; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/UserNickNameDTO.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | /** 4 | * 只需要获取用户昵称等信息,可以根据实际情况添加需要的字段 5 | * 6 | * @author cml 7 | * 8 | */ 9 | public class UserNickNameDTO { 10 | private final String nickName; 11 | 12 | public UserNickNameDTO(String nickName) { 13 | super(); 14 | this.nickName = nickName; 15 | } 16 | 17 | public String getNickName() { 18 | return nickName; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/dto/UserProjection.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.dto; 2 | 3 | public interface UserProjection { 4 | 5 | public String getUsername(); 6 | 7 | public Long getUserId(); 8 | 9 | } -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/framework/db/converter/DateToDateTimeConverter.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.framework.db.converter; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.AttributeConverter; 6 | import javax.persistence.Converter; 7 | 8 | import org.joda.time.DateTime; 9 | 10 | /** 11 | * 数据库date类型转换成DateTime 12 | * 13 | * @author cml 14 | * 15 | */ 16 | @Converter(autoApply = true) 17 | public class DateToDateTimeConverter implements AttributeConverter { 18 | 19 | @Override 20 | public Date convertToDatabaseColumn(DateTime attribute) { 21 | if (attribute != null) { 22 | return new Date(attribute.getMillis()); 23 | } 24 | return null; 25 | } 26 | 27 | @Override 28 | public DateTime convertToEntityAttribute(Date dbData) { 29 | if (dbData != null) { 30 | return new DateTime(dbData.getTime()); 31 | } 32 | return null; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/framework/util/MD5.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.framework.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class MD5 { 6 | public static String getMD5(String source) { 7 | String s = null; 8 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 9 | 'a', 'b', 'c', 'd', 'e', 'f' }; 10 | try { 11 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 12 | md5.update(source.getBytes()); 13 | byte tmp[] = md5.digest(); 14 | char str[] = new char[16 * 2]; 15 | int k = 0; 16 | for (int i = 0; i < 16; i++) { 17 | byte byte0 = tmp[i]; 18 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 19 | str[k++] = hexDigits[byte0 & 0xf]; 20 | } 21 | s = new String(str); 22 | 23 | } catch (Exception ex) { 24 | ex.printStackTrace(); 25 | } 26 | return s; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /SpringJpa/src/main/java/com/cml/learn/jpa/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.service; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.cml.learn.jpa.db.bean.User; 10 | import com.cml.learn.jpa.db.write.UserRepository; 11 | 12 | @Service 13 | @Transactional() 14 | public class UserService { 15 | 16 | private static Logger log = LoggerFactory.getLogger(UserService.class); 17 | 18 | @Autowired 19 | private UserRepository userRepository; 20 | 21 | public void testTransaction(long id, long second) throws Exception { 22 | User user = userRepository.findOne(id); 23 | log.info("firstUserNickname:" + user.getNickname()); 24 | 25 | user.setNickname("modifiedByFirst!"); 26 | userRepository.save(user); 27 | 28 | log.info("update user 1 success!!!"); 29 | 30 | User secondUser = userRepository.findOne(second); 31 | log.info("secondUserNickname:" + secondUser.getNickname()); 32 | 33 | secondUser.setNickname("modified by Senond!!"); 34 | userRepository.save(secondUser); 35 | 36 | log.info("update user 2 success!!!"); 37 | 38 | // throw new RuntimeException(""); 39 | } 40 | 41 | public void modifyUser(long id, String nickname) throws Exception { 42 | User user = userRepository.findOne(id); 43 | if (null == user) { 44 | return; 45 | } 46 | 47 | log.info("firstUserNickname:" + user.getNickname()); 48 | 49 | user.setNickname(nickname); 50 | userRepository.save(user); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /SpringJpa/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.database=mysql 2 | spring.jpa.show-sql=true 3 | spring.jpa.generate-ddl=false 4 | 5 | #\u5199db\u914D\u7F6E 6 | spring.datasource.url=jdbc:mysql://localhost:3306/jpa-w 7 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 8 | spring.datasource.username=root 9 | spring.datasource.password=1234 10 | #\u53EA\u8BFBdb\u914D\u7F6E 11 | spring.datasource2.url=jdbc:mysql://localhost:3306/jpa-r 12 | spring.datasource2.driverClassName=com.mysql.jdbc.Driver 13 | spring.datasource2.username=root 14 | spring.datasource2.password=1234 -------------------------------------------------------------------------------- /SpringJpa/src/test/java/com/cml/learn/jpa/test/TransactionTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import com.cml.learn.jpa.Application; 10 | import com.cml.learn.jpa.service.UserService; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest(classes = Application.class) 14 | public class TransactionTest { 15 | 16 | @Autowired 17 | private UserService userService; 18 | 19 | @Test 20 | public void testTransaction() throws Exception { 21 | userService.testTransaction(1,2); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SpringJpa/src/test/java/com/cml/learn/jpa/test/UserCreateTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.test; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | 5 | import org.joda.time.DateTime; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import com.cml.learn.jpa.Application; 13 | import com.cml.learn.jpa.db.bean.User; 14 | import com.cml.learn.jpa.db.write.UserRepository; 15 | import com.cml.learn.jpa.framework.util.MD5; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest(classes = Application.class) 19 | public class UserCreateTest { 20 | 21 | @Autowired 22 | private UserRepository userRepository; 23 | 24 | /** 25 | * 用户创建测试 26 | */ 27 | @Test 28 | public void testCreateUser() { 29 | for (int i = 0; i < 50; i++) { 30 | User user = new User(); 31 | user.setUsername("user" + i); 32 | user.setPassword(MD5.getMD5("111111")); 33 | user.setNickname("nickname" + i); 34 | user.setCreateTime(DateTime.now()); 35 | user.setUpdateTime(DateTime.now()); 36 | user = userRepository.save(user); 37 | Long userId = user.getUserId(); 38 | 39 | System.out.println("create User success userId:" + userId); 40 | 41 | assertNotNull(userId); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /SpringJpa/src/test/java/com/cml/learn/jpa/test/UserProjectionQueryTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import com.cml.learn.jpa.Application; 10 | import com.cml.learn.jpa.db.write.UserRepository; 11 | import com.cml.learn.jpa.dto.UserEmailDTO; 12 | import com.cml.learn.jpa.dto.UserNickNameDTO; 13 | 14 | /** 15 | * 部分字段查询 16 | * 17 | * @author cml 18 | * 19 | */ 20 | @RunWith(SpringRunner.class) 21 | @SpringBootTest(classes = Application.class) 22 | public class UserProjectionQueryTest { 23 | @Autowired 24 | private UserRepository userRepository; 25 | 26 | /** 27 | * 查询部分字段功能 28 | */ 29 | @Test 30 | public void testProjectionQuery() { 31 | UserEmailDTO emailDTO = userRepository.findByUserId(1, UserEmailDTO.class); 32 | System.out.println("emailDTO:" + emailDTO.getUserEmail()); 33 | 34 | UserNickNameDTO userNickNameDTO = userRepository.findByUserId(1, UserNickNameDTO.class); 35 | System.out.println("userNickNameDTO:" + userNickNameDTO.getNickName()); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /SpringJpa/src/test/java/com/cml/learn/jpa/test/order/OrderCreateTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.jpa.test.order; 2 | 3 | import java.util.UUID; 4 | 5 | import org.joda.time.DateTime; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import com.cml.learn.jpa.Application; 13 | import com.cml.learn.jpa.db.bean.Order; 14 | import com.cml.learn.jpa.db.bean.User; 15 | import com.cml.learn.jpa.db.write.OrderRepository; 16 | import com.cml.learn.jpa.db.write.UserRepository; 17 | 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(classes = Application.class) 20 | public class OrderCreateTest { 21 | @Autowired 22 | private OrderRepository orderRepository; 23 | @Autowired 24 | private UserRepository userRepository; 25 | 26 | @Test 27 | public void testAddOrder() { 28 | for (int i = 1; i < 50; i++) { 29 | Order order = new Order(); 30 | order.setOrderName("orderName"+i); 31 | order.setOrderNumber(UUID.randomUUID().toString()); 32 | order.setCreateTime(DateTime.now()); 33 | order.setUpdateTime(DateTime.now()); 34 | 35 | User user = userRepository.findOne((long) i); 36 | order.setUser(user); 37 | 38 | orderRepository.save(order); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SpringStarter/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SpringStarter/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /SpringStarter/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | org.eclipse.jdt.core.compiler.compliance=1.8 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.8 6 | -------------------------------------------------------------------------------- /embedded-container/src/main/java/com/cml/learn/embedd/container/Application.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.embedd.container; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | public static void main(String[] args) { 9 | SpringApplication.run(Application.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /embedded-container/src/main/java/com/cml/learn/embedd/container/redis/RedisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.embedd.container.redis; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.api.RedissonClient; 5 | import org.redisson.config.Config; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.DependsOn; 9 | import redis.embedded.RedisServer; 10 | 11 | import java.io.IOException; 12 | 13 | @Configuration 14 | public class RedisConfiguration { 15 | 16 | @Bean 17 | public RedisServer redisServer() throws IOException { 18 | RedisServer redisServer = new RedisServer(6379); 19 | redisServer.start(); 20 | return redisServer; 21 | } 22 | 23 | @Bean 24 | @DependsOn({"redisServer"}) 25 | public RedissonClient createRedisson() throws InterruptedException { 26 | Config config = new Config(); 27 | config.useSingleServer() 28 | .setAddress("redis://127.0.0.1:6379") 29 | .setTimeout(1000); 30 | return Redisson.create(config); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /embedded-container/src/main/java/com/cml/learn/embedd/container/redis/RedisTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.embedd.container.redis; 2 | 3 | import org.redisson.api.RBucket; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.ApplicationArguments; 7 | import org.springframework.boot.ApplicationRunner; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class RedisTest implements ApplicationRunner { 12 | 13 | @Autowired 14 | private RedissonClient redissonClient; 15 | 16 | @Override 17 | public void run(ApplicationArguments args) throws Exception { 18 | 19 | System.out.println("-----------------------redis----------------"); 20 | RBucket testKey = redissonClient.getBucket("testKey"); 21 | testKey.set("myValue:" + System.currentTimeMillis()); 22 | 23 | System.out.println(redissonClient.getBucket("testKey").get()); 24 | System.out.println("-----------------------redis----------------"); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /embedded-container/src/main/java/com/cml/learn/embedd/container/zookeeper/EmbeddedZookeeperConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.embedd.container.zookeeper; 2 | 3 | import org.apache.curator.RetryPolicy; 4 | import org.apache.curator.framework.CuratorFramework; 5 | import org.apache.curator.framework.CuratorFrameworkFactory; 6 | import org.apache.curator.retry.ExponentialBackoffRetry; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class EmbeddedZookeeperConfiguration { 12 | 13 | @Bean(destroyMethod = "stop", initMethod = "start") 14 | public EmbeddedZooKeeper embeddedZooKeeper() { 15 | return new EmbeddedZooKeeper(); 16 | } 17 | 18 | @Bean(destroyMethod = "close", initMethod = "start") 19 | public CuratorFramework zkCuratorFramework() { 20 | RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 5); 21 | return CuratorFrameworkFactory.builder().retryPolicy(retryPolicy) 22 | .connectString("localhost:2181") 23 | .connectionTimeoutMs(1000) 24 | .sessionTimeoutMs(1000) 25 | .build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /embedded-container/src/main/java/com/cml/learn/embedd/container/zookeeper/EmbeddedZookeeperTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.embedd.container.zookeeper; 2 | 3 | import org.apache.curator.framework.CuratorFramework; 4 | import org.apache.zookeeper.CreateMode; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.ApplicationArguments; 7 | import org.springframework.boot.ApplicationRunner; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class EmbeddedZookeeperTest implements ApplicationRunner { 12 | @Autowired 13 | private CuratorFramework curatorFramework; 14 | 15 | @Override 16 | public void run(ApplicationArguments args) throws Exception { 17 | System.out.println("-----------------------zk----------------"); 18 | 19 | System.out.println(curatorFramework.getChildren().forPath("/")); 20 | curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/test", "dataValue".getBytes()); 21 | System.out.println("/test 节点数据:" + new String(curatorFramework.getData().forPath("/test"))); 22 | System.out.println("-----------------------zk----------------"); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /flyway/flyway.iml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /flyway/src/main/java/com/cml/learn/flyway/FlywayApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.flyway; 2 | 3 | import com.cml.learn.flyway.repository.City; 4 | import com.cml.learn.flyway.repository.CityRepository; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.context.ConfigurableApplicationContext; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.PageRequest; 10 | 11 | import java.sql.SQLException; 12 | 13 | @SpringBootApplication 14 | public class FlywayApplication { 15 | public static void main(String[] args) throws SQLException { 16 | ConfigurableApplicationContext app = SpringApplication.run(FlywayApplication.class, args); 17 | 18 | CityRepository cityRepository = app.getBean(CityRepository.class); 19 | 20 | City city = new City("shanghai", "on"); 21 | cityRepository.save(city); 22 | System.out.println("save result==>city Id:" + city.getId()); 23 | 24 | city = new City("杭州", "off"); 25 | cityRepository.save(city); 26 | System.out.println("save result==>city Id:" + city.getId()); 27 | 28 | Page cities = cityRepository.findAll(new PageRequest(0, 100)); 29 | System.out.println("result===>" + cities.getContent()); 30 | 31 | // app.close(); 32 | } 33 | } -------------------------------------------------------------------------------- /flyway/src/main/java/com/cml/learn/flyway/repository/City.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.flyway.repository; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | @Entity 7 | public class City implements Serializable { 8 | 9 | @Id 10 | @GeneratedValue(strategy = GenerationType.IDENTITY) 11 | private Long id; 12 | 13 | @Column(nullable = false) 14 | private String name; 15 | 16 | @Column(nullable = false) 17 | private String state; 18 | 19 | // ... additional members, often include @OneToMany mappings 20 | 21 | protected City() { 22 | // no-args constructor required by JPA spec 23 | // this one is protected since it shouldn't be used directly 24 | } 25 | 26 | public City(String name, String state) { 27 | this.name = name; 28 | this.state = state; 29 | } 30 | 31 | public String getName() { 32 | return this.name; 33 | } 34 | 35 | public String getState() { 36 | return this.state; 37 | } 38 | 39 | // ... etc 40 | 41 | public Long getId() { 42 | return id; 43 | } 44 | 45 | public void setId(Long id) { 46 | this.id = id; 47 | } 48 | 49 | public void setName(String name) { 50 | this.name = name; 51 | } 52 | 53 | public void setState(String state) { 54 | this.state = state; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return "City{" + 60 | "id=" + id + 61 | ", name='" + name + '\'' + 62 | ", state='" + state + '\'' + 63 | '}'; 64 | } 65 | } -------------------------------------------------------------------------------- /flyway/src/main/java/com/cml/learn/flyway/repository/CityRepository.java: -------------------------------------------------------------------------------- 1 | package com.cml.learn.flyway.repository; 2 | 3 | import org.springframework.data.domain.*; 4 | import org.springframework.data.repository.*; 5 | 6 | public interface CityRepository extends CrudRepository { 7 | 8 | Page findAll(Pageable pageable); 9 | 10 | City findByNameAndStateAllIgnoringCase(String name, String state); 11 | 12 | } -------------------------------------------------------------------------------- /flyway/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:h2:file:~/.h2/testdb 4 | driver-class-name: org.h2.Driver 5 | username: sa 6 | password: sa 7 | h2: 8 | console: 9 | enabled: true 10 | path: /h2/console 11 | jpa: 12 | hibernate: 13 | ddl-auto: none #第一次使用时需要设置为create 14 | # jpa: 15 | # hibernate: 16 | logging: 17 | level: 18 | org: 19 | hibernate: DEBUG 20 | # ddl-auto: create -------------------------------------------------------------------------------- /rabbitmq/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /rabbitmq/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs -------------------------------------------------------------------------------- /rabbitmq/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | rabbitmq 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.springframework.ide.eclipse.core.springbuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.m2e.core.maven2Builder 20 | 21 | 22 | 23 | 24 | 25 | org.springframework.ide.eclipse.core.springnature 26 | org.eclipse.jdt.core.javanature 27 | org.eclipse.m2e.core.maven2Nature 28 | 29 | 30 | -------------------------------------------------------------------------------- /rabbitmq/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding//src/test/resources=UTF-8 6 | encoding/=UTF-8 7 | -------------------------------------------------------------------------------- /rabbitmq/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | org.eclipse.jdt.core.compiler.compliance=1.8 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.8 6 | -------------------------------------------------------------------------------- /rabbitmq/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /rabbitmq/README.MD: -------------------------------------------------------------------------------- 1 | # rabbitmq项目说明 # 2 | 通过Spring与SpringBoot两种方式整合,完成rabbitmq基本消息发送与接收功能 3 | 4 | # 项目运行要求 # 5 | - 正确安装好rabbitmq 6 | - 正确配置好config/rabbitmq/rabbitmq.properties中rabbitmq连接信息 7 | 8 | # 基于docker的rabbitmq环境安装 # 9 | 1. 获取镜像: docker pull rabbitmq:management 10 | 2. 执行镜像 11 | docker run -d --name rabbitmq --publish 5671:5671 \ 12 | --publish 5672:5672 --publish 4369:4369 --publish 25672:25672 --publish 15671:15671 --publish 15672:15672 \rabbitmq:management 13 | 1. 查看docker容器ip:docker-machine ip 14 | 2. 根据获取的ip,在浏览器上访问:http://${ip}:15672 打开管理页面,则说明rabbitmq安装成功 15 | ![](screenshots/rabbit-admin.png) 16 | 17 | 18 | ---------- 19 | # 整合Spring工程说明 # 20 | 21 | # src/main/resource说明 # 22 | 1. config/rabbitmq/rabbitmq.properties是对rabbitmq的基本信息配置 23 | 2. spring目录是使用spring整合时的配置文件目录 24 | 3. springboot目录是使用springboot整合时的配置文件目录 25 | 26 | # src/main/test说明 # 27 | - SpringIntegrationReceiverTest 接收Rabbitmq消息,测试前先启动 28 | - SpringIntegrationSendTest 发送Rabbitmq消息,已有fanout,direct,topic,与手动确认消息类型 29 | 30 | # 执行结果说明 # 31 | 启动SpringIntegrationReceiverTest后,启动SpringIntegrationSendTest发送消息,可以看到控制台上有log如下: 32 | ![](screenshots/receiver.png) 33 | 表明程序执行ok,各监听队列已收到消息。 34 | 35 | ---------- 36 | # 整合SpringBoot工程说明 # 37 | # TODO # -------------------------------------------------------------------------------- /rabbitmq/screenshots/rabbit-admin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/rabbitmq/screenshots/rabbit-admin.png -------------------------------------------------------------------------------- /rabbitmq/screenshots/receiver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/rabbitmq/screenshots/receiver.png -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/model/EmailModel.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.model; 2 | 3 | public class EmailModel { 4 | private String to; 5 | private String title; 6 | private String content; 7 | 8 | public String getTo() { 9 | return to; 10 | } 11 | 12 | public void setTo(String to) { 13 | this.to = to; 14 | } 15 | 16 | public String getTitle() { 17 | return title; 18 | } 19 | 20 | public void setTitle(String title) { 21 | this.title = title; 22 | } 23 | 24 | public String getContent() { 25 | return content; 26 | } 27 | 28 | public void setContent(String content) { 29 | this.content = content; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "EmailModel [to=" + to + ", title=" + title + ", content=" + content + "]"; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/AbstractEmailReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public abstract class AbstractEmailReceiver extends AbstractReceiver { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/AbstractReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.amqp.core.Message; 6 | import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener; 7 | import org.springframework.amqp.support.converter.MessageConverter; 8 | 9 | import com.rabbitmq.client.Channel; 10 | 11 | public abstract class AbstractReceiver implements ChannelAwareMessageListener { 12 | 13 | static Log logger=LogFactory.getLog(AbstractReceiver.class); 14 | 15 | private MessageConverter messageConverter; 16 | private boolean autoACK; 17 | 18 | @Override 19 | public void onMessage(Message message, Channel channel) throws Exception { 20 | boolean successHandle = false; 21 | try { 22 | @SuppressWarnings("unchecked") 23 | T msg = (T) messageConverter.fromMessage(message); 24 | successHandle = handle(msg); 25 | } catch (Exception e) { 26 | logger.error("", e); 27 | } finally { 28 | if (successHandle && !autoACK) { 29 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); 30 | } 31 | } 32 | } 33 | 34 | /** 35 | * 36 | * @param t 37 | * @return true 处理成功 38 | */ 39 | public abstract boolean handle(T t); 40 | 41 | public MessageConverter getMessageConverter() { 42 | return messageConverter; 43 | } 44 | 45 | public void setMessageConverter(MessageConverter messageConverter) { 46 | this.messageConverter = messageConverter; 47 | } 48 | 49 | public boolean isAutoACK() { 50 | return autoACK; 51 | } 52 | 53 | public void setAutoACK(boolean autoACK) { 54 | this.autoACK = autoACK; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/DirectMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public class DirectMessageReceiver extends AbstractEmailReceiver { 6 | 7 | @Override 8 | public boolean handle(EmailModel t) { 9 | logger.info("DirectMessageReceiver:"+t.toString()); 10 | return false; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/FanoutMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public class FanoutMessageReceiver extends AbstractEmailReceiver { 6 | 7 | @Override 8 | public boolean handle(EmailModel t) { 9 | logger.info("FanoutMessageReceiver:"+t.toString()); 10 | return false; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/QueneMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public class QueneMessageReceiver extends AbstractEmailReceiver{ 6 | 7 | @Override 8 | public boolean handle(EmailModel t) { 9 | return false; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/TopicManualACKMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public class TopicManualACKMessageReceiver extends AbstractEmailReceiver { 6 | 7 | @Override 8 | public boolean handle(EmailModel t) { 9 | logger.info("TopicManualACKMessageReceiver:" + t.toString()); 10 | return true; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/receiver/TopicMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.receiver; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public class TopicMessageReceiver extends AbstractEmailReceiver{ 6 | 7 | @Override 8 | public boolean handle(EmailModel t) { 9 | logger.info("TopicMessageReceiver:"+t.toString()); 10 | return false; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rabbitmq/src/main/java/com/cml/learning/rabbitmq/spring/service/MailService.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring.service; 2 | 3 | import com.cml.learning.rabbitmq.spring.model.EmailModel; 4 | 5 | public interface MailService { 6 | void sendTopicEmail(String routeKey,EmailModel model); 7 | 8 | void sendDirectEmail(String routeKey,EmailModel model); 9 | 10 | void sendFanoutEmail(String routeKey,EmailModel model); 11 | } 12 | -------------------------------------------------------------------------------- /rabbitmq/src/main/resources/config/rabbitmq/rabbitmq.properties: -------------------------------------------------------------------------------- 1 | rabbitmq.host=192.168.99.100 2 | rabbitmq.username=guest 3 | rabbitmq.password=guest 4 | rabbitmq.channelCacheSize=25 5 | rabbitmq.exchange=myexchange2 6 | 7 | #TOPPIC\u6D88\u606F 8 | rabbitmq.exchange.topic=mailTopic 9 | rabbitmq.exchange.topic.quene=mailTopicQuene 10 | rabbitmq.exchange.topic.route=mail.* 11 | #MANUAL TOPIC\u6D88\u606F 12 | rabbitmq.exchange.manualTopic=manualTopic 13 | rabbitmq.exchange.manualTopic.quene=manualTopicQuene 14 | rabbitmq.exchange.manualTopic.route=mailManul.* 15 | 16 | #direct\u5F62\u5F0F\u6D88\u606F\u53D1\u9001 17 | rabbitmq.exchange.direct=maildirect 18 | rabbitmq.exchange.direct.quene=maildirectQuene 19 | rabbitmq.exchange.direct.route=mail 20 | 21 | #Fanout\u5F62\u5F0F\u6D88\u606F 22 | rabbitmq.exchange.fanout=mailFanout 23 | rabbitmq.exchange.fanout.quene=mailFanoutQuene -------------------------------------------------------------------------------- /rabbitmq/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J\u914d\u7f6e 2 | log4j.rootCategory=info,stdout 3 | 4 | # \u63a7\u5236\u53f0\u8f93\u51fa 5 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 8 | -------------------------------------------------------------------------------- /rabbitmq/src/test/java/com/cml/learning/rabbitmq/spring/SpringIntegrationReceiverTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.learning.rabbitmq.spring; 2 | 3 | import org.junit.Test; 4 | import org.springframework.context.support.ClassPathXmlApplicationContext; 5 | 6 | /** 7 | * 整合Spring测试,接收消息 8 | * 9 | * @author cml 10 | * 11 | */ 12 | public class SpringIntegrationReceiverTest { 13 | @Test 14 | public void testMessage() throws Exception { 15 | ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/application-rabbitmq-listener.xml"); 16 | System.out.println("receiver started!!!"); 17 | Thread.sleep(1000000); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /web/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | /logs 4 | /transaction-logs 5 | /.apt_generated/ 6 | -------------------------------------------------------------------------------- /web/README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot Learning # 2 | 3 | 此项目主要作为SpringBoot学习,和根据实际项目对SpringBoot进行配置改造 4 | 主要使用框架:SpringBoot(Spring,SpringMVC),Mybatis,ehcache,javamail 5 | 6 | # 项目结构 # 7 | - **程序入口** 8 | > com.cml.springboot.BootApplication 9 | 10 | - **核心配置** 11 | > com.cml.springboot.framework 是核心包,取代原有的xml配置,将xml配置等价转换为注解配置! 12 | 13 | - **demo代码** 14 | > com.cml.springboot.sample为测试使用的代码,主要结构为Controller,bean,db,service几个常用的包层级。 15 | 16 | - **db** 17 | > db文件夹下为demo工程的数据库ddl 18 | 19 | # 执行程序 # 20 | 详见:wiki Home page 21 | # 分支说明 # 22 | 23 | 1. master 24 | 25 | > 主要分支,模拟常用api功能。 26 | 27 | 2. branch_learn 28 | 29 | > 初始化分支,混杂各种spring boot学习代码,未做具体区分 30 | 31 | 3. branch_shiro 32 | 33 | > 整合shiro框架,实现授权,认证与自定义拦截器授权处理 34 | 35 | 4. deploy_jar_bugfind 36 | 37 | > 查找与解决打包jar后Mybatis扫描问题 38 | 39 | 5. branch_i18n 40 | 41 | > 国际化支持 42 | 43 | 6. branch_mail 44 | 45 | > 邮件发送功能整合,注意需要在config/application.properties配置邮箱服务密码 46 | 47 | 7. branch-mybatis-scanner 48 | 49 | > 添加Mybatis MapperScan动态扫描(占位符)功能 ,详情见博客:http://blog.csdn.net/cml_blog/article/details/65658654 50 | 51 | 8. branch-mybatis-generate 52 | 53 | > mybatis beans生成工具,默认日期类型为DateTime类型,入口类:com.cml.springboot.sample.mbg.MybatisGenerateEntrance 54 | 55 | 56 | #问题与解决 57 | 1、Mybatis打包jar后无法扫描到bean与mapper问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/53138851 58 | 2、163发送邮件功能问题,解决对应地址http://blog.csdn.net/cml_blog/article/details/54235510 59 | 60 | # 当前分支(master)测试说明 # 61 | > 详见demo.html 62 | > 端口号为2222,可在config/application.properties 中server.port进行配置 63 | 64 | # 更多信息请查看wiki # 65 | 66 | 67 | -------------------------------------------------------------------------------- /web/screenshots/structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmlbeliever/SpringBootLearning/4a970d085dd0960331d6b10e28c6ec530f42ded2/web/screenshots/structure.png -------------------------------------------------------------------------------- /web/src/main/i18n/messages.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to default -------------------------------------------------------------------------------- /web/src/main/i18n/messages_en_US.properties: -------------------------------------------------------------------------------- 1 | welcome=welcome to english -------------------------------------------------------------------------------- /web/src/main/i18n/messages_zh_CN.properties: -------------------------------------------------------------------------------- 1 | welcome=\u6b22\u8fce\u6765\u5230\u4e2d\u56fd -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/BootApplication.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.PropertySource; 9 | import org.springframework.context.annotation.PropertySources; 10 | import org.springframework.scheduling.annotation.EnableAsync; 11 | 12 | @Configuration 13 | @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) 14 | @ComponentScan() 15 | @EnableAsync 16 | @PropertySources({ @PropertySource("classpath:config/application-jdbc.properties") }) 17 | public class BootApplication { 18 | 19 | // @Bean 20 | // public PropertyPlaceholderConfigurer placeHolder() { 21 | // 22 | // PropertyPlaceholderConfigurer configure = new 23 | // PropertyPlaceholderConfigurer(); 24 | // configure.setLocations(null); 25 | // 26 | // return configure; 27 | // } 28 | 29 | public static void main(String[] args) throws Exception { 30 | SpringApplication.run(BootApplication.class, args); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/AsyncTaskConfig.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | import java.util.concurrent.Executor; 4 | 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.scheduling.annotation.AsyncConfigurer; 11 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 12 | 13 | @Configuration 14 | public class AsyncTaskConfig implements AsyncConfigurer { 15 | 16 | protected static Log log = LogFactory.getLog(AsyncTaskConfig.class); 17 | 18 | @Value("${async.task.config.corePoolSize}") 19 | private Integer corePoolSize; 20 | @Value("${async.task.config.maxPoolSize}") 21 | private Integer maxPoolSize; 22 | 23 | @Override 24 | public Executor getAsyncExecutor() { 25 | 26 | log.info("<<>>====>corePoolSize:" + corePoolSize + ",maxPoolSize:" + maxPoolSize); 27 | 28 | ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor(); 29 | ex.setCorePoolSize(corePoolSize); 30 | ex.setMaxPoolSize(maxPoolSize); 31 | ex.initialize(); 32 | return ex; 33 | } 34 | 35 | @Override 36 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 37 | return null; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/Configuration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework; 2 | 3 | public interface Configuration { 4 | interface Status { 5 | int STATUS_OK = 1; 6 | int STATUS_FAIL = 2; 7 | int STATUS_INVALID_TOKEN = 3; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.controller; 2 | 3 | import org.springframework.validation.Errors; 4 | import org.springframework.validation.ObjectError; 5 | 6 | import com.cml.springboot.framework.Configuration; 7 | 8 | public class BaseController { 9 | 10 | public static final int SUCCESS = Configuration.Status.STATUS_OK; 11 | public static final int FAIL = Configuration.Status.STATUS_FAIL; 12 | 13 | public static String getAllErrors(Errors errors) { 14 | StringBuilder builder = new StringBuilder(); 15 | for (ObjectError error : errors.getAllErrors()) { 16 | builder.append(error.getDefaultMessage()).append("\n"); 17 | } 18 | return builder.toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/deserializer/DateTimeDeserializer.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.deserializer; 2 | 3 | import java.io.IOException; 4 | 5 | import org.joda.time.DateTime; 6 | import org.joda.time.format.DateTimeFormat; 7 | import org.joda.time.format.DateTimeFormatter; 8 | import org.springframework.format.datetime.joda.DateTimeFormatterFactory; 9 | 10 | import com.fasterxml.jackson.core.JsonGenerator; 11 | import com.fasterxml.jackson.core.JsonProcessingException; 12 | import com.fasterxml.jackson.databind.JsonSerializer; 13 | import com.fasterxml.jackson.databind.SerializerProvider; 14 | 15 | public class DateTimeDeserializer extends JsonSerializer { 16 | 17 | private String format = "yyyyMMddHHmmss"; 18 | 19 | public DateTimeDeserializer() { 20 | System.out.println("===================================================dddddddddddddddddddddddddddddddddddd"); 21 | } 22 | 23 | public DateTimeDeserializer(String format) { 24 | super(); 25 | this.format = format; 26 | } 27 | 28 | @Override 29 | public void serialize(DateTime value, JsonGenerator gen, SerializerProvider serializers) 30 | throws IOException, JsonProcessingException { 31 | if (null != value) { 32 | gen.writeString(value.toString(format)); 33 | } 34 | System.out.println("=============================="); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/mybatis/MybatisScanConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.mybatis.spring.annotation.MapperScan; 6 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | @AutoConfigureAfter(MybatisConfig.class) 11 | @MapperScan(basePackages = { "com.cml.springboot.sample.db" }, sqlSessionFactoryRef = "sqlSessionFactory") 12 | public class MybatisScanConfiguration { 13 | protected static Log log = LogFactory.getLog(MybatisScanConfiguration.class); 14 | 15 | public MybatisScanConfiguration() { 16 | log.info("*************************MybatisScanConfiguration***********************"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/mybatis/SpringBootVFS.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.mybatis; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.apache.ibatis.io.VFS; 10 | import org.springframework.core.io.Resource; 11 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 12 | import org.springframework.core.io.support.ResourcePatternResolver; 13 | 14 | public class SpringBootVFS extends VFS { 15 | 16 | private final ResourcePatternResolver resourceResolver; 17 | 18 | public SpringBootVFS() { 19 | this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); 20 | } 21 | 22 | @Override 23 | public boolean isValid() { 24 | return true; 25 | } 26 | 27 | @Override 28 | protected List list(URL url, String path) throws IOException { 29 | Resource[] resources = resourceResolver.getResources("classpath*:" + path + "/**/*.class"); 30 | List resourcePaths = new ArrayList(); 31 | for (Resource resource : resources) { 32 | resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); 33 | } 34 | return resourcePaths; 35 | } 36 | 37 | private static String preserveSubpackageName(final URI uri, final String rootPath) { 38 | final String uriStr = uri.toString(); 39 | final int start = uriStr.indexOf(rootPath); 40 | return uriStr.substring(start); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/response/BaseResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | public class BaseResponse { 4 | private Integer code; 5 | private String message; 6 | 7 | public BaseResponse() { 8 | } 9 | 10 | public BaseResponse(Integer code, String message) { 11 | super(); 12 | this.code = code; 13 | this.message = message; 14 | } 15 | 16 | public Integer getCode() { 17 | return code; 18 | } 19 | 20 | public void setCode(Integer code) { 21 | this.code = code; 22 | } 23 | 24 | public String getMessage() { 25 | return message; 26 | } 27 | 28 | public void setMessage(String message) { 29 | this.message = message; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/response/BaseResponseAdvise.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.http.converter.HttpMessageConverter; 8 | import org.springframework.http.server.ServerHttpRequest; 9 | import org.springframework.http.server.ServerHttpResponse; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 12 | 13 | //@ControllerAdvice() 14 | public class BaseResponseAdvise implements ResponseBodyAdvice { 15 | 16 | private static Log log = LogFactory.getLog(BaseResponseAdvise.class); 17 | 18 | @Override 19 | public boolean supports(MethodParameter returnType, Class> converterType) { 20 | log.info("===>" + (returnType.getGenericParameterType() instanceof BaseResponse)); 21 | return returnType.getGenericParameterType() == BaseResponse.class; 22 | } 23 | 24 | @Override 25 | public BaseResponse beforeBodyWrite(BaseResponse body, MethodParameter returnType, MediaType selectedContentType, 26 | Class> selectedConverterType, ServerHttpRequest request, 27 | ServerHttpResponse response) { 28 | // body.setMessage("被我修改了"); 29 | return body; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/response/MethodResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.response; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.context.request.NativeWebRequest; 6 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 7 | import org.springframework.web.method.support.ModelAndViewContainer; 8 | 9 | @Component 10 | public class MethodResponseHandler implements HandlerMethodReturnValueHandler { 11 | 12 | @Override 13 | public boolean supportsReturnType(MethodParameter returnType) { 14 | System.out.println("=====================? supportsReturnType"); 15 | return true; 16 | } 17 | 18 | @Override 19 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, 20 | NativeWebRequest webRequest) throws Exception { 21 | System.out.println("====================> handleReturnValue"); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/transaction/TransactionService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.transaction; 2 | 3 | import javax.annotation.Resource; 4 | import javax.sql.DataSource; 5 | 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 9 | import org.springframework.transaction.PlatformTransactionManager; 10 | import org.springframework.transaction.annotation.EnableTransactionManagement; 11 | 12 | @Configuration 13 | @EnableTransactionManagement() 14 | public class TransactionService { 15 | 16 | @Resource 17 | private DataSource dataSource; 18 | 19 | @Bean(name = "txManager") 20 | public PlatformTransactionManager txManager() { 21 | return new DataSourceTransactionManager(dataSource); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/util/LogUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | public class LogUtil { 4 | 5 | private static final String FORMAT_CONTROLLER = "《《《《%s》》》》====>%s"; 6 | 7 | public static String formatControllerLog(Object controller, String log) { 8 | return String.format(FORMAT_CONTROLLER, controller.getClass().getSimpleName(), log); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/util/MD5.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class MD5 { 6 | public static String getMD5(String source) { 7 | String s = null; 8 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 9 | 'a', 'b', 'c', 'd', 'e', 'f' }; 10 | try { 11 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 12 | md5.update(source.getBytes()); 13 | byte tmp[] = md5.digest(); 14 | char str[] = new char[16 * 2]; 15 | int k = 0; 16 | for (int i = 0; i < 16; i++) { 17 | byte byte0 = tmp[i]; 18 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 19 | str[k++] = hexDigits[byte0 & 0xf]; 20 | } 21 | s = new String(str); 22 | 23 | } catch (Exception ex) { 24 | ex.printStackTrace(); 25 | } 26 | return s; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/framework/util/UUIDUtil.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.framework.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class UUIDUtil { 6 | 7 | public static final String generateUUID() { 8 | return UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/bean/UserResponse.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.bean; 2 | 3 | import com.cml.springboot.framework.response.BaseResponse; 4 | 5 | public class UserResponse extends BaseResponse { 6 | private User user; 7 | 8 | public UserResponse(Integer code, String message, User user) { 9 | super(code, message); 10 | this.user = user; 11 | } 12 | 13 | public UserResponse(Integer code, User user) { 14 | super(code, null); 15 | this.user = user; 16 | } 17 | 18 | public User getUser() { 19 | return user; 20 | } 21 | 22 | public void setUser(User user) { 23 | this.user = user; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/controller/ModelAttributeController.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.controller; 2 | 3 | import java.sql.SQLException; 4 | 5 | import javax.annotation.Resource; 6 | import javax.validation.Valid; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.ModelAttribute; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import com.cml.springboot.sample.bean.User; 16 | import com.cml.springboot.sample.service.UserService; 17 | 18 | /** 19 | * ModelAttribute demo 20 | * 21 | * @author team-lab 22 | * 23 | */ 24 | @Controller 25 | @RequestMapping("/model") 26 | public class ModelAttributeController { 27 | 28 | @Resource(name = "userServiceImpl") 29 | private UserService userService; 30 | 31 | @ModelAttribute("user") 32 | public User user(@RequestParam String token) throws SQLException { 33 | System.out.println("==================================================token:"+token); 34 | if (StringUtils.isBlank(token)) { 35 | return null; 36 | } 37 | return userService.findUserByToken(token); 38 | } 39 | 40 | @RequestMapping("/testA") 41 | @ResponseBody 42 | public String testA(@ModelAttribute() User user) { 43 | if (user == null) { 44 | return "user is null!!!!"; 45 | } 46 | return "user:" + user.getUsername() + "," + user.getNickName(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/db/LogMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogMapper { 6 | void insertLog(LogBean logbean); 7 | } 8 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/db/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.db; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserMapper { 8 | User getUserByToken(String token) throws SQLException; 9 | 10 | User getUser(User user); 11 | 12 | Integer updateToken(User loginUser); 13 | } 14 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/db/resource/log.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | INSERT INTO t_api_log ( 7 | call_day, 8 | parameters, 9 | return_status_code, 10 | returns, 11 | api_url, 12 | create_date, 13 | update_date 14 | 15 | ) 16 | VALUES ( 17 | #{callDayStr}, 18 | #{parameters}, 19 | #{returnStatusCode}, 20 | #{returns}, 21 | #{apiUrl}, 22 | #{createDate}, 23 | NOW() 24 | ) 25 | 26 | 27 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/db/resource/user.sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | 35 | 36 | 37 | UPDATE 38 | t_user 39 | SET 40 | token = #{newToken} 41 | WHERE 42 | token = #{token} 43 | 44 | 45 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/service/LogService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import com.cml.springboot.sample.bean.LogBean; 4 | 5 | public interface LogService { 6 | void insertLog(LogBean logbean); 7 | 8 | void insertLogReadOnly(LogBean logbean); 9 | } 10 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.cml.springboot.sample.bean.User; 6 | 7 | public interface UserService { 8 | User findUserByToken(String token) throws SQLException; 9 | 10 | User login(User user) throws Exception; 11 | } 12 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/service/impl/LogServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service.impl; 2 | 3 | import org.joda.time.DateTime; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.scheduling.annotation.Async; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.cml.springboot.sample.bean.LogBean; 10 | import com.cml.springboot.sample.db.LogMapper; 11 | import com.cml.springboot.sample.service.LogService; 12 | 13 | @Service("logServiceImpl") 14 | @Transactional 15 | public class LogServiceImpl implements LogService { 16 | 17 | @Autowired 18 | private LogMapper logMapper; 19 | 20 | @Override 21 | @Async 22 | public void insertLog(LogBean logbean) { 23 | System.out.println("LogServiceImpl.insertLog threadId:" + Thread.currentThread().getId() + "," 24 | + Thread.currentThread().getName()); 25 | logbean.setCreateDate(new DateTime()); 26 | logMapper.insertLog(logbean); 27 | } 28 | 29 | @Transactional(readOnly = true) 30 | @Override 31 | public void insertLogReadOnly(LogBean logbean) { 32 | logbean.setCreateDate(new DateTime()); 33 | logMapper.insertLog(logbean); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /web/src/main/java/com/cml/springboot/sample/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.sample.service.impl; 2 | 3 | import java.sql.SQLException; 4 | 5 | import javax.transaction.Transactional; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.cml.springboot.framework.util.MD5; 11 | import com.cml.springboot.framework.util.UUIDUtil; 12 | import com.cml.springboot.sample.bean.User; 13 | import com.cml.springboot.sample.db.UserMapper; 14 | import com.cml.springboot.sample.service.UserService; 15 | 16 | @Transactional 17 | @Component("userServiceImpl") 18 | public class UserServiceImpl implements UserService { 19 | 20 | @Autowired 21 | private UserMapper userMapper; 22 | 23 | @Override 24 | public User findUserByToken(String token) throws SQLException { 25 | return userMapper.getUserByToken(token); 26 | } 27 | 28 | @Override 29 | public User login(User user) throws Exception { 30 | 31 | user.setPassword(MD5.getMD5(user.getPassword())); 32 | 33 | User loginUser = userMapper.getUser(user); 34 | if (null != loginUser) { 35 | String newToken = UUIDUtil.generateUUID(); 36 | // 重新生成token 37 | user.setNewToken(newToken); 38 | user.setToken(loginUser.getToken()); 39 | int updateCount = userMapper.updateToken(user); 40 | 41 | if (updateCount > 0) { 42 | loginUser.setToken(newToken); 43 | return loginUser; 44 | } 45 | 46 | } 47 | return null; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /web/src/main/resources/ValidationMessages.properties: -------------------------------------------------------------------------------- 1 | user.empty.username=\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7axxxxx -------------------------------------------------------------------------------- /web/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | I am a banner!!! -------------------------------------------------------------------------------- /web/src/main/resources/config/application-jdbc.properties: -------------------------------------------------------------------------------- 1 | #-----------mybatis--------------- 2 | #db.mybatis.mapper-locations=classpath*:com/cml/springboot/sample/db/resource/* 3 | #db.mybatis.type-aliases-package=com.cml.springboot.sample.bean 4 | #db.mybatis.type-handler-package=com.cml.springboot.framework.mybatis.typehandler 5 | 6 | 7 | db.mybatis.mapperLocations=classpath*:com/cml/springboot/sample/db/resource/* 8 | db.mybatis.typeAliasesPackage=com.cml.springboot.sample.bean 9 | db.mybatis.typeHandlerPackage=com.cml.springboot.framework.mybatis.typehandler 10 | 11 | db.mybatis.jdbc.driverClassName=com.mysql.jdbc.Driver 12 | db.mybatis.jdbc.url=jdbc:mysql://localhost/springboot?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull 13 | db.mybatis.jdbc.username=root 14 | db.mybatis.jdbc.password=1234 15 | 16 | # \u6700\u5927\u63a5\u7d9a\u6570 17 | db.mybatis.jdbc.maxActive=20 18 | #\u672a\u4f7f\u7528\u306e\u63a5\u7d9a\u3092\u4fdd\u6301\u3059\u308b\u6700\u5927\u6570 19 | db.mybatis.jdbc.maxIdle=2 20 | #\u672a\u4f7f\u7528\u306e\u63a5\u7d9a\u3092\u4fdd\u6301\u3059\u308b\u6700\u5c0f\u6570 21 | db.mybatis.jdbc.minIdle=2 22 | db.mybatis.jdbc.maxWait=1000 23 | #\u521d\u59cb\u521b\u5efa\u8fde\u63a5\u6570 24 | db.mybatis.jdbc.initialSize=2 25 | db.mybatis.jdbc.validationQuery=SELECT 1 26 | 27 | #-----------mybatis--------------- -------------------------------------------------------------------------------- /web/src/main/resources/config/application.properties: -------------------------------------------------------------------------------- 1 | endpoints.beans.id=springbeans 2 | endpoints.beans.sensitive=false 3 | endpoints.shutdown.enabled=true 4 | 5 | spring.datasource.initialize=false 6 | 7 | # \u81ea\u5b9a\u4e49\u7aef\u53e3 8 | server.port=2222 9 | 10 | #\u5173\u95EDbanner\u8BBE\u7F6E 11 | spring.main.banner-mode=off 12 | 13 | #spring.resources.staticLocations=*\.html,/*.html 14 | #spring.devtools.restart.exclude=static/**,public/**,src/main/webapp/** 15 | 16 | spring.mvc.view.prefix=/ 17 | spring.mvc.view.suffix=.jsp 18 | application.message=Hello Phil 19 | 20 | 21 | #\u5f02\u6b65\u5904\u7406\u914d\u7f6e 22 | async.task.config.corePoolSize=5 23 | async.task.config.maxPoolSize=500 24 | 25 | #\u5f02\u5e38\u8fd4\u56de\u5904\u7406\u914d\u7f6e true\u8868\u793a\u4e0d\u5bf9\u5916\u66b4\u9732\u5f02\u5e38\u4fe1\u606f\uff0c\u53ea\u8fd4\u56de\u56fa\u5b9a\u7684${exception.response.messasge} 26 | exception.response.filter=true 27 | #exception.response.contentType=application/json 28 | exception.response.messasge=exception 29 | 30 | #log\u914d\u7f6e TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. 31 | #logging.file=logs/api.log 32 | #logging.path=logs %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} 33 | #logging.level.root=INFO 34 | #logging.level.org.springframework.web=DEBUG 35 | #logging.level.org.hibernate=ERROR 36 | 37 | 38 | #logging.config=classpath:log4j2.xml -------------------------------------------------------------------------------- /web/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J\u914d\u7f6e 2 | log4j.rootCategory=INFO,stdout,file 3 | log4j.logger.com.cml.springboot.framework.interceptor=INFO,logfile 4 | log4j.logger.org.mybatis.spring.SqlSessionFactoryBean=ALL,stdout,logfile 5 | 6 | ###\u663e\u793aSQL\u8bed\u53e5\u90e8\u5206 7 | log4j.logger.org.mybatis=ALL 8 | log4j.logger.org.apache=ALL 9 | log4j.logger.org.apache.ibatis.logging.jdbc=ALL 10 | log4j.logger.java.sql=ALL 11 | log4j.logger.com.cml.springboot=ALL 12 | 13 | # \u63a7\u5236\u53f0\u8f93\u51fa 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 17 | 18 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 19 | log4j.appender.file=org.apache.log4j.DailyRollingFileAppender 20 | log4j.appender.file.file=logs/springboot.log 21 | log4j.appender.file.DatePattern='.'yyyy-MM-dd 22 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 23 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n 24 | 25 | # \u65e5\u5fd7\u8f93\u51fa\u5230\u6587\u4ef6 26 | log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender 27 | log4j.appender.logfile.file=logs/api.log 28 | log4j.appender.logfile.DatePattern='.'yyyy-MM-dd 29 | log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 30 | log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n -------------------------------------------------------------------------------- /web/src/main/resources/public/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 404 8 | 9 | -------------------------------------------------------------------------------- /web/src/main/webapp/WEB-INF/jsp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 234567890=-"src/main/webapp/test.jsp" 11 | 12 | -------------------------------------------------------------------------------- /web/src/main/webapp/WEB-INF/jsp/welcome.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> 4 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 5 | 6 | 7 | 8 | 9 | 10 | 11 | Spring URL: ${springUrl} at ${time} 12 |
13 | JSTL URL: ${url} 14 |
15 | Message: ${message} 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /web/src/main/webapp/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

master api demo

9 |

10 | 16 |

注:为了测试方便,将请求url设置为可接受get方式

17 | 18 | -------------------------------------------------------------------------------- /web/src/main/webapp/demo.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 4 | 5 | 6 | 7 | 8 | Insert title here 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /web/src/main/webapp/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | errors 11 | 12 | -------------------------------------------------------------------------------- /web/src/main/webapp/static/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

9 | 登录测试 10 | 登录测试 11 | 登录测试 12 | 13 | -------------------------------------------------------------------------------- /web/src/main/webapp/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 | 23456789 test 11 | 12 | -------------------------------------------------------------------------------- /web/src/main/webapp/upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | upload 8 | 9 |
10 | 11 | 12 |
13 |
14 |
15 | 16 | 17 |
18 | 19 | -------------------------------------------------------------------------------- /web/src/test/java/com/cml/springboot/controller/test/HelloControllerIT.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import java.net.URL; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.context.embedded.LocalServerPort; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.web.client.TestRestTemplate; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | //@RunWith(SpringRunner.class) 16 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 | public class HelloControllerIT { 18 | 19 | @LocalServerPort 20 | private int port; 21 | 22 | private URL base; 23 | 24 | @Autowired 25 | private TestRestTemplate template; 26 | 27 | @Before 28 | public void setUp() throws Exception { 29 | this.base = new URL("http://localhost:" + port + "/"); 30 | } 31 | 32 | @Test 33 | public void getHello() throws Exception { 34 | ResponseEntity response = template.getForEntity(base.toString(), String.class); 35 | // assertThat(response.getBody(), equalTo("Hello World!")); 36 | } 37 | } -------------------------------------------------------------------------------- /web/src/test/java/com/cml/springboot/controller/test/HelloControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cml.springboot.controller.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | import org.springframework.test.web.servlet.MockMvc; 10 | 11 | //@RunWith(SpringRunner.class) 12 | //@SpringBootTest 13 | //@AutoConfigureMockMvc 14 | public class HelloControllerTest { 15 | 16 | @Autowired 17 | private MockMvc mvc; 18 | 19 | @Test 20 | public void getHello() throws Exception { 21 | // mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) 22 | // .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); 23 | } 24 | } --------------------------------------------------------------------------------