├── .gitignore ├── README.md ├── example-spring-boot-starter-test ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── zwd │ │ └── spring │ │ └── boot │ │ └── starter │ │ └── test │ │ └── SpringbootStarterTest.java │ └── resources │ └── application.properties ├── example-spring-boot-starter ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── zwd │ │ └── springbootstarter │ │ ├── config │ │ ├── ExampleAutoConfigure.java │ │ └── ExampleServiceProperties.java │ │ └── service │ │ └── ExampleService.java │ └── resources │ └── META-INF │ └── spring.factories ├── hot.md ├── image ├── hot-bulid.png ├── hot-start.png ├── swagger-home.png ├── swagger-info.png └── swagger-request.png ├── mulidatasource.md ├── pom.xml ├── profile.md ├── rabbitmq-example ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── rabbitmqexample │ │ │ ├── RabbitmqExampleApplication.java │ │ │ ├── config │ │ │ ├── MessageRabbitMqConfiguration.java │ │ │ └── QueueConstants.java │ │ │ ├── controller │ │ │ └── TestController.java │ │ │ ├── entity │ │ │ └── MessageEntity.java │ │ │ └── util │ │ │ ├── HelloReceiver.java │ │ │ ├── HelloSender.java │ │ │ ├── MessageConsumer.java │ │ │ └── MessageProvider.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── rabbitmqexample │ └── RabbitmqExampleApplicationTests.java ├── redis.md ├── spring-boot-admin-in-docker ├── LICENSE ├── README.md ├── admin-client │ ├── LICENSE │ ├── README.md │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── liumapp │ │ │ │ └── demo │ │ │ │ └── admin │ │ │ │ └── client │ │ │ │ ├── AdminClientMain.java │ │ │ │ └── schedule │ │ │ │ └── ScheduleLogGenerator.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── liumapp │ │ └── demo │ │ └── admin │ │ └── client │ │ └── package-info.java ├── admin-eureka │ ├── LICENSE │ ├── README.md │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── liumapp │ │ │ │ └── demo │ │ │ │ └── admin │ │ │ │ └── eureka │ │ │ │ └── AdminEurekaMain.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── liumapp │ │ └── demo │ │ └── admin │ │ └── eureka │ │ └── package-info.java ├── admin-server │ ├── LICENSE │ ├── README.md │ ├── pom.xml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── liumapp │ │ │ │ └── demo │ │ │ │ └── admin │ │ │ │ └── server │ │ │ │ └── AdminServerMain.java │ │ └── resources │ │ │ └── application.yml │ │ └── test │ │ └── java │ │ └── com │ │ └── liumapp │ │ └── demo │ │ └── admin │ │ └── server │ │ └── package-info.java ├── build-image.sh ├── docker-compose.yml ├── log │ ├── admin-client.log.2018-09-12.0.gz │ └── admin-client.log.2018-09-13.0.gz ├── pic │ ├── version1.0.1-1.jpg │ ├── version1.0.1-2.jpg │ ├── version1.0.jpg │ ├── version1.3.0-1.jpg │ ├── version1.3.0-2.jpg │ ├── version2.1-1.jpg │ └── version2.1-2.jpg ├── pom.xml └── rm-image.sh ├── spring-boot-hot ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── springboothot │ │ │ └── SpringBootHotApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── springboothot │ └── SpringBootHotApplicationTests.java ├── spring-boot-mybatis-mulidatasource ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── neo │ │ │ │ ├── Application.java │ │ │ │ ├── datasource │ │ │ │ ├── DataSource1Config.java │ │ │ │ └── DataSource2Config.java │ │ │ │ ├── entity │ │ │ │ └── UserEntity.java │ │ │ │ ├── mapper │ │ │ │ ├── test1 │ │ │ │ │ └── User1Mapper.java │ │ │ │ └── test2 │ │ │ │ │ └── User2Mapper.java │ │ │ │ └── web │ │ │ │ └── UserController.java │ │ └── resources │ │ │ ├── application.properties │ │ │ └── mybatis │ │ │ ├── mapper │ │ │ ├── test1 │ │ │ │ └── UserMapper.xml │ │ │ └── test2 │ │ │ │ └── UserMapper.xml │ │ │ └── mybatis-config.xml │ └── test │ │ └── java │ │ └── com │ │ └── neo │ │ ├── ApplicationTests.java │ │ └── mapper │ │ ├── User1MapperTest.java │ │ └── User2MapperTest.java └── users.sql ├── spring-boot-profiles ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── springbootprofiles │ │ │ └── SpringBootProfilesApplication.java │ └── resources │ │ ├── application-dev.properties │ │ ├── application-rc.properties │ │ ├── application-test.properties │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── springbootprofiles │ └── SpringBootProfilesApplicationTests.java ├── spring-boot-redis ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── springbootredis │ │ │ ├── SpringBootRedisApplication.java │ │ │ ├── config │ │ │ └── RedisConfig.java │ │ │ └── domain │ │ │ └── User.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── springbootredis │ └── SpringBootRedisApplicationTests.java ├── spring-boot-swagger2 ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── springbootswagger2 │ │ │ ├── SpringBootSwagger2Application.java │ │ │ ├── config │ │ │ └── Swagger2.java │ │ │ └── controller │ │ │ └── UserController.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── springbootswagger2 │ └── SpringBootSwagger2ApplicationTests.java ├── springboot-jpa-example ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── zwd │ │ │ └── example │ │ │ └── jpa │ │ │ ├── Application.java │ │ │ ├── User.java │ │ │ └── UserRepository.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── zwd │ └── example │ └── jpa │ └── ApplicationTests.java ├── springboot-jwt-demo ├── .gitigore ├── README.md ├── img │ ├── 1536139112248.jpg │ └── 1536139919870.jpg ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ ├── config │ │ │ └── BeanRegisterConfig.java │ │ │ ├── controller │ │ │ └── LoginController.java │ │ │ ├── filter │ │ │ └── MyFilter.java │ │ │ └── util │ │ │ └── JwtHelper.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── DemoApplicationTests.java ├── springboot-mybatis-pageHelper ├── .gitignore ├── README.md ├── images │ └── 1.png ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── wqs │ │ └── root │ │ ├── SpringbootMybatisRedisApplication.java │ │ ├── controller │ │ └── UserController.java │ │ ├── domain │ │ └── User.java │ │ ├── mapper │ │ └── UserMapper.java │ │ ├── service │ │ └── UserService.java │ │ └── util │ │ └── MyPage.java │ └── resources │ └── mapper │ └── UserMapper.xml ├── springboot-outh2.0 ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── zwd │ │ └── example │ │ └── spring │ │ └── outh │ │ ├── Application.java │ │ ├── config │ │ └── SecurityConfig.java │ │ ├── controller │ │ └── UserController.java │ │ └── server │ │ ├── CustomAuthenticationServerConfig.java │ │ └── CustomResourceServerConfig.java │ └── resources │ └── application.yml ├── springboot-property-example ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── zwd │ │ │ └── propertyexample │ │ │ ├── PropertyExampleApplication.java │ │ │ └── properties │ │ │ └── UserProperties.java │ └── resources │ │ ├── application-dev.properties │ │ ├── application-prod.properties │ │ ├── application-test.properties │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── zwd │ └── propertyexample │ └── PropertyExampleApplicationTests.java ├── springboot-security ├── .gitigore ├── README.md ├── img │ ├── 1536139112248.jpg │ └── 1536139919870.jpg ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── DemoApplication.java │ │ │ ├── config │ │ │ └── SecurityConfiguration.java │ │ │ ├── controller │ │ │ ├── AdminController.java │ │ │ └── EmployeeController.java │ │ │ ├── domain │ │ │ ├── Admin.java │ │ │ └── Employee.java │ │ │ ├── filter │ │ │ ├── JwtAuthenticationFilter.java │ │ │ └── JwtLoginFilter.java │ │ │ ├── service │ │ │ └── impl │ │ │ │ └── UserDetailServiceImpl.java │ │ │ └── util │ │ │ └── JwtUtils.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── demo │ └── DemoApplicationTests.java ├── springboot-websocket ├── README.md ├── index.html ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── zwd │ └── example │ └── websocket │ ├── Application.java │ ├── config │ └── WebSocketConfig.java │ ├── contoller │ └── WebSocketController.java │ └── domain │ └── WebSocketServer.java ├── starter.md ├── swagger.md └── swagger_info.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | *.iml 26 | 27 | target 28 | 29 | .idea 30 | 31 | .DS_Store 32 | 33 | 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## SpringBoot 2 | ----- 3 | ## 基础教程 4 | 5 | 6 | - [springboot properties文件使用技巧](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-property-example) 7 | 8 | - [springboot 集成redis](./redis.md) 9 | 10 | - [springboot热部署实战](./hot.md) 11 | 12 | - [springboot实现多环境配置动态解析](./profile.md) 13 | 14 | ## 高级教程 15 | 16 | - [springboot2.0整合spring security outh2.0](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-outh2.0) 17 | 18 | 19 | - [springboot2.0 集成spring security实现权限管理](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-security) 20 | 21 | - [springboot2.0 集成webSocket实现实时通信](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-websocket) 22 | 23 | 24 | - [springboot2.0 集成jwt实现token认证](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-jwt-demo) 25 | 26 | - [springboot2.0 集成rabbitmq实现队列DLQ](https://github.com/DespairYoke/spring-boot-examples/tree/master/rabbitmq-example) 27 | 28 | - [springboot2.0 集成swagger2](./swagger.md) 29 | 30 | - [springboot2.0 集成spring-data-jpa](https://github.com/DespairYoke/spring-boot-examples/tree/master/springboot-jpa-example) 31 | 32 | - [springboot2.0 集成mybatis配置多数据源](./mulidatasource.md) 33 | 34 | - [springboot2.0 自定义starter](./starter.md) 35 | 36 | -------------------------------------------------------------------------------- /example-spring-boot-starter-test/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | example-spring-boot-starter-test 13 | 14 | 15 | 16 | 17 | com.zwd.example.springboot 18 | example-spring-boot-starter 19 | 1.0-SNAPSHOT 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | -------------------------------------------------------------------------------- /example-spring-boot-starter-test/src/main/java/com/zwd/spring/boot/starter/test/SpringbootStarterTest.java: -------------------------------------------------------------------------------- 1 | package com.zwd.spring.boot.starter.test; 2 | 3 | import com.example.zwd.springbootstarter.config.ExampleAutoConfigure; 4 | import com.example.zwd.springbootstarter.service.ExampleService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.context.annotation.Import; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @SpringBootApplication 13 | @RestController 14 | @Import(ExampleAutoConfigure.class) 15 | public class SpringbootStarterTest { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(SpringbootStarterTest.class, args); 19 | } 20 | 21 | @Autowired 22 | private ExampleService exampleService; 23 | 24 | @GetMapping("/input") 25 | public String input(String word){ 26 | return exampleService.wrap(word); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /example-spring-boot-starter-test/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #example.service.enabled=true 2 | #example.service.prefix=#### 3 | #example.service.suffix=@@@@ -------------------------------------------------------------------------------- /example-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | example-spring-boot-starter 13 | 1.0-SNAPSHOT 14 | example-spring-boot-starter 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-autoconfigure 20 | 21 | 22 | -------------------------------------------------------------------------------- /example-spring-boot-starter/src/main/java/com/example/zwd/springbootstarter/config/ExampleAutoConfigure.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootstarter.config; 2 | 3 | import com.example.zwd.springbootstarter.service.ExampleService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 8 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | 12 | @Configuration 13 | @ConditionalOnClass(ExampleService.class) 14 | @EnableConfigurationProperties(ExampleServiceProperties.class) 15 | public class ExampleAutoConfigure { 16 | 17 | @Autowired 18 | private ExampleServiceProperties properties; 19 | 20 | @Bean 21 | @ConditionalOnMissingBean 22 | @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true") 23 | ExampleService exampleService (){ 24 | return new ExampleService(properties.getPrefix(),properties.getSuffix()); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /example-spring-boot-starter/src/main/java/com/example/zwd/springbootstarter/config/ExampleServiceProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootstarter.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties("example.service") 6 | public class ExampleServiceProperties { 7 | 8 | private String prefix; 9 | 10 | private String suffix; 11 | 12 | public String getPrefix() { 13 | return prefix; 14 | } 15 | 16 | public void setPrefix(String prefix) { 17 | this.prefix = prefix; 18 | } 19 | 20 | public String getSuffix() { 21 | return suffix; 22 | } 23 | 24 | public void setSuffix(String suffix) { 25 | this.suffix = suffix; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /example-spring-boot-starter/src/main/java/com/example/zwd/springbootstarter/service/ExampleService.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootstarter.service; 2 | 3 | public class ExampleService { 4 | 5 | private String prefix; 6 | 7 | private String suffix; 8 | 9 | public String getPrefix() { 10 | return prefix; 11 | } 12 | 13 | public void setPrefix(String prefix) { 14 | this.prefix = prefix; 15 | } 16 | 17 | public String getSuffix() { 18 | return suffix; 19 | } 20 | 21 | public void setSuffix(String suffix) { 22 | this.suffix = suffix; 23 | } 24 | 25 | public ExampleService(String prefix, String suffix) { 26 | this.prefix = prefix; 27 | this.suffix = suffix; 28 | } 29 | 30 | public String wrap(String word) { 31 | return word ; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /example-spring-boot-starter/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.zwd.springbootstarter.config.ExampleAutoConfigure -------------------------------------------------------------------------------- /hot.md: -------------------------------------------------------------------------------- 1 | ## springboot热部署 2 | 3 | [官网连接](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html) 4 | 5 | spring-boot-devtools 最重要的功能就是热部署。它会监听 classpath 下的文件变动,并且会立即重启应用。 6 | ```java 7 | 8 | org.springframework.boot 9 | spring-boot-devtools 10 | true 11 | 12 | 13 | ``` 14 | ` true`true表示依赖不会传递。 15 | 如果,希望指定文件夹下的文件改变的时候,重新启动 Spring Boot,我们只要在 src/main/resources/application.properties 中配置信息。 16 | 17 | spring.devtools.restart.additional-paths= # Additional paths to watch for changes. 18 | 19 | - 启动实例 20 | ```java 21 | @SpringBootApplication 22 | @RestController 23 | public class SpringBootHotApplication { 24 | 25 | @Value(value = "${username}") 26 | private String name; 27 | 28 | public static void main(String[] args) { 29 | SpringApplication.run(SpringBootHotApplication.class, args); 30 | } 31 | 32 | @GetMapping(value = "/") 33 | public String index() { 34 | return "hello "+ name; 35 | } 36 | 37 | } 38 | ``` 39 | - application.properties 40 | ```properties 41 | server.port=8001 42 | username=name 43 | 44 | spring.devtools.restart.additional-paths=resources/application.properties 45 | ``` 46 | 使用`mvn spring-boot:run`启动项目。 47 | ![](./image/hot-start.png) 48 | 49 | 访问http://localhost:8001 响应信息如下 50 | 51 | hello name 52 | 53 | 保持项目启动,修改配置文件name改为其他(如:zwd)。打开一个新的命令行窗口,使用maven编译命令进行编译。 54 | 55 | ![](./image/hot-bulid.png) 56 | 57 | 编译成功后再次访问http://localhost:8001, 58 | 响应信息如下 59 | 60 | hello zwd 61 | 62 | [项目地址](./spring-boot-hot) -------------------------------------------------------------------------------- /image/hot-bulid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/image/hot-bulid.png -------------------------------------------------------------------------------- /image/hot-start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/image/hot-start.png -------------------------------------------------------------------------------- /image/swagger-home.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/image/swagger-home.png -------------------------------------------------------------------------------- /image/swagger-info.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/image/swagger-info.png -------------------------------------------------------------------------------- /image/swagger-request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/image/swagger-request.png -------------------------------------------------------------------------------- /mulidatasource.md: -------------------------------------------------------------------------------- 1 | ## springboot配置mybatis多数据源 2 | 3 | 所谓多数据源,其实连接两dataSource,而每个dataSource生成的sqlFactory管理着不同的xml。 4 | 只要使用时,根据业务选择自己所需的mapper即可。 5 | 6 | springboot1.x时,可用DataSourceBuilder进行生成数据源,2.x以后必须手动配置数据源。 7 | - 1.x配置 8 | ```java 9 | @Bean(name = "test1DataSource") 10 | @ConfigurationProperties(prefix = "spring.datasource.test1") 11 | @Primary 12 | public DataSource testDataSource() { 13 | return DataSourceBuilder.create().build(); 14 | } 15 | 16 | ``` 17 | - 2.x配置 18 | ```java 19 | @Autowired 20 | Environment env; 21 | @Bean(name = "test1DataSource") 22 | @Primary 23 | public DataSource testDataSource() { 24 | DriverManagerDataSource dataSource = new DriverManagerDataSource(); 25 | dataSource.setDriverClassName(env.getProperty("test1.driverClassName")); 26 | dataSource.setUrl(env.getProperty("test1.url")); 27 | dataSource.setUsername(env.getProperty("test1.username")); 28 | dataSource.setPassword(env.getProperty("test1.password")); 29 | return dataSource; 30 | } 31 | ``` 32 | ### 项目搭建 33 | 34 | - applicaiton.properties配置文件 35 | ```properties 36 | mybatis.config-locations=classpath:mybatis/mybatis-config.xml 37 | 38 | test1.driverClassName= com.mysql.cj.jdbc.Driver 39 | test1.url = jdbc:mysql://localhost:3306/zwdtest?useUnicode=true 40 | test1.username = root 41 | test1.password = root 42 | 43 | 44 | test2.driverClassName = com.mysql.cj.jdbc.Driver 45 | test2.url = jdbc:mysql://localhost:3306/zwdtest?useUnicode=true 46 | test2.username = root 47 | test2.password = root 48 | ``` 49 | 根据自己需求添加或更改所需数据源。 50 | 51 | - 配置类(重点) 52 | 每个datasource都对应着自己的配置类,这里查看一下test1的配置上类。如下 53 | 54 | ```java 55 | @Configuration 56 | @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate") 57 | public class DataSource1Config { 58 | 59 | @Autowired 60 | Environment env; 61 | @Bean(name = "test1DataSource") 62 | @Primary 63 | public DataSource testDataSource() { 64 | DriverManagerDataSource dataSource = new DriverManagerDataSource(); 65 | dataSource.setDriverClassName(env.getProperty("test1.driverClassName")); 66 | dataSource.setUrl(env.getProperty("test1.url")); 67 | dataSource.setUsername(env.getProperty("test1.username")); 68 | dataSource.setPassword(env.getProperty("test1.password")); 69 | return dataSource; 70 | } 71 | 72 | @Bean(name = "test1SqlSessionFactory") 73 | @Primary 74 | public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { 75 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 76 | bean.setDataSource(dataSource); 77 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); 78 | return bean.getObject(); 79 | } 80 | 81 | @Bean(name = "test1TransactionManager") 82 | @Primary 83 | public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { 84 | return new DataSourceTransactionManager(dataSource); 85 | } 86 | 87 | @Bean(name = "test1SqlSessionTemplate") 88 | @Primary 89 | public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 90 | return new SqlSessionTemplate(sqlSessionFactory); 91 | } 92 | 93 | } 94 | ``` 95 | `@MapperScan(basePackages = "com.neo.mapper.test1"`扫描对应的包。 96 | 97 | `classpath:mybatis/mapper/test1/*.xml`是此sqlfactory所能操作的xml的路径。不同的连接路径不同。 98 | 99 | - 如何使用 100 | 101 | 从项目目录可以看出mapper分为test1,test2,这是连接两个不同的数据库,当我们想要操作时,只需要选择不同包下的mapper。 102 | 103 | [项目地址](./spring-boot-mybatis-mulidatasource) -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | pom 9 | 1.0-SNAPSHOT 10 | 11 | rabbitmq-example 12 | spring-boot-admin-in-docker 13 | springboot-security 14 | springboot-property-example 15 | springboot-mybatis-pageHelper 16 | springboot-jwt-demo 17 | springboot-websocket 18 | springboot-outh2.0 19 | springboot-jpa-example 20 | example-spring-boot-starter 21 | example-spring-boot-starter-test 22 | spring-boot-mybatis-mulidatasource 23 | spring-boot-redis 24 | spring-boot-swagger2 25 | spring-boot-hot 26 | spring-boot-profiles 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-dependencies 34 | 2.1.3.RELEASE 35 | pom 36 | import 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | org.apache.maven.plugins 48 | maven-compiler-plugin 49 | 3.5.1 50 | 51 | 1.8 52 | 1.8 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /profile.md: -------------------------------------------------------------------------------- 1 | ## springboot实现多环境配置动态解析 2 | 3 | 在项目整个流程中,开发、测试和线上可能会用不同的环境配置。如果每次都更改配置的话,太过麻烦和笨重。springboot为了方便 4 | 提供了spring.profiles.active机制。只要按照application-{profile}.properties建立文件,即可切换不同的配置。 5 | 6 | ### 项目测试 7 | 8 | - 在resource下新建三个文件 9 | ```properties 10 | application-dev.properties //开发环境配置文件 11 | application-rc.properties //线上环境配置文件 12 | application-test.properties //测试环境配置文件 13 | ``` 14 | - 选择使用的配置文件 15 | 在resource/application.properties配置文件中添加一下配置项目: 16 | ```properties 17 | spring.profiles.active=dev 18 | ``` 19 | - .测试多环境配置 20 | 我们分别在 21 | ```properties 22 | application-dev.properties //开发环境配置文件 23 | application-rc.properties //线上环境配置文件 24 | application-test.properties //测试环境配置文件 25 | ``` 26 | 文件中添加以下配置: 27 | ```properties 28 | #端口号 29 | server.port=8081 30 | server.port=8082 31 | server.port=8083 32 | ``` 33 | 依次修改application.properties文件中的以下配置: 34 | ```properties 35 | spring.profiles.active=dev、test、rc 36 | ``` 37 | 修改后依次重启服务。 38 | 当使用dev的时候控制台输出一下内容: 39 | ```properties 40 | 2019-02-26 16:35:39.137 INFO 6089 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/zwd-admin/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.] 41 | 2019-02-26 16:35:39.690 INFO 6089 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 42 | 2019-02-26 16:35:39.690 INFO 6089 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6071 ms 43 | 2019-02-26 16:35:40.082 INFO 6089 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 44 | 2019-02-26 16:35:40.401 INFO 6089 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path '' 45 | 2019-02-26 16:35:40.405 INFO 6089 --- [ main] c.e.z.s.SpringBootProfilesApplication : Started SpringBootProfilesApplication in 8.212 seconds (JVM running for 9.8) 46 | ``` 47 | 使用rc的时候控制台输出一下内容: 48 | ```properties 49 | 2019-02-26 16:36:36.399 INFO 6096 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2252 ms 50 | 2019-02-26 16:36:36.759 INFO 6096 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 51 | 2019-02-26 16:36:37.097 INFO 6096 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path '' 52 | 2019-02-26 16:36:37.101 INFO 6096 --- [ main] c.e.z.s.SpringBootProfilesApplication : Started SpringBootProfilesApplication in 3.775 seconds (JVM running for 4.76) 53 | ``` 54 | 使用test的时候控制台输出一下内容: 55 | ```properties 56 | 2019-02-26 16:37:07.174 INFO 6100 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 57 | 2019-02-26 16:37:07.174 INFO 6100 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3532 ms 58 | 2019-02-26 16:37:07.505 INFO 6100 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 59 | 2019-02-26 16:37:07.760 INFO 6100 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8083 (http) with context path '' 60 | 2019-02-26 16:37:07.770 INFO 6100 --- [ main] c.e.z.s.SpringBootProfilesApplication : Started SpringBootProfilesApplication in 4.898 seconds (JVM running for 6.37) 61 | ``` 62 | 63 | 可以看出在服务启动的时候分别用了不同的配置文件。 64 | 65 | [项目地址](./spring-boot-profiles) -------------------------------------------------------------------------------- /rabbitmq-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /rabbitmq-example/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/rabbitmq-example/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /rabbitmq-example/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /rabbitmq-example/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: post 3 | tiltle: rabbitmq发布与订阅 4 | no-post-nav: true 5 | category: springboot 6 | tags: [springboot] 7 | --- 8 | 9 | ### rabbitmq发布与订阅 10 | 11 | >默认情况下如果一个 Message 被消费者所正确接收则会被从 Queue 中移除 12 | >如果一个 Queue 没被任何消费者订阅,那么这个 Queue 中的消息会被 Cache(缓存),当有消费者订阅时则会立即发送,当 Message 13 | >被消费者正确接收时,就会被从 Queue 中移除 14 | 15 | #### 消息发送确认 16 | ##### 发送的消息怎么样才算失败或成功?如何确认? 17 | 18 | #### ConfirmCallback 19 | 20 | `通过实现 ConfirmCallback 接口,消息发送到 Broker 后触发回调,确认消息是否到达 Broker 服务器,也就是只确认是否正确到达 Exchange 中` 21 | 22 | ``` java 23 | @Component 24 | public class RabbitTemplateConfig implements RabbitTemplate.ConfirmCallback{ 25 | 26 | @Autowired 27 | private RabbitTemplate rabbitTemplate; 28 | 29 | @PostConstruct 30 | public void init(){ 31 | rabbitTemplate.setConfirmCallback(this); //指定 ConfirmCallback 32 | } 33 | 34 | @Override 35 | public void confirm(CorrelationData correlationData, boolean ack, String cause) { 36 | System.out.println("消息唯一标识:"+correlationData); 37 | System.out.println("确认结果:"+ack); 38 | System.out.println("失败原因:"+cause); 39 | } 40 | ``` 41 | 42 | * 还需要在配置文件添加配置 43 | ``` yml 44 | spring: 45 | rabbitmq: 46 | publisher-confirms: true 47 | ``` 48 | #### ReturnCallback 49 | 50 | * 通过实现 ReturnCallback 接口,启动消息失败返回,比如路由不到队列时触发回调 51 | 52 | ``` java 53 | @Component 54 | public class RabbitTemplateConfig implements RabbitTemplate.ReturnCallback{ 55 | 56 | @Autowired 57 | private RabbitTemplate rabbitTemplate; 58 | 59 | @PostConstruct 60 | public void init(){ 61 | rabbitTemplate.setReturnCallback(this); //指定 ReturnCallback 62 | } 63 | 64 | @Override 65 | public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { 66 | System.out.println("消息主体 message : "+message); 67 | System.out.println("消息主体 message : "+replyCode); 68 | System.out.println("描述:"+replyText); 69 | System.out.println("消息使用的交换器 exchange : "+exchange); 70 | System.out.println("消息使用的路由键 routing : "+routingKey); 71 | } 72 | } 73 | ``` 74 | * 还需要在配置文件添加配置 75 | ``` yml 76 | spring: 77 | rabbitmq: 78 | publisher-returns: true 79 | ``` 80 | 81 | ### 消息接收确认 82 | 83 | ### 消息消费者如何通知 Rabbit 消息消费成功? 84 | 85 | * 消息通过 ACK 确认是否被正确接收,每个 Message 都要被确认(acknowledged),可以手动去 ACK 或自动 ACK 86 | * 自动确认会在消息发送给消费者后立即确认,但存在丢失消息的可能,如果消费端消费逻辑抛出异常,也就是消费端没有处理成功这条消息,那么就相当于丢失了消息 87 | * 如果消息已经被处理,但后续代码抛出异常,使用 Spring 进行管理的话消费端业务逻辑会进行回滚,这也同样造成了实际意义的消息丢失 88 | * 如果手动确认则当消费者调用 ack、nack、reject 几种方法进行确认,手动确认可以在业务失败后进行一些操作,如果消息未被 ACK 则会发送到下一个消费者 89 | * 如果某个服务忘记 ACK 了,则 RabbitMQ 不会再发送数据给它,因为 RabbitMQ 认为该服务的处理能力有限 90 | * ACK 机制还可以起到限流作用,比如在接收到某条消息时休眠几秒钟 91 | 消息确认模式有: 92 | ** AcknowledgeMode.NONE:自动确认 93 | ** AcknowledgeMode.AUTO:根据情况确认 94 | ** AcknowledgeMode.MANUAL:手动确认 95 | 96 | ``` yml 97 | spring: 98 | rabbitmq: 99 | listener: 100 | simple: 101 | acknowledge-mode: manual 102 | ``` 103 | 104 | ``` java 105 | @RabbitHandler 106 | public void processMessage2(String message,Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long tag) { 107 | System.out.println(message); 108 | try { 109 | channel.basicAck(tag,false); // 确认消息 110 | } catch (IOException e) { 111 | e.printStackTrace(); 112 | } 113 | } 114 | ```  115 | 需要注意的 basicAck 方法需要传递两个参数 116 | * deliveryTag(唯一标识 ID):当一个消费者向 RabbitMQ 注册后,会建立起一个 Channel ,RabbitMQ 会用 basic.deliver 方法向消费者推送消息,这个方法携带了一个 delivery tag, 它代表了 RabbitMQ 向该 Channel 投递的这条消息的唯一标识 ID,是一个单调递增的正整数,delivery tag 的范围仅限于 Channel 117 | * multiple:为了减少网络流量,手动确认可以被批处理,当该参数为 true 时,则可以一次性确认 delivery_tag 小于等于传入值的所有消息 118 | -------------------------------------------------------------------------------- /rabbitmq-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example.zwd 7 | rabbitmq-example 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | rabbitmq-example 12 | Demo project for Spring Boot 13 | 14 | 15 | com.zwd.example.springboot 16 | spring-boot-examples 17 | 1.0-SNAPSHOT 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-amqp 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-web 36 | 37 | 38 | 39 | com.alibaba 40 | fastjson 41 | 1.2.44 42 | 43 | 44 | 45 | org.projectlombok 46 | lombok 47 | true 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-maven-plugin 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/RabbitmqExampleApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RabbitmqExampleApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RabbitmqExampleApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/config/MessageRabbitMqConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.config; 2 | 3 | import org.springframework.amqp.core.*; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | /** 8 | * @author zwd 9 | * @date 2018/11/19 14:47 10 | * @Email stephen.zwd@gmail.com 11 | */ 12 | @Configuration 13 | public class MessageRabbitMqConfiguration { 14 | /** 15 | * 交换配置 16 | * 17 | * @return 18 | */ 19 | @Bean 20 | public DirectExchange messageDirectExchange() { 21 | return (DirectExchange) ExchangeBuilder.directExchange(QueueConstants.MESSAGE_EXCHANGE) 22 | .durable(true) 23 | .build(); 24 | } 25 | 26 | /** 27 | * 消息队列声明 28 | * 29 | * @return 30 | */ 31 | @Bean 32 | public Queue messageQueue() { 33 | return QueueBuilder.durable(QueueConstants.MESSAGE_QUEUE_NAME) 34 | .build(); 35 | } 36 | 37 | /** 38 | * 消息绑定 39 | * 40 | * @return 41 | */ 42 | @Bean 43 | public Binding messageBinding() { 44 | return BindingBuilder.bind(messageQueue()) 45 | .to(messageDirectExchange()) 46 | .with(QueueConstants.MESSAGE_ROUTE_KEY); 47 | } 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/config/QueueConstants.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.config; 2 | 3 | /** 4 | * @author zwd 5 | * @date 2018/11/19 14:46 6 | * @Email stephen.zwd@gmail.com 7 | */ 8 | public interface QueueConstants { 9 | /** 10 | * 消息交换 11 | */ 12 | String MESSAGE_EXCHANGE = "message.direct.exchange"; 13 | /** 14 | * 消息队列名称 15 | */ 16 | String MESSAGE_QUEUE_NAME = "message.queue"; 17 | 18 | /** 19 | * 消息路由键 20 | */ 21 | String MESSAGE_ROUTE_KEY = "message.send"; 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.controller; 2 | 3 | import com.example.zwd.rabbitmqexample.entity.MessageEntity; 4 | import com.example.zwd.rabbitmqexample.util.HelloSender; 5 | import com.example.zwd.rabbitmqexample.util.MessageProvider; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | /** 11 | * @author zwd 12 | * @date 2018/11/19 15:50 13 | * @Email stephen.zwd@gmail.com 14 | */ 15 | @RestController 16 | public class TestController { 17 | // /** 18 | // * 消息队列 - 消息提供者 注入 19 | // */ 20 | // @Autowired 21 | // private MessageProvider messageProvider; 22 | // /** 23 | // * 测试发送消息队列方法 24 | // * 25 | // * @param messageEntity 发送消息实体内容 26 | // * @return 27 | // */ 28 | // @RequestMapping(value = "/index") 29 | // public String index(MessageEntity messageEntity) { 30 | // // 将实体实例写入消息队列 31 | // messageProvider.sendMessage(messageEntity); 32 | // return "Success"; 33 | // } 34 | 35 | @Autowired 36 | private HelloSender helloSender; 37 | 38 | @RequestMapping(value = "/index") 39 | public String sayhello (MessageEntity messageEntity) { 40 | // 将实体实例写入消息队列 41 | helloSender.send(messageEntity); 42 | return "Success"; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/entity/MessageEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.entity; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * @author zwd 9 | * @date 2018/11/19 15:22 10 | * @Email stephen.zwd@gmail.com 11 | */ 12 | @Data 13 | public class MessageEntity implements Serializable { 14 | /** 15 | * 消息内容 16 | */ 17 | private String content; 18 | } 19 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/util/HelloReceiver.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.util; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.zwd.rabbitmqexample.config.QueueConstants; 5 | import com.example.zwd.rabbitmqexample.entity.MessageEntity; 6 | import com.rabbitmq.client.Channel; 7 | import com.rabbitmq.client.ReturnCallback; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.amqp.core.Message; 11 | import org.springframework.amqp.rabbit.annotation.RabbitHandler; 12 | import org.springframework.amqp.rabbit.annotation.RabbitListener; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.messaging.handler.annotation.Payload; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.stereotype.Service; 17 | 18 | import java.io.IOException; 19 | 20 | /** 21 | * @author zwd 22 | * @date 2018/11/19 16:14 23 | * @Email stephen.zwd@gmail.com 24 | */ 25 | @Service 26 | @RabbitListener(queues = QueueConstants.MESSAGE_QUEUE_NAME) 27 | public class HelloReceiver { 28 | 29 | Logger logger = LoggerFactory.getLogger(HelloReceiver.class); 30 | 31 | @RabbitHandler 32 | public void handler(@Payload MessageEntity messageEntity, Channel channel, Message message) { 33 | logger.info("消费内容:{}", JSON.toJSONString(messageEntity)); 34 | try { 35 | //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发 36 | channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); 37 | } catch (IOException e) { 38 | e.printStackTrace(); 39 | //丢弃这条消息 40 | //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false); 41 | logger.info("receiver fail"); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/util/HelloSender.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.util; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.zwd.rabbitmqexample.config.QueueConstants; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.amqp.core.Message; 8 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | /** 13 | * @author zwd 14 | * @date 2018/11/19 16:02 15 | * @Email stephen.zwd@gmail.com 16 | */ 17 | @Service 18 | public class HelloSender implements RabbitTemplate.ReturnCallback{ 19 | 20 | @Autowired 21 | private RabbitTemplate rabbitTemplate; 22 | static Logger logger = LoggerFactory.getLogger(HelloSender.class); 23 | public void send(Object object) { 24 | logger.info("写入消息队列内容:{}", JSON.toJSONString(object)); 25 | rabbitTemplate.setMandatory(true); 26 | rabbitTemplate.setReturnCallback(this); 27 | this.rabbitTemplate.setConfirmCallback((correlationData,ack,cause)-> { 28 | if (!ack) { 29 | logger.info("HelloSender 消息发送失败"+ cause + correlationData.toString()); 30 | }else { 31 | logger.info("HelloSender 消息发送成功"); 32 | } 33 | }); 34 | rabbitTemplate.convertAndSend(QueueConstants.MESSAGE_EXCHANGE,QueueConstants.MESSAGE_ROUTE_KEY,object); 35 | } 36 | @Override 37 | public void returnedMessage(Message message, int i, String s, String s1, String s2) { 38 | System.out.println("server"); 39 | logger.info("sender return success" + message.toString()+"==="+i+"==="+s1+"==="+s2); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/util/MessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.util; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.zwd.rabbitmqexample.config.QueueConstants; 5 | import com.example.zwd.rabbitmqexample.entity.MessageEntity; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.amqp.rabbit.annotation.RabbitHandler; 9 | import org.springframework.amqp.rabbit.annotation.RabbitListener; 10 | import org.springframework.messaging.handler.annotation.Payload; 11 | import org.springframework.stereotype.Component; 12 | 13 | /** 14 | * @author zwd 15 | * @date 2018/11/19 15:42 16 | * @Email stephen.zwd@gmail.com 17 | */ 18 | //@Component 19 | //@RabbitListener(queues = QueueConstants.MESSAGE_QUEUE_NAME) 20 | public class MessageConsumer { 21 | /** 22 | * logger instance 23 | */ 24 | static Logger logger = LoggerFactory.getLogger(MessageConsumer.class); 25 | 26 | @RabbitHandler 27 | public void handler(@Payload MessageEntity messageEntity) { 28 | logger.info("消费内容:{}", JSON.toJSONString(messageEntity)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/java/com/example/zwd/rabbitmqexample/util/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample.util; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.example.zwd.rabbitmqexample.config.QueueConstants; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.amqp.core.AmqpTemplate; 8 | import org.springframework.amqp.rabbit.core.RabbitTemplate; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | 12 | /** 13 | * @author zwd 14 | * @date 2018/11/19 15:41 15 | * @Email stephen.zwd@gmail.com 16 | */ 17 | //@Component 18 | public class MessageProvider { 19 | /** 20 | * logger instance 21 | */ 22 | static Logger logger = LoggerFactory.getLogger(MessageProvider.class); 23 | /** 24 | * 消息队列模板 25 | */ 26 | @Autowired 27 | private AmqpTemplate amqpTemplate; 28 | 29 | public void sendMessage(Object object) { 30 | logger.info("写入消息队列内容:{}", JSON.toJSONString(object)); 31 | // rabbitTemplate.setReturnCallback(); 32 | amqpTemplate.convertAndSend(QueueConstants.MESSAGE_EXCHANGE, QueueConstants.MESSAGE_ROUTE_KEY, object); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /rabbitmq-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | spring.rabbitmq.host=47.96.127.51 3 | spring.rabbitmq.port=5672 4 | spring.rabbitmq.username=springcloud 5 | spring.rabbitmq.password=123456 6 | # 开启发送确认 7 | spring.rabbitmq.publisher-confirms=true 8 | # 开启发送失败退回 9 | spring.rabbitmq.publisher-returns=true 10 | # 开启ACK 11 | spring.rabbitmq.listener.direct.acknowledge-mode=manual 12 | spring.rabbitmq.listener.simple.acknowledge-mode=manual 13 | 14 | -------------------------------------------------------------------------------- /rabbitmq-example/src/test/java/com/example/zwd/rabbitmqexample/RabbitmqExampleApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.rabbitmqexample; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RabbitmqExampleApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /redis.md: -------------------------------------------------------------------------------- 1 | ## springboot集成Redis缓存实战 2 | 3 | springboot官网 4 | 5 | You can inject an auto-configured RedisConnectionFactory, StringRedisTemplate, 6 | or vanilla RedisTemplate instance as you would any other Spring Bean. 7 | 8 | 可见如果我们key value都是简单的字符串,可以直接使用stringRedisTemplate;但如果是更复杂的数据存储。那就要手动生成RedisTemplete。 9 | 10 | ### StringRedisTemplate演示 11 | - maven依赖 12 | ```xml 13 | 14 | org.springframework.boot 15 | spring-boot-starter-data-redis 16 | 17 | ``` 18 | - application.properties文件配置 19 | ```properties 20 | # Redis数据库索引(默认为0),如果设置为1,那么存入的key-value都存放在select 1中 21 | spring.redis.database=0 22 | # Redis服务器地址 23 | spring.redis.host=127.0.0.1 24 | # Redis服务器连接端口 25 | spring.redis.port=6379 26 | # Redis服务器连接密码(默认为空) 27 | spring.redis.password=password 28 | ``` 29 | - test类编写 30 | ```java 31 | @RunWith(SpringRunner.class) 32 | @SpringBootTest 33 | public class SpringBootRedisApplicationTests { 34 | 35 | @Autowired 36 | private StringRedisTemplate template; 37 | 38 | @Test 39 | public void contextLoads() { 40 | 41 | 42 | template.opsForValue().set("name","zwd"); 43 | Assert.assertEquals("zwd",template.opsForValue().get("name")); 44 | 45 | } 46 | } 47 | ``` 48 | 49 | ### RedisTemplate使用示例 50 | 51 | - redisTemplate必须手动创建bean。 52 | 53 | ```java 54 | @Configuration 55 | public class RedisConfig { 56 | 57 | @Bean 58 | public RedisTemplate redisTemplate (RedisConnectionFactory factory) { 59 | 60 | RedisTemplate redisTemplate = new RedisTemplate<>(); 61 | redisTemplate.setConnectionFactory(factory); 62 | 63 | return redisTemplate; 64 | } 65 | } 66 | ``` 67 | - 创建一个pojo 68 | ```java 69 | public class User implements Serializable { 70 | 71 | private String name; 72 | 73 | private int age; 74 | 75 | //省略get set toString 76 | } 77 | 78 | ``` 79 | - Test示例 80 | ```java 81 | @RunWith(SpringRunner.class) 82 | @SpringBootTest 83 | public class SpringBootRedisApplicationTests { 84 | 85 | @Autowired 86 | private StringRedisTemplate template; 87 | 88 | @Autowired 89 | private RedisTemplate redisTemplate; 90 | @Test 91 | public void contextLoads() { 92 | 93 | 94 | template.opsForValue().set("name","zwd"); 95 | Assert.assertEquals("zwd",template.opsForValue().get("name")); 96 | 97 | } 98 | 99 | @Test 100 | public void TestRedisTemplete() { 101 | 102 | User user = new User(); 103 | user.setName("朱卫东"); 104 | user.setAge(11); 105 | redisTemplate.opsForValue().set("user",user); 106 | System.out.println(redisTemplate.opsForValue().get("user")); 107 | 108 | } 109 | 110 | } 111 | ``` 112 | 113 | [项目地址](./spring-boot-redis) 114 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-admin-in-docker 2 | 在docker中部署一个由spring boot admin管理的服务集群 3 | 4 | Deploying a service cluster managed by spring boot admin in docker 5 | 6 | [Spring Boot admin document](http://codecentric.github.io/spring-boot-admin/2.0.2/#getting-started) 7 | 8 | [使用文档](https://github.com/liumapp/spring-boot-admin-in-docker/wiki) 9 | 10 | ## How to use 11 | 12 | ### Using Docker 13 | 14 | update both application.yml in admin-server and admin-client 15 | 16 | 17 | spring: 18 | profiles: 19 | active: docker 20 | 21 | run 22 | 23 | ./build-image.sh 24 | 25 | to install docker images 26 | 27 | run 28 | 29 | docker-compose up -d 30 | 31 | wait a few seconds , and open your browser , and visit http://localhost:8766 32 | 33 | the username is : admin 34 | 35 | the password is : adminadmin 36 | 37 | you can change it by update application.yml 38 | 39 | to stop the docker container , run the following command: 40 | 41 | docker-compose down 42 | 43 | to remove the docker images , run the following command: 44 | 45 | ./rm-image.sh 46 | 47 | ### Using IDEA 48 | 49 | update both application.yml in admin-server and admin-client 50 | 51 | spring: 52 | profiles: 53 | active: dev 54 | 55 | start admin-eureka first , then admin-server and admin-client 56 | 57 | open your browser and visit http://localhost:8766 58 | 59 | done. 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/README.md: -------------------------------------------------------------------------------- 1 | # basic-maven-archetype 2 | Basic maven archetype for util project . 3 | 4 | ## how to use 5 | 6 | 7 | mvn archetype:create-from-project 8 | 9 | cd target 10 | 11 | cd generated-sources 12 | 13 | cd archetype 14 | 15 | mvn install 16 | 17 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | spring-boot-admin-in-docker 6 | com.liumapp.demo.admin 7 | v4.1.0 8 | 9 | 10 | com.liumapp.demo.admin.client 11 | admin-client 12 | v4.1.0 13 | jar 14 | 15 | admin-client 16 | http://maven.apache.org 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-actuator 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | de.codecentric 29 | spring-boot-admin-starter-client 30 | 1.5.6 31 | 32 | 33 | org.springframework.cloud 34 | spring-cloud-starter-eureka 35 | 1.3.2.RELEASE 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | org.jolokia 44 | jolokia-core 45 | 46 | 47 | com.liumapp.qtools.date 48 | qtools-date 49 | v1.0.5 50 | 51 | 52 | 53 | 54 | 55 | 56 | com.spotify 57 | docker-maven-plugin 58 | 1.0.0 59 | 60 | liumapp/${project.artifactId}:${project.version} 61 | java:8 62 | ["java", "-jar", "/${project.build.finalName}.jar"] 63 | 64 | 65 | / 66 | ${project.build.directory} 67 | ${project.build.finalName}.jar 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/src/main/java/com/liumapp/demo/admin/client/AdminClientMain.java: -------------------------------------------------------------------------------- 1 | package com.liumapp.demo.admin.client; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.scheduling.annotation.EnableScheduling; 7 | 8 | 9 | @SpringBootApplication 10 | @EnableDiscoveryClient 11 | @EnableScheduling 12 | public class AdminClientMain { 13 | 14 | public static void main (String[] args) { 15 | SpringApplication.run(AdminClientMain.class, args); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/src/main/java/com/liumapp/demo/admin/client/schedule/ScheduleLogGenerator.java: -------------------------------------------------------------------------------- 1 | package com.liumapp.demo.admin.client.schedule; 2 | 3 | import com.liumapp.qtools.date.DateTool; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.scheduling.annotation.Scheduled; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.util.Date; 10 | 11 | 12 | @Component 13 | public class ScheduleLogGenerator { 14 | 15 | private static Logger LOGGER = LoggerFactory.getLogger(ScheduleLogGenerator.class); 16 | 17 | @Scheduled(fixedRate = 3000) 18 | public void reportLogTime () { 19 | LOGGER.info(DateTool.getDateString(new Date(), "yyyy-MM-dd HH:mm:ss")); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8111 3 | 4 | eureka: 5 | client: 6 | serviceUrl: 7 | defaultZone: http://localhost:1234/eureka/ 8 | 9 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-client/src/test/java/com/liumapp/demo/admin/client/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by liumapp on 9/28/17. 3 | * E-mail:liumapp.com@gmail.com 4 | * home-page:http://www.liumapp.com 5 | */ 6 | package com.liumapp.demo.admin.client; -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-eureka/README.md: -------------------------------------------------------------------------------- 1 | # basic-maven-archetype 2 | Basic maven archetype for util project . 3 | 4 | ## how to use 5 | 6 | 7 | mvn archetype:create-from-project 8 | 9 | cd target 10 | 11 | cd generated-sources 12 | 13 | cd archetype 14 | 15 | mvn install 16 | 17 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-eureka/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | spring-boot-admin-in-docker 7 | com.liumapp.demo.admin 8 | v4.1.0 9 | 10 | 11 | com.liumapp.demo.admin.eureka 12 | admin-eureka 13 | v4.1.0 14 | jar 15 | 16 | 17 | admin-eureka 18 | http://maven.apache.org 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-starter-netflix-eureka-server 24 | 1.4.5.RELEASE 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-autoconfigure 34 | 35 | 36 | 37 | 38 | 39 | 40 | com.spotify 41 | docker-maven-plugin 42 | 1.0.0 43 | 44 | liumapp/${project.artifactId}:${project.version} 45 | java:8 46 | ["java", "-jar", "/${project.build.finalName}.jar"] 47 | 48 | 49 | / 50 | ${project.build.directory} 51 | ${project.build.finalName}.jar 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-eureka/src/main/java/com/liumapp/demo/admin/eureka/AdminEurekaMain.java: -------------------------------------------------------------------------------- 1 | package com.liumapp.demo.admin.eureka; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 7 | 8 | 9 | @SpringBootApplication 10 | @EnableEurekaServer 11 | public class AdminEurekaMain { 12 | 13 | public static void main (String[] args) { 14 | SpringApplication.run(AdminEurekaMain.class, args); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-eureka/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 1234 3 | 4 | eureka: 5 | instance: 6 | prefer-ip-address: false 7 | client: 8 | register-with-eureka: false 9 | fetch-registry: false 10 | service-url: 11 | defaultZone: http://localhost:1234/eureka/ -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-eureka/src/test/java/com/liumapp/demo/admin/eureka/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by liumapp on 9/28/17. 3 | * E-mail:liumapp.com@gmail.com 4 | * home-page:http://www.liumapp.com 5 | */ 6 | package com.liumapp.demo.admin.eureka; -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-server/README.md: -------------------------------------------------------------------------------- 1 | # basic-maven-archetype 2 | Basic maven archetype for util project . 3 | 4 | ## how to use 5 | 6 | 7 | mvn archetype:create-from-project 8 | 9 | cd target 10 | 11 | cd generated-sources 12 | 13 | cd archetype 14 | 15 | mvn install 16 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | spring-boot-admin-in-docker 6 | com.liumapp.demo.admin 7 | v4.1.0 8 | 9 | 10 | com.liumapp.demo.admin.server 11 | admin-server 12 | v4.1.0 13 | jar 14 | 15 | 16 | admin-server 17 | http://maven.apache.org 18 | 19 | 20 | 21 | de.codecentric 22 | spring-boot-admin-server 23 | 1.5.6 24 | 25 | 26 | de.codecentric 27 | spring-boot-admin-server-ui 28 | 1.5.6 29 | 30 | 31 | 32 | de.codecentric 33 | spring-boot-admin-server-ui-login 34 | 1.5.6 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-web 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | org.springframework.cloud 53 | spring-cloud-starter-netflix-eureka-client 54 | 1.4.5.RELEASE 55 | 56 | 57 | org.jolokia 58 | jolokia-core 59 | 60 | 61 | 62 | 63 | 64 | 65 | com.spotify 66 | docker-maven-plugin 67 | 1.0.0 68 | 69 | liumapp/${project.artifactId}:${project.version} 70 | java:8 71 | ["java", "-jar", "/${project.build.finalName}.jar"] 72 | 73 | 74 | / 75 | ${project.build.directory} 76 | ${project.build.finalName}.jar 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-server/src/main/java/com/liumapp/demo/admin/server/AdminServerMain.java: -------------------------------------------------------------------------------- 1 | package com.liumapp.demo.admin.server; 2 | 3 | import de.codecentric.boot.admin.config.EnableAdminServer; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 10 | 11 | 12 | @Configuration 13 | @EnableAutoConfiguration 14 | @EnableDiscoveryClient 15 | @EnableAdminServer 16 | public class AdminServerMain { 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(AdminServerMain.class, args); 20 | } 21 | 22 | @Configuration 23 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 24 | @Override 25 | protected void configure(HttpSecurity http) throws Exception { 26 | http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll(); 27 | http.logout().logoutUrl("/logout"); 28 | http.csrf().disable(); 29 | 30 | http.authorizeRequests() 31 | .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**").permitAll(); 32 | 33 | http.authorizeRequests().antMatchers("/api/**").permitAll().antMatchers("/**") 34 | .authenticated(); 35 | 36 | // Enable so that the clients can authenticate via HTTP basic for registering 37 | http.httpBasic(); 38 | } 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | file: "tmp/boot.log" 3 | 4 | management: 5 | context-path: "/actuator" 6 | 7 | spring: 8 | application: 9 | name: "@pom.artifactId@" 10 | boot: 11 | admin: 12 | url: http://localhost:8080 13 | profiles: 14 | active: 15 | - secure 16 | 17 | --- 18 | spring: 19 | profiles: insecure 20 | 21 | management: 22 | security: 23 | enabled: false 24 | 25 | security: 26 | basic: 27 | enabled: false 28 | 29 | --- 30 | spring: 31 | profiles: secure 32 | boot: 33 | admin: 34 | username: "${security.user.name}" 35 | password: "${security.user.password}" 36 | client: 37 | metadata: 38 | user.name: "${security.user.name}" 39 | user.password: "${security.user.password}" 40 | 41 | security: 42 | user: 43 | name: user 44 | password: pass 45 | 46 | eureka: 47 | client: 48 | serviceUrl: 49 | defaultZone: http://sign-online-eureka:1234/eureka/ 50 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/admin-server/src/test/java/com/liumapp/demo/admin/server/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by liumapp on 9/28/17. 3 | * E-mail:liumapp.com@gmail.com 4 | * home-page:http://www.liumapp.com 5 | */ 6 | package com.liumapp.demo.admin.server; -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/build-image.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo '=============================================================' 4 | echo '$ $' 5 | echo '$ liumapp $' 6 | echo '$ $' 7 | echo '$ $' 8 | echo '$ email: liumapp.com@gmail.com $' 9 | echo '$ homePage: http://www.liumapp.com $' 10 | echo '$ Github: https://github.com/liumapp $' 11 | echo '$ $' 12 | echo '=============================================================' 13 | echo '.' 14 | 15 | mvn clean install -Dmaven.test.skip=true 16 | 17 | cd admin-client 18 | 19 | mvn clean package -Dmaven.test.skip=true docker:build 20 | 21 | cd .. 22 | 23 | cd admin-eureka 24 | 25 | mvn clean package -Dmaven.test.skip=true docker:build 26 | 27 | cd .. 28 | 29 | cd admin-server 30 | 31 | mvn clean package -Dmaven.test.skip=true docker:build 32 | 33 | cd .. 34 | 35 | echo 'success' 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | admin-client: 5 | image: liumapp/admin-client:v4.1.0 6 | restart: always 7 | container_name: admin-client 8 | hostname: admin-client 9 | ports: 10 | - "7373:7373" 11 | volumes: 12 | - ./log/:/spring-boot-admin-in-docker/log/ 13 | admin-server: 14 | image: liumapp/admin-server:v4.1.0 15 | restart: always 16 | container_name: admin-server 17 | hostname: admin-server 18 | ports: 19 | - "8766:8766" 20 | volumes: 21 | - ./log/:/spring-boot-admin-in-docker/log/ 22 | admin-eureka: 23 | image: liumapp/admin-eureka:v4.1.0 24 | restart: always 25 | hostname: admin-eureka 26 | container_name: admin-eureka 27 | ports: 28 | - '1234:1234' 29 | 30 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/log/admin-client.log.2018-09-12.0.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/log/admin-client.log.2018-09-12.0.gz -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/log/admin-client.log.2018-09-13.0.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/log/admin-client.log.2018-09-13.0.gz -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version1.0.1-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version1.0.1-1.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version1.0.1-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version1.0.1-2.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version1.0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version1.0.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version1.3.0-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version1.3.0-1.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version1.3.0-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version1.3.0-2.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version2.1-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version2.1-1.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pic/version2.1-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-admin-in-docker/pic/version2.1-2.jpg -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | 11 | com.liumapp.demo.admin 12 | spring-boot-admin-in-docker 13 | v4.1.0 14 | pom 15 | 16 | 17 | UTF-8 18 | UTF-8 19 | 1.8 20 | 21 | Dalston.SR2 22 | 23 | 24 | 25 | 26 | 27 | admin-eureka 28 | admin-server 29 | admin-client 30 | 31 | 32 | 33 | 34 | 35 | org.springframework.cloud 36 | spring-cloud-dependencies 37 | ${spring-cloud.version} 38 | pom 39 | import 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | 50 | 51 | 52 | repackage 53 | build-info 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /spring-boot-admin-in-docker/rm-image.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo '=============================================================' 4 | echo '$ $' 5 | echo '$ liumapp $' 6 | echo '$ $' 7 | echo '$ $' 8 | echo '$ email: liumapp.com@gmail.com $' 9 | echo '$ homePage: http://www.liumapp.com $' 10 | echo '$ Github: https://github.com/liumapp $' 11 | echo '$ $' 12 | echo '=============================================================' 13 | echo '.' 14 | 15 | docker rmi liumapp/admin-client:v4.1.0 16 | 17 | docker rmi liumapp/admin-server:v4.1.0 18 | 19 | docker rmi liumapp/admin-eureka:v4.1.0 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /spring-boot-hot/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | -------------------------------------------------------------------------------- /spring-boot-hot/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.net.URL; 25 | import java.nio.channels.Channels; 26 | import java.nio.channels.ReadableByteChannel; 27 | import java.util.Properties; 28 | 29 | public class MavenWrapperDownloader { 30 | 31 | /** 32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 33 | */ 34 | private static final String DEFAULT_DOWNLOAD_URL = 35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 36 | 37 | /** 38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 39 | * use instead of the default one. 40 | */ 41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 42 | ".mvn/wrapper/maven-wrapper.properties"; 43 | 44 | /** 45 | * Path where the maven-wrapper.jar will be saved to. 46 | */ 47 | private static final String MAVEN_WRAPPER_JAR_PATH = 48 | ".mvn/wrapper/maven-wrapper.jar"; 49 | 50 | /** 51 | * Name of the property which should be used to override the default download url for the wrapper. 52 | */ 53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 54 | 55 | public static void main(String args[]) { 56 | System.out.println("- Downloader started"); 57 | File baseDirectory = new File(args[0]); 58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 59 | 60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 61 | // wrapperUrl parameter. 62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 63 | String url = DEFAULT_DOWNLOAD_URL; 64 | if(mavenWrapperPropertyFile.exists()) { 65 | FileInputStream mavenWrapperPropertyFileInputStream = null; 66 | try { 67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 68 | Properties mavenWrapperProperties = new Properties(); 69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 71 | } catch (IOException e) { 72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 73 | } finally { 74 | try { 75 | if(mavenWrapperPropertyFileInputStream != null) { 76 | mavenWrapperPropertyFileInputStream.close(); 77 | } 78 | } catch (IOException e) { 79 | // Ignore ... 80 | } 81 | } 82 | } 83 | System.out.println("- Downloading from: : " + url); 84 | 85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 86 | if(!outputFile.getParentFile().exists()) { 87 | if(!outputFile.getParentFile().mkdirs()) { 88 | System.out.println( 89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 90 | } 91 | } 92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 93 | try { 94 | downloadFileFromURL(url, outputFile); 95 | System.out.println("Done"); 96 | System.exit(0); 97 | } catch (Throwable e) { 98 | System.out.println("- Error downloading"); 99 | e.printStackTrace(); 100 | System.exit(1); 101 | } 102 | } 103 | 104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 105 | URL website = new URL(urlString); 106 | ReadableByteChannel rbc; 107 | rbc = Channels.newChannel(website.openStream()); 108 | FileOutputStream fos = new FileOutputStream(destination); 109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 110 | fos.close(); 111 | rbc.close(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /spring-boot-hot/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-hot/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-hot/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /spring-boot-hot/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | com.example.zwd 11 | spring-boot-hot 12 | 0.0.1-SNAPSHOT 13 | spring-boot-hot 14 | Demo project for Spring Boot 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-devtools 28 | true 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-test 33 | test 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-maven-plugin 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /spring-boot-hot/src/main/java/com/example/zwd/springboothot/SpringBootHotApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springboothot; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @SpringBootApplication 10 | @RestController 11 | public class SpringBootHotApplication { 12 | 13 | @Value(value = "${username}") 14 | private String name; 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(SpringBootHotApplication.class, args); 18 | } 19 | 20 | @GetMapping(value = "/") 21 | public String index() { 22 | return "hello "+ name; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /spring-boot-hot/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8001 2 | username=name 3 | 4 | spring.devtools.restart.additional-paths=resources/application.properties -------------------------------------------------------------------------------- /spring-boot-hot/src/test/java/com/example/zwd/springboothot/SpringBootHotApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springboothot; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootHotApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | 7 | com.zwd.example.springboot 8 | spring-boot-examples 9 | 1.0-SNAPSHOT 10 | 11 | 12 | com.neo 13 | spring-boot-mybatis-mulidatasource 14 | 1.0.0 15 | jar 16 | 17 | spring-boot-mybatis-mulidatasource 18 | Demo project for Spring Boot and mybatis 19 | 20 | 21 | UTF-8 22 | 1.8 23 | 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-test 33 | test 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-web 38 | 39 | 40 | org.mybatis.spring.boot 41 | mybatis-spring-boot-starter 42 | 1.1.1 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-devtools 51 | true 52 | 53 | 54 | 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-maven-plugin 60 | 61 | true 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/Application.java: -------------------------------------------------------------------------------- 1 | package com.neo; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | public class Application { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(Application.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/datasource/DataSource1Config.java: -------------------------------------------------------------------------------- 1 | package com.neo.datasource; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.mybatis.spring.SqlSessionFactoryBean; 5 | import org.mybatis.spring.SqlSessionTemplate; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Primary; 13 | import org.springframework.context.support.GenericApplicationContext; 14 | import org.springframework.core.env.Environment; 15 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 16 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 17 | import org.springframework.jdbc.datasource.DriverManagerDataSource; 18 | 19 | import javax.sql.DataSource; 20 | 21 | 22 | @Configuration 23 | @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate") 24 | public class DataSource1Config { 25 | 26 | @Autowired 27 | Environment env; 28 | @Bean(name = "test1DataSource") 29 | @Primary 30 | public DataSource testDataSource() { 31 | DriverManagerDataSource dataSource = new DriverManagerDataSource(); 32 | dataSource.setDriverClassName(env.getProperty("test1.driverClassName")); 33 | dataSource.setUrl(env.getProperty("test1.url")); 34 | dataSource.setUsername(env.getProperty("test1.username")); 35 | dataSource.setPassword(env.getProperty("test1.password")); 36 | return dataSource; 37 | } 38 | 39 | @Bean(name = "test1SqlSessionFactory") 40 | @Primary 41 | public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { 42 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 43 | bean.setDataSource(dataSource); 44 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); 45 | return bean.getObject(); 46 | } 47 | 48 | @Bean(name = "test1TransactionManager") 49 | @Primary 50 | public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { 51 | return new DataSourceTransactionManager(dataSource); 52 | } 53 | 54 | @Bean(name = "test1SqlSessionTemplate") 55 | @Primary 56 | public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 57 | return new SqlSessionTemplate(sqlSessionFactory); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/datasource/DataSource2Config.java: -------------------------------------------------------------------------------- 1 | package com.neo.datasource; 2 | 3 | import org.apache.ibatis.session.SqlSessionFactory; 4 | import org.mybatis.spring.SqlSessionFactoryBean; 5 | import org.mybatis.spring.SqlSessionTemplate; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.boot.jdbc.DataSourceBuilder; 11 | import org.springframework.context.ApplicationContext; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.support.GenericApplicationContext; 15 | import org.springframework.core.env.Environment; 16 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 17 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 18 | import org.springframework.jdbc.datasource.DriverManagerDataSource; 19 | 20 | import javax.sql.DataSource; 21 | 22 | /** 23 | * Created by summer on 2016/11/25. 24 | */ 25 | @Configuration 26 | @MapperScan(basePackages = "com.neo.mapper.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate") 27 | public class DataSource2Config { 28 | 29 | @Autowired 30 | Environment env; 31 | @Bean(name = "test2DataSource") 32 | public DataSource testDataSource() { 33 | 34 | DriverManagerDataSource dataSource = new DriverManagerDataSource(); 35 | dataSource.setDriverClassName(env.getProperty("test2.driverClassName")); 36 | dataSource.setUrl(env.getProperty("test2.url")); 37 | dataSource.setUsername(env.getProperty("test2.username")); 38 | dataSource.setPassword(env.getProperty("test2.password")); 39 | return dataSource; 40 | } 41 | 42 | @Bean(name = "test2SqlSessionFactory") 43 | public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception { 44 | SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 45 | bean.setDataSource(dataSource); 46 | bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml")); 47 | return bean.getObject(); 48 | } 49 | 50 | @Bean(name = "test2TransactionManager") 51 | public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) { 52 | return new DataSourceTransactionManager(dataSource); 53 | } 54 | 55 | @Bean(name = "test2SqlSessionTemplate") 56 | public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { 57 | return new SqlSessionTemplate(sqlSessionFactory); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/entity/UserEntity.java: -------------------------------------------------------------------------------- 1 | package com.neo.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.neo.enums.UserSexEnum; 6 | 7 | public class UserEntity implements Serializable { 8 | 9 | private static final long serialVersionUID = 1L; 10 | private Long id; 11 | private String userName; 12 | private String passWord; 13 | private String nickName; 14 | 15 | public UserEntity() { 16 | super(); 17 | } 18 | 19 | public UserEntity(String userName, String passWord) { 20 | super(); 21 | this.passWord = passWord; 22 | this.userName = userName; 23 | } 24 | 25 | public Long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(Long id) { 30 | this.id = id; 31 | } 32 | 33 | public String getUserName() { 34 | return userName; 35 | } 36 | 37 | public void setUserName(String userName) { 38 | this.userName = userName; 39 | } 40 | 41 | public String getPassWord() { 42 | return passWord; 43 | } 44 | 45 | public void setPassWord(String passWord) { 46 | this.passWord = passWord; 47 | } 48 | 49 | 50 | public String getNickName() { 51 | return nickName; 52 | } 53 | 54 | public void setNickName(String nickName) { 55 | this.nickName = nickName; 56 | } 57 | 58 | @Override 59 | public String toString() { 60 | // TODO Auto-generated method stub 61 | return "userName " + this.userName + ", pasword " + this.passWord + "sex " ; 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/mapper/test1/User1Mapper.java: -------------------------------------------------------------------------------- 1 | package com.neo.mapper.test1; 2 | 3 | import com.neo.entity.UserEntity; 4 | 5 | import java.util.List; 6 | 7 | public interface User1Mapper { 8 | 9 | List getAll(); 10 | 11 | UserEntity getOne(Long id); 12 | 13 | void insert(UserEntity user); 14 | 15 | void update(UserEntity user); 16 | 17 | void delete(Long id); 18 | 19 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/mapper/test2/User2Mapper.java: -------------------------------------------------------------------------------- 1 | package com.neo.mapper.test2; 2 | 3 | import java.util.List; 4 | 5 | import com.neo.entity.UserEntity; 6 | 7 | public interface User2Mapper { 8 | 9 | List getAll(); 10 | 11 | UserEntity getOne(Long id); 12 | 13 | void insert(UserEntity user); 14 | 15 | void update(UserEntity user); 16 | 17 | void delete(Long id); 18 | 19 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/java/com/neo/web/UserController.java: -------------------------------------------------------------------------------- 1 | package com.neo.web; 2 | 3 | import java.util.List; 4 | 5 | import com.neo.mapper.test1.User1Mapper; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import com.neo.entity.UserEntity; 13 | import com.neo.mapper.test2.User2Mapper; 14 | 15 | @RestController 16 | public class UserController { 17 | 18 | @Autowired 19 | private User1Mapper user1Mapper; 20 | 21 | @Autowired 22 | private User2Mapper user2Mapper; 23 | 24 | @RequestMapping("/getUsers") 25 | public List getUsers() { 26 | List users=user1Mapper.getAll(); 27 | return users; 28 | } 29 | 30 | @RequestMapping("/getUser") 31 | public UserEntity getUser(Long id) { 32 | System.out.println("user2"); 33 | UserEntity user=user2Mapper.getOne(id); 34 | return user; 35 | } 36 | 37 | @RequestMapping("/add") 38 | public void save(@RequestBody UserEntity user) { 39 | System.out.println("user2"); 40 | user2Mapper.insert(user); 41 | } 42 | 43 | @RequestMapping(value="update") 44 | public void update(UserEntity user) { 45 | user2Mapper.update(user); 46 | } 47 | 48 | @RequestMapping(value="/delete/{id}") 49 | public void delete(@PathVariable("id") Long id) { 50 | user1Mapper.delete(id); 51 | } 52 | 53 | 54 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | mybatis.config-locations=classpath:mybatis/mybatis-config.xml 2 | 3 | test1.driverClassName= com.mysql.cj.jdbc.Driver 4 | test1.url = jdbc:mysql://localhost:3306/zwdtest?useUnicode=true 5 | test1.username = root 6 | test1.password = root 7 | 8 | 9 | test2.driverClassName = com.mysql.cj.jdbc.Driver 10 | test2.url = jdbc:mysql://localhost:3306/zwdtest?useUnicode=true 11 | test2.username = root 12 | test2.password = root -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/resources/mybatis/mapper/test1/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | id, userName, passWord, nick_name 13 | 14 | 15 | 20 | 21 | 27 | 28 | 29 | INSERT INTO 30 | users 31 | (userName,passWord) 32 | VALUES 33 | (#{userName}, #{passWord}) 34 | 35 | 36 | 37 | UPDATE 38 | users 39 | SET 40 | userName = #{userName}, 41 | passWord = #{passWord}, 42 | nick_name = #{nickName} 43 | WHERE 44 | id = #{id} 45 | 46 | 47 | 48 | DELETE FROM 49 | users 50 | WHERE 51 | id =#{id} 52 | 53 | 54 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/resources/mybatis/mapper/test2/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | id, userName, passWord, nick_name 13 | 14 | 15 | 20 | 21 | 27 | 28 | 29 | INSERT INTO 30 | users 31 | (userName,passWord) 32 | VALUES 33 | (#{userName}, #{passWord}) 34 | 35 | 36 | 37 | UPDATE 38 | users 39 | SET 40 | userName = #{userName}, 41 | passWord = #{passWord}, 42 | nick_name = #{nickName} 43 | WHERE 44 | id = #{id} 45 | 46 | 47 | 48 | DELETE FROM 49 | users 50 | WHERE 51 | id =#{id} 52 | 53 | 54 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/main/resources/mybatis/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/test/java/com/neo/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.neo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | System.out.println("hello world"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/test/java/com/neo/mapper/User1MapperTest.java: -------------------------------------------------------------------------------- 1 | package com.neo.mapper; 2 | 3 | import java.util.List; 4 | 5 | import com.neo.mapper.test1.User1Mapper; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import com.neo.entity.UserEntity; 14 | import com.neo.enums.UserSexEnum; 15 | 16 | @RunWith(SpringRunner.class) 17 | @SpringBootTest 18 | public class User1MapperTest { 19 | 20 | @Autowired 21 | private User1Mapper userMapper; 22 | 23 | @Test 24 | public void testInsert() throws Exception { 25 | userMapper.insert(new UserEntity("aa", "a123456")); 26 | userMapper.insert(new UserEntity("bb", "b123456")); 27 | userMapper.insert(new UserEntity("cc", "b123456")); 28 | 29 | Assert.assertEquals(3, userMapper.getAll().size()); 30 | } 31 | 32 | @Test 33 | public void testQuery() throws Exception { 34 | List users = userMapper.getAll(); 35 | if(users==null || users.size()==0){ 36 | System.out.println("is null"); 37 | }else{ 38 | System.out.println(users.size()); 39 | } 40 | } 41 | 42 | 43 | @Test 44 | public void testUpdate() throws Exception { 45 | UserEntity user = userMapper.getOne(6l); 46 | System.out.println(user.toString()); 47 | user.setNickName("neo"); 48 | userMapper.update(user); 49 | Assert.assertTrue(("neo".equals(userMapper.getOne(6l).getNickName()))); 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/src/test/java/com/neo/mapper/User2MapperTest.java: -------------------------------------------------------------------------------- 1 | package com.neo.mapper; 2 | 3 | import com.neo.entity.UserEntity; 4 | import com.neo.enums.UserSexEnum; 5 | import com.neo.mapper.test2.User2Mapper; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import java.util.List; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | public class User2MapperTest { 18 | 19 | @Autowired 20 | private User2Mapper userMapper; 21 | 22 | @Test 23 | public void testInsert() throws Exception { 24 | userMapper.insert(new UserEntity("aa", "a123456")); 25 | userMapper.insert(new UserEntity("bb", "b123456")); 26 | userMapper.insert(new UserEntity("cc", "b123456")); 27 | 28 | Assert.assertEquals(3, userMapper.getAll().size()); 29 | } 30 | 31 | @Test 32 | public void testQuery() throws Exception { 33 | List users = userMapper.getAll(); 34 | if(users==null || users.size()==0){ 35 | System.out.println("is null"); 36 | }else{ 37 | System.out.println(users.toString()); 38 | } 39 | } 40 | 41 | 42 | @Test 43 | public void testUpdate() throws Exception { 44 | UserEntity user = userMapper.getOne(6l); 45 | System.out.println(user.toString()); 46 | user.setNickName("neo"); 47 | userMapper.update(user); 48 | Assert.assertTrue(("neo".equals(userMapper.getOne(6l).getNickName()))); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /spring-boot-mybatis-mulidatasource/users.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : 本地 5 | Source Server Version : 50505 6 | Source Host : localhost:3306 7 | Source Database : test1 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50505 11 | File Encoding : 65001 12 | 13 | Date: 2016-11-05 21:17:33 14 | */ 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for `users` 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `users`; 22 | CREATE TABLE `users` ( 23 | `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id', 24 | `userName` varchar(32) DEFAULT NULL COMMENT '用户名', 25 | `passWord` varchar(32) DEFAULT NULL COMMENT '密码', 26 | `user_sex` varchar(32) DEFAULT NULL, 27 | `nick_name` varchar(32) DEFAULT NULL, 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8; 30 | 31 | -------------------------------------------------------------------------------- /spring-boot-profiles/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | -------------------------------------------------------------------------------- /spring-boot-profiles/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-profiles/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-profiles/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /spring-boot-profiles/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | com.example.zwd 11 | spring-boot-profiles 12 | 0.0.1-SNAPSHOT 13 | spring-boot-profiles 14 | Demo project for Spring Boot 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-maven-plugin 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /spring-boot-profiles/src/main/java/com/example/zwd/springbootprofiles/SpringBootProfilesApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootprofiles; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootProfilesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootProfilesApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-profiles/src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 -------------------------------------------------------------------------------- /spring-boot-profiles/src/main/resources/application-rc.properties: -------------------------------------------------------------------------------- 1 | server.port=8082 -------------------------------------------------------------------------------- /spring-boot-profiles/src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | server.port=8083 -------------------------------------------------------------------------------- /spring-boot-profiles/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=test -------------------------------------------------------------------------------- /spring-boot-profiles/src/test/java/com/example/zwd/springbootprofiles/SpringBootProfilesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootprofiles; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootProfilesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-redis/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | -------------------------------------------------------------------------------- /spring-boot-redis/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.net.URL; 25 | import java.nio.channels.Channels; 26 | import java.nio.channels.ReadableByteChannel; 27 | import java.util.Properties; 28 | 29 | public class MavenWrapperDownloader { 30 | 31 | /** 32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 33 | */ 34 | private static final String DEFAULT_DOWNLOAD_URL = 35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 36 | 37 | /** 38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 39 | * use instead of the default one. 40 | */ 41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 42 | ".mvn/wrapper/maven-wrapper.properties"; 43 | 44 | /** 45 | * Path where the maven-wrapper.jar will be saved to. 46 | */ 47 | private static final String MAVEN_WRAPPER_JAR_PATH = 48 | ".mvn/wrapper/maven-wrapper.jar"; 49 | 50 | /** 51 | * Name of the property which should be used to override the default download url for the wrapper. 52 | */ 53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 54 | 55 | public static void main(String args[]) { 56 | System.out.println("- Downloader started"); 57 | File baseDirectory = new File(args[0]); 58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 59 | 60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 61 | // wrapperUrl parameter. 62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 63 | String url = DEFAULT_DOWNLOAD_URL; 64 | if(mavenWrapperPropertyFile.exists()) { 65 | FileInputStream mavenWrapperPropertyFileInputStream = null; 66 | try { 67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 68 | Properties mavenWrapperProperties = new Properties(); 69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 71 | } catch (IOException e) { 72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 73 | } finally { 74 | try { 75 | if(mavenWrapperPropertyFileInputStream != null) { 76 | mavenWrapperPropertyFileInputStream.close(); 77 | } 78 | } catch (IOException e) { 79 | // Ignore ... 80 | } 81 | } 82 | } 83 | System.out.println("- Downloading from: : " + url); 84 | 85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 86 | if(!outputFile.getParentFile().exists()) { 87 | if(!outputFile.getParentFile().mkdirs()) { 88 | System.out.println( 89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 90 | } 91 | } 92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 93 | try { 94 | downloadFileFromURL(url, outputFile); 95 | System.out.println("Done"); 96 | System.exit(0); 97 | } catch (Throwable e) { 98 | System.out.println("- Error downloading"); 99 | e.printStackTrace(); 100 | System.exit(1); 101 | } 102 | } 103 | 104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 105 | URL website = new URL(urlString); 106 | ReadableByteChannel rbc; 107 | rbc = Channels.newChannel(website.openStream()); 108 | FileOutputStream fos = new FileOutputStream(destination); 109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 110 | fos.close(); 111 | rbc.close(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /spring-boot-redis/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-redis/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-redis/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /spring-boot-redis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | com.example.zwd 11 | spring-boot-redis 12 | 0.0.1-SNAPSHOT 13 | spring-boot-redis 14 | Demo project for Spring Boot 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-data-redis 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-maven-plugin 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /spring-boot-redis/src/main/java/com/example/zwd/springbootredis/SpringBootRedisApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootredis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootRedisApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootRedisApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-redis/src/main/java/com/example/zwd/springbootredis/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootredis.config; 2 | 3 | 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.redis.connection.RedisConnectionFactory; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | 9 | @Configuration 10 | public class RedisConfig { 11 | 12 | @Bean 13 | public RedisTemplate redisTemplate (RedisConnectionFactory factory) { 14 | 15 | RedisTemplate redisTemplate = new RedisTemplate<>(); 16 | redisTemplate.setConnectionFactory(factory); 17 | 18 | return redisTemplate; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spring-boot-redis/src/main/java/com/example/zwd/springbootredis/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootredis.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | public class User implements Serializable { 6 | 7 | private String name; 8 | 9 | private int age; 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | 19 | public int getAge() { 20 | return age; 21 | } 22 | 23 | public void setAge(int age) { 24 | this.age = age; 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return "User{" + 30 | "name='" + name + '\'' + 31 | ", age=" + age + 32 | '}'; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-redis/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Redis数据库索引(默认为0),如果设置为1,那么存入的key-value都存放在select 1中 2 | spring.redis.database=0 3 | # Redis服务器地址 4 | spring.redis.host=47.96.127.51 5 | # Redis服务器连接端口 6 | spring.redis.port=6379 7 | # Redis服务器连接密码(默认为空) 8 | spring.redis.password=adminadmin 9 | -------------------------------------------------------------------------------- /spring-boot-redis/src/test/java/com/example/zwd/springbootredis/SpringBootRedisApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootredis; 2 | 3 | import com.example.zwd.springbootredis.domain.User; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.data.redis.core.RedisTemplate; 10 | import org.springframework.data.redis.core.StringRedisTemplate; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class SpringBootRedisApplicationTests { 16 | 17 | @Autowired 18 | private StringRedisTemplate template; 19 | 20 | @Autowired 21 | private RedisTemplate redisTemplate; 22 | @Test 23 | public void contextLoads() { 24 | 25 | 26 | template.opsForValue().set("name","zwd"); 27 | Assert.assertEquals("zwd",template.opsForValue().get("name")); 28 | 29 | } 30 | 31 | @Test 32 | public void TestRedisTemplete() { 33 | 34 | User user = new User(); 35 | user.setName("朱卫东"); 36 | user.setAge(11); 37 | redisTemplate.opsForValue().set("user",user); 38 | System.out.println(redisTemplate.opsForValue().get("user")); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-swagger2/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | -------------------------------------------------------------------------------- /spring-boot-swagger2/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/spring-boot-swagger2/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /spring-boot-swagger2/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /spring-boot-swagger2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | com.example.zwd 11 | spring-boot-swagger2 12 | 0.0.1-SNAPSHOT 13 | spring-boot-swagger2 14 | Demo project for Spring Boot 15 | 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | 27 | io.springfox 28 | springfox-swagger2 29 | 2.8.0 30 | 31 | 32 | io.springfox 33 | springfox-swagger-ui 34 | 2.8.0 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-test 39 | test 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-maven-plugin 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /spring-boot-swagger2/src/main/java/com/example/zwd/springbootswagger2/SpringBootSwagger2Application.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootswagger2; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootSwagger2Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootSwagger2Application.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-swagger2/src/main/java/com/example/zwd/springbootswagger2/config/Swagger2.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootswagger2.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import springfox.documentation.builders.ApiInfoBuilder; 6 | import springfox.documentation.builders.PathSelectors; 7 | import springfox.documentation.builders.RequestHandlerSelectors; 8 | import springfox.documentation.service.ApiInfo; 9 | import springfox.documentation.spi.DocumentationType; 10 | import springfox.documentation.spring.web.plugins.Docket; 11 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 12 | 13 | @Configuration 14 | @EnableSwagger2 15 | public class Swagger2 { 16 | /** 17 | * 通过 createRestApi函数来构建一个DocketBean 18 | * 函数名,可以随意命名,喜欢什么命名就什么命名 19 | */ 20 | @Bean 21 | public Docket createRestApi() { 22 | return new Docket(DocumentationType.SWAGGER_2) 23 | .apiInfo(apiInfo())//调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容 24 | .select() 25 | //控制暴露出去的路径下的实例 26 | //如果某个接口不想暴露,可以使用以下注解 27 | //@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下 28 | .apis(RequestHandlerSelectors.basePackage("com.example.zwd.springbootswagger2.controller")) 29 | .paths(PathSelectors.any()) 30 | .build(); 31 | } 32 | //构建 api文档的详细信息函数 33 | private ApiInfo apiInfo() { 34 | return new ApiInfoBuilder() 35 | //页面标题 36 | .title("Spring Boot Swagger2 构建RESTful API") 37 | //条款地址 38 | .termsOfServiceUrl("http://despairyoke.github.io/") 39 | .contact("zwd") 40 | .version("1.0") 41 | //描述 42 | .description("API 描述") 43 | .build(); 44 | } 45 | } -------------------------------------------------------------------------------- /spring-boot-swagger2/src/main/java/com/example/zwd/springbootswagger2/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootswagger2.controller; 2 | 3 | import io.swagger.annotations.ApiImplicitParam; 4 | import io.swagger.annotations.ApiOperation; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | public class UserController { 10 | 11 | @ApiOperation(value = "接口的功能介绍",notes = "提示接口使用者注意事项",httpMethod = "GET") 12 | @ApiImplicitParam(dataType = "string",name = "name",value = "姓名",required = true) 13 | @RequestMapping(value = "/") 14 | public String index(String name) { 15 | 16 | return "hello "+ name; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /spring-boot-swagger2/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /spring-boot-swagger2/src/test/java/com/example/zwd/springbootswagger2/SpringBootSwagger2ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.springbootswagger2; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootSwagger2ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /springboot-jpa-example/README.md: -------------------------------------------------------------------------------- 1 | ### springboot2.0 集成spring-data-jpa 2 | 3 | 对于熟悉hibernate的人,都知道使用orm的好处,这里我用spring-data-jpa的原因是因为我发现在写测试demo的时候都需要进行建库建表等一系列流程操作,这些操作使本来很简单的一个demo变的复杂化,所以我引入spring-data-jpa的orm机制,并使用create-drop,这样就脱离了对数据库的操作。 4 | 5 | 6 | #### maven依赖 7 | ```xml 8 | 9 | 10 | org.springframework.boot 11 | spring-boot-starter-data-jpa 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-web 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-test 20 | test 21 | 22 | 23 | mysql 24 | mysql-connector-java 25 | runtime 26 | 27 | 28 | ``` 29 | 实体类 30 | 31 | #### 配置文件 32 | application.properties 33 | ``` 34 | spring.datasource.url=jdbc:mysql://localhost:3306/test 35 | spring.datasource.username=root 36 | spring.datasource.password=root 37 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 38 | 39 | spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop 40 | ``` 41 | `spring.jpa.properties.hibernate.hbm2ddl.auto`是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下: 42 | 43 | `create`:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。 44 | `create-drop`:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。 45 | `update`:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。 46 | validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。 47 | 48 | #### 实体类 49 | ```java 50 | @Entity 51 | public class User { 52 | 53 | @Id 54 | @GeneratedValue 55 | private Long id; 56 | 57 | @Column(nullable = false) 58 | private String name; 59 | 60 | @Column(nullable = false) 61 | private Integer age; 62 | //省略构造 63 | //省略getset 64 | } 65 | ``` 66 | 此处要注意,必须保留一个空的构造函数,不让数据库会生成失败。 67 | 68 | #### 查询接口 69 | ```java 70 | public interface UserRepository extends JpaRepository { 71 | 72 | 73 | User findByName(String name); 74 | 75 | User findByNameAndAge(String name,Integer age); 76 | 77 | @Query("from User u where u.name =:name") 78 | User findUser(@Param("name") String name); 79 | 80 | } 81 | ``` 82 | 83 | #### 测试示例 84 | ```java 85 | @RunWith(SpringJUnit4ClassRunner.class) 86 | @SpringBootTest(classes = Application.class) 87 | public class ApplicationTests { 88 | @Autowired 89 | private UserRepository userRepository; 90 | 91 | 92 | @Test 93 | public void test() { 94 | 95 | // 创建10条记录 96 | userRepository.save(new User("AAA", 10)); 97 | userRepository.save(new User("BBB", 20)); 98 | userRepository.save(new User("CCC", 30)); 99 | userRepository.save(new User("DDD", 40)); 100 | userRepository.save(new User("EEE", 50)); 101 | userRepository.save(new User("FFF", 60)); 102 | userRepository.save(new User("GGG", 70)); 103 | userRepository.save(new User("HHH", 80)); 104 | userRepository.save(new User("III", 90)); 105 | userRepository.save(new User("JJJ", 100)); 106 | 107 | User aaa = userRepository.findByName("AAA"); 108 | System.out.println(aaa.toString()); 109 | 110 | User bbb = userRepository.findByNameAndAge("BBB", 20); 111 | System.out.println(bbb); 112 | 113 | User ccc = userRepository.findUser("CCC"); 114 | System.out.println(ccc); 115 | } 116 | } 117 | 118 | ``` -------------------------------------------------------------------------------- /springboot-jpa-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.zwd.example.springboot 7 | spring-boot-examples 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | springboot-jpa-example 13 | 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-data-jpa 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-test 27 | test 28 | 29 | 30 | mysql 31 | mysql-connector-java 32 | runtime 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /springboot-jpa-example/src/main/java/com/zwd/example/jpa/Application.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.jpa; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Application { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Application.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springboot-jpa-example/src/main/java/com/zwd/example/jpa/User.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.jpa; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | 8 | @Entity 9 | public class User { 10 | 11 | @Id 12 | @GeneratedValue 13 | private Long id; 14 | 15 | @Column(nullable = false) 16 | private String name; 17 | 18 | @Column(nullable = false) 19 | private Integer age; 20 | 21 | public User(String name, Integer age) { 22 | this.name = name; 23 | this.age = age; 24 | } 25 | 26 | public Long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | public Integer getAge() { 43 | return age; 44 | } 45 | 46 | public void setAge(Integer age) { 47 | this.age = age; 48 | } 49 | 50 | public User() { 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "User{" + 56 | "id=" + id + 57 | ", name='" + name + '\'' + 58 | ", age=" + age + 59 | '}'; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /springboot-jpa-example/src/main/java/com/zwd/example/jpa/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.jpa; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.Query; 5 | import org.springframework.data.repository.query.Param; 6 | 7 | public interface UserRepository extends JpaRepository { 8 | 9 | 10 | User findByName(String name); 11 | 12 | User findByNameAndAge(String name,Integer age); 13 | 14 | @Query("from User u where u.name =:name") 15 | User findUser(@Param("name") String name); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /springboot-jpa-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://localhost:3306/test 2 | spring.datasource.username=root 3 | spring.datasource.password=root 4 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5 | 6 | spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop 7 | -------------------------------------------------------------------------------- /springboot-jpa-example/src/test/java/com/zwd/example/jpa/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.jpa; 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.SpringJUnit4ClassRunner; 8 | 9 | 10 | @RunWith(SpringJUnit4ClassRunner.class) 11 | @SpringBootTest(classes = Application.class) 12 | public class ApplicationTests { 13 | @Autowired 14 | private UserRepository userRepository; 15 | 16 | 17 | @Test 18 | public void test() { 19 | 20 | // 创建10条记录 21 | userRepository.save(new User("AAA", 10)); 22 | userRepository.save(new User("BBB", 20)); 23 | userRepository.save(new User("CCC", 30)); 24 | userRepository.save(new User("DDD", 40)); 25 | userRepository.save(new User("EEE", 50)); 26 | userRepository.save(new User("FFF", 60)); 27 | userRepository.save(new User("GGG", 70)); 28 | userRepository.save(new User("HHH", 80)); 29 | userRepository.save(new User("III", 90)); 30 | userRepository.save(new User("JJJ", 100)); 31 | 32 | User aaa = userRepository.findByName("AAA"); 33 | System.out.println(aaa.toString()); 34 | 35 | User bbb = userRepository.findByNameAndAge("BBB", 20); 36 | System.out.println(bbb); 37 | 38 | User ccc = userRepository.findUser("CCC"); 39 | System.out.println(ccc); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /springboot-jwt-demo/.gitigore: -------------------------------------------------------------------------------- 1 | /target 2 | .idea -------------------------------------------------------------------------------- /springboot-jwt-demo/img/1536139112248.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-jwt-demo/img/1536139112248.jpg -------------------------------------------------------------------------------- /springboot-jwt-demo/img/1536139919870.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-jwt-demo/img/1536139919870.jpg -------------------------------------------------------------------------------- /springboot-jwt-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springboot-jwt-demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springboot-jwt-demo 12 | Demo project for Spring Boot 13 | 14 | 15 | com.zwd.example.springboot 16 | spring-boot-examples 17 | 1.0-SNAPSHOT 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-devtools 41 | 42 | 43 | 44 | io.jsonwebtoken 45 | jjwt 46 | 0.9.0 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-maven-plugin 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | 8 | @SpringBootApplication 9 | public class DemoApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(DemoApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/java/com/example/demo/config/BeanRegisterConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.config; 2 | 3 | import com.example.demo.filter.MyFilter; 4 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | 9 | /** 10 | * @author zwd 11 | * @date 2018/12/18 16:34 12 | * @Email stephen.zwd@gmail.com 13 | */ 14 | @Configuration 15 | public class BeanRegisterConfig { 16 | 17 | @Bean 18 | public FilterRegistrationBean createFilterBean() { 19 | //过滤器注册类 20 | FilterRegistrationBean registration = new FilterRegistrationBean(); 21 | registration.setFilter(new MyFilter()); 22 | registration.addUrlPatterns("/user/hello"); //需要过滤的接口 23 | return registration; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/java/com/example/demo/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import com.example.demo.util.JwtHelper; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.Jwts; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | /** 15 | * @author zwd 16 | * @date 2018/9/10 14:47 17 | * @Email stephen.zwd@gmail.com 18 | */ 19 | @RestController 20 | public class LoginController { 21 | 22 | @RequestMapping("/user/login") 23 | public String login() { 24 | 25 | String jwtToken = JwtHelper.generateToken("123",456); 26 | 27 | return jwtToken; 28 | } 29 | 30 | @RequestMapping("user/hello") 31 | public String user(){ 32 | 33 | return "hello"; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/java/com/example/demo/filter/MyFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.filter; 2 | 3 | import com.example.demo.util.JwtHelper; 4 | import io.jsonwebtoken.Claims; 5 | 6 | import javax.servlet.*; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | 11 | /** 12 | * @author zwd 13 | * @date 2018/12/18 16:22 14 | * @Email stephen.zwd@gmail.com 15 | */ 16 | public class MyFilter implements Filter { 17 | @Override 18 | public void init(FilterConfig filterConfig) throws ServletException { 19 | 20 | } 21 | 22 | @Override 23 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 24 | 25 | HttpServletRequest request =(HttpServletRequest)servletRequest; 26 | HttpServletResponse response = (HttpServletResponse)servletResponse; 27 | String token = request.getHeader("authorization"); 28 | Claims claims = JwtHelper.verifyJwt(token); 29 | if (claims == null) { 30 | response.getWriter().write("token is invalid"); 31 | }else { 32 | filterChain.doFilter(request,response); 33 | } 34 | } 35 | 36 | @Override 37 | public void destroy() { 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/java/com/example/demo/util/JwtHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.JwtBuilder; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.SignatureAlgorithm; 8 | import org.apache.tomcat.util.codec.binary.Base64; 9 | 10 | import javax.crypto.SecretKey; 11 | import javax.crypto.spec.SecretKeySpec; 12 | 13 | import java.util.Date; 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | 17 | /** 18 | * @author zwd 19 | * @date 2018/9/10 11:09 20 | * @Email stephen.zwd@gmail.com 21 | */ 22 | public class JwtHelper { 23 | 24 | /** 25 | * token 过期时间, 单位: 秒. 这个值表示 30 天 26 | */ 27 | private static final long TOKEN_EXPIRED_TIME = 30 * 24 * 60 * 60; 28 | 29 | /** 30 | * jwt 加密解密密钥 31 | */ 32 | private static final String JWT_SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY="; 33 | 34 | public static final String jwtId = "tokenId"; 35 | /** 36 | * 创建JWT 37 | */ 38 | public static String createJWT(Map claims, Long time) { 39 | SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //指定签名的时候使用的签名算法,也就是header那部分,jjwt已经将这部分内容封装好了。 40 | Date now = new Date(System.currentTimeMillis()); 41 | 42 | SecretKey secretKey = generalKey(); 43 | long nowMillis = System.currentTimeMillis();//生成JWT的时间 44 | //下面就是在为payload添加各种标准声明和私有声明了 45 | JwtBuilder builder = Jwts.builder() //这里其实就是new一个JwtBuilder,设置jwt的body 46 | .setClaims(claims) //如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的 47 | .setId(jwtId) //设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。 48 | .setIssuedAt(now) //iat: jwt的签发时间 49 | .signWith(signatureAlgorithm, secretKey);//设置签名使用的签名算法和签名使用的秘钥 50 | if (time >= 0) { 51 | long expMillis = nowMillis + time; 52 | Date exp = new Date(expMillis); 53 | builder.setExpiration(exp); //设置过期时间 54 | } 55 | return builder.compact(); 56 | } 57 | 58 | /** 59 | * 验证jwt 60 | */ 61 | public static Claims verifyJwt(String token) { 62 | //签名秘钥,和生成的签名的秘钥一模一样 63 | SecretKey key = generalKey(); 64 | Claims claims; 65 | try { 66 | claims = Jwts.parser() //得到DefaultJwtParser 67 | .setSigningKey(key) //设置签名的秘钥 68 | .parseClaimsJws(token).getBody(); 69 | } catch (Exception e) { 70 | claims = null; 71 | }//设置需要解析的jwt 72 | return claims; 73 | 74 | } 75 | 76 | 77 | /** 78 | * 由字符串生成加密key 79 | * 80 | * @return 81 | */ 82 | public static SecretKey generalKey() { 83 | String stringKey = JWT_SECRET; 84 | byte[] encodedKey = Base64.decodeBase64(stringKey); 85 | SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); 86 | return key; 87 | } 88 | 89 | /** 90 | * 根据userId和openid生成token 91 | */ 92 | public static String generateToken(String openId, Integer userId) { 93 | Map map = new HashMap<>(); 94 | map.put("userId", userId); 95 | map.put("openId", openId); 96 | return createJWT(map, TOKEN_EXPIRED_TIME); 97 | } 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /springboot-jwt-demo/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-jwt-demo/src/main/resources/application.yml -------------------------------------------------------------------------------- /springboot-jwt-demo/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import io.jsonwebtoken.Claims; 4 | import io.jsonwebtoken.JwtBuilder; 5 | import io.jsonwebtoken.Jwts; 6 | import io.jsonwebtoken.SignatureAlgorithm; 7 | import org.apache.tomcat.util.codec.binary.Base64; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import javax.crypto.SecretKey; 14 | import javax.crypto.spec.SecretKeySpec; 15 | import java.util.Date; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest 19 | public class DemoApplicationTests { 20 | 21 | @Test 22 | public void contextLoads() throws Exception { 23 | DemoApplicationTests util= new DemoApplicationTests(); 24 | String ab=util.createJWT("jwt", "{id:100,name:zhuweidong}", 60000); 25 | System.out.println(ab); 26 | //eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJEU1NGQVdEV0FEQVMuLi4iLCJzdWIiOiJ7aWQ6MTAwLG5hbWU6eGlhb2hvbmd9IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJuaWNrX25hbWUiOiJEQVNEQTEyMSIsImV4cCI6MTUxNzgzNTE0NiwiaWF0IjoxNTE3ODM1MDg2LCJqdGkiOiJqd3QifQ.ncVrqdXeiCfrB9v6BulDRWUDDdROB7f-_Hg5N0po980 27 | String jwt="eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJEU1NGQVdEV0FEQVMuLi4iLCJzdWIiOiJ7aWQ6MTAwLG5hbWU6eGlhb2hvbmd9IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJuaWNrX25hbWUiOiJEQVNEQTEyMSIsImV4cCI6MTUxNzgzNTEwOSwiaWF0IjoxNTE3ODM1MDQ5LCJqdGkiOiJqd3QifQ.G_ovXAVTlB4WcyD693VxRRjOxa4W5Z-fklOp_iHj3Fg"; 28 | Claims c=util.parseJWT(ab);//注意:如果jwt已经过期了,这里会抛出jwt过期异常。 29 | System.out.println(c.getId());//jwt 30 | System.out.println(c.getIssuedAt());//Mon Feb 05 20:50:49 CST 2018 31 | System.out.println(c.getSubject());//{id:100,name:xiaohong} 32 | System.out.println(c.getIssuer());//null 33 | System.out.println(c.get("uid", String.class));//DSSFAWDWADAS... 34 | } 35 | 36 | public String createJWT(String id, String subject, long ttlMillis) throws Exception { 37 | SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 ; 38 | long nowMillis = System. currentTimeMillis(); 39 | Date now = new Date( nowMillis); 40 | SecretKey key = generalKey(); 41 | JwtBuilder builder = Jwts. builder() 42 | .setId(id) 43 | .setIssuedAt(now) 44 | .setSubject(subject) 45 | .signWith(signatureAlgorithm, key); 46 | if (ttlMillis >= 0){ 47 | long expMillis = nowMillis + ttlMillis; 48 | Date exp = new Date( expMillis); 49 | builder.setExpiration( exp); 50 | } 51 | return builder.compact(); 52 | } 53 | 54 | public Claims parseJWT(String jwt) throws Exception{ 55 | SecretKey key = generalKey(); 56 | Claims claims = Jwts. parser() 57 | .setSigningKey( key) 58 | .parseClaimsJws( jwt).getBody(); 59 | return claims; 60 | } 61 | /** 62 | * 由字符串生成加密key 63 | * @return 64 | */ 65 | public SecretKey generalKey(){ 66 | String stringKey = "7786df7fc3a34e26a61c034d5ec8245d";//本地配置文件中加密的密文7786df7fc3a34e26a61c034d5ec8245d 67 | byte[] encodedKey = Base64.decodeBase64(stringKey);//本地的密码解码[B@152f6e2 68 | //System.out.println(encodedKey);//[B@152f6e2 69 | System.out.println(Base64.encodeBase64URLSafeString(encodedKey));//7786df7fc3a34e26a61c034d5ec8245d 70 | SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// 根据给定的字节数组使用AES加密算法构造一个密钥,使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。(后面的文章中马上回推出讲解Java加密和解密的一些算法) 71 | return key; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | .idea 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | *.yml 26 | *.properties -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/README.md: -------------------------------------------------------------------------------- 1 | # springboot-mybatis-pageHelper 2 | ## 通关拦截查询语句实现分页 3 | 4 | ![](./images/1.png) -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-mybatis-pageHelper/images/1.png -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.wqs.root 7 | springboot-mybatis-pageHelper 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springboot-mybatis-pageHelper 12 | Demo project for Spring Boot 13 | 14 | 15 | com.zwd.example.springboot 16 | spring-boot-examples 17 | 1.0-SNAPSHOT 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.mybatis.spring.boot 29 | mybatis-spring-boot-starter 30 | 1.3.1 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | com.github.pagehelper 39 | pagehelper-spring-boot-starter 40 | 1.1.2 41 | 42 | 43 | mysql 44 | mysql-connector-java 45 | runtime 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-maven-plugin 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/SpringbootMybatisRedisApplication.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @MapperScan("com.wqs.root.mapper") 9 | public class SpringbootMybatisRedisApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringbootMybatisRedisApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root.controller; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.wqs.root.domain.User; 5 | import com.wqs.root.service.UserService; 6 | import com.wqs.root.util.MyPage; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | @Controller 14 | public class UserController { 15 | @Autowired 16 | private UserService userService; 17 | @RequestMapping("/user") 18 | @ResponseBody 19 | //@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,@RequestParam(value = "pageSize",defaultValue = "5")int pageSize 20 | public MyPage findUserPage(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,@RequestParam(value = "pageSize",defaultValue = "5")int pageSize){ 21 | Page persons = userService.findUserPage(pageNum, pageSize); 22 | MyPage myPages=new MyPage(persons); 23 | return myPages; 24 | } 25 | // @RequestMapping(value = "/redis",method = RequestMethod.GET) 26 | // @ResponseBody 27 | // public String redisTest(){ 28 | // Page persons = userService.findUserPage(1, 5); 29 | // redisUtil.set("persons",persons); 30 | // System.out.println("进入了方法"); 31 | // String persons1 = redisUtil.get("persons").toString(); 32 | // System.out.println(persons1); 33 | // return persons1; 34 | // } 35 | @RequestMapping("add") 36 | public void add(){ 37 | for(int i=16;i<100;i++){ 38 | User user = new User(); 39 | user.setName("葫芦娃"+i); 40 | userService.addUser(user); 41 | } 42 | System.out.println("执行完成!!!"); 43 | } 44 | @RequestMapping("query") 45 | @ResponseBody 46 | public List query(){ 47 | return userService.queryAllUser(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root.domain; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.io.Serializable; 6 | 7 | @Component 8 | public class User implements Serializable { 9 | private int id; 10 | private String name; 11 | 12 | public int getId() { 13 | return id; 14 | } 15 | 16 | public void setId(int id) { 17 | this.id = id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root.mapper; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.wqs.root.domain.User; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | @Repository 9 | public interface UserMapper { 10 | Page findUserPage(); 11 | void insertUser(User user); 12 | List selectAllUser(); 13 | } 14 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root.service; 2 | 3 | import com.github.pagehelper.Page; 4 | import com.github.pagehelper.PageHelper; 5 | import com.wqs.root.domain.User; 6 | import com.wqs.root.mapper.UserMapper; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.cache.annotation.EnableCaching; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.io.Serializable; 12 | import java.util.List; 13 | 14 | @Service 15 | public class UserService implements Serializable { 16 | @Autowired 17 | private UserMapper userMapper; 18 | 19 | public Page findUserPage(int pageNumber, int pageSize){ 20 | PageHelper.startPage(pageNumber,pageSize); 21 | Page page = userMapper.findUserPage(); 22 | System.out.println("aaa"); 23 | return page; 24 | } 25 | 26 | public void addUser(User user){ 27 | userMapper.insertUser(user); 28 | } 29 | 30 | public List queryAllUser(){ 31 | return userMapper.selectAllUser(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/java/com/wqs/root/util/MyPage.java: -------------------------------------------------------------------------------- 1 | package com.wqs.root.util; 2 | 3 | import com.github.pagehelper.Page; 4 | 5 | import java.util.List; 6 | 7 | public class MyPage { 8 | private int pageNumber; 9 | private int pageSize; 10 | private long totalCount; 11 | private int totalPage; 12 | private List list; 13 | public MyPage(){ 14 | 15 | } 16 | public MyPage(Page page){ 17 | this.pageNumber=page.getPageNum(); 18 | this.pageSize=page.getPageSize(); 19 | this.totalCount=page.getTotal(); 20 | this.totalPage=page.getPages(); 21 | this.list=page.getResult(); 22 | } 23 | public int getPageNumber() { 24 | return pageNumber; 25 | } 26 | 27 | public void setPageNumber(int pageNumber) { 28 | this.pageNumber = pageNumber; 29 | } 30 | 31 | public int getPageSize() { 32 | return pageSize; 33 | } 34 | 35 | public void setPageSize(int pageSize) { 36 | this.pageSize = pageSize; 37 | } 38 | 39 | public long getTotalCount() { 40 | return totalCount; 41 | } 42 | 43 | public void setTotalCount(long totalCount) { 44 | this.totalCount = totalCount; 45 | } 46 | 47 | public int getTotalPage() { 48 | return totalPage; 49 | } 50 | 51 | public void setTotalPage(int totalPage) { 52 | this.totalPage = totalPage; 53 | } 54 | 55 | public List getList() { 56 | return list; 57 | } 58 | 59 | public void setList(List list) { 60 | this.list = list; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /springboot-mybatis-pageHelper/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | insert into user values(#{id},#{name}) 19 | 20 | 23 | -------------------------------------------------------------------------------- /springboot-outh2.0/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | springboot-outh2.0 9 | 1.0-SNAPSHOT 10 | 11 | 12 | com.zwd.example.springboot 13 | spring-boot-examples 14 | 1.0-SNAPSHOT 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-security 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | 35 | org.springframework.security.oauth 36 | spring-security-oauth2 37 | 2.3.3.RELEASE 38 | 39 | 40 | com.alibaba 41 | fastjson 42 | 1.2.44 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/java/com/zwd/example/spring/outh/Application.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.spring.outh; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author zwd 8 | * @date 2018/12/19 19:44 9 | * @Email stephen.zwd@gmail.com 10 | */ 11 | 12 | //@SpringBootApplication 13 | public class Application { 14 | 15 | public static void main(String[] args) { 16 | 17 | Runnable task = () -> { 18 | String threadName = Thread.currentThread().getName(); 19 | System.out.println("Hello "+ threadName); 20 | }; 21 | task.run(); 22 | // SpringApplication.run(Application.class); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/java/com/zwd/example/spring/outh/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.spring.outh.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | import org.springframework.security.core.userdetails.User; 9 | import org.springframework.security.core.userdetails.UserDetailsService; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 13 | 14 | /** 15 | * @author zwd 16 | * @date 2018/12/21 11:03 17 | * @Email stephen.zwd@gmail.com 18 | */ 19 | @Configuration 20 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 21 | 22 | @Bean 23 | @Override 24 | public AuthenticationManager authenticationManagerBean() throws Exception { 25 | AuthenticationManager manager = super.authenticationManagerBean(); 26 | return manager; 27 | } 28 | 29 | //配置内存模式的用户 30 | @Bean 31 | @Override 32 | protected UserDetailsService userDetailsService(){ 33 | InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 34 | manager.createUser(User.withUsername("employee").password(new BCryptPasswordEncoder().encode("123456")).authorities("USER").build()); 35 | manager.createUser(User.withUsername("employee1").password(new BCryptPasswordEncoder().encode("123456")).authorities("USER").build()); 36 | return manager; 37 | } 38 | 39 | @Bean 40 | public PasswordEncoder passwordEncoder() { 41 | return new BCryptPasswordEncoder(); 42 | } 43 | 44 | @Override 45 | protected void configure(HttpSecurity http) throws Exception { 46 | http 47 | // .formLogin().and() 48 | .httpBasic().and() 49 | .csrf().disable(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/java/com/zwd/example/spring/outh/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.spring.outh.controller; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | /** 7 | * @author zwd 8 | * @date 2018/12/21 14:47 9 | * @Email stephen.zwd@gmail.com 10 | */ 11 | @RestController 12 | @RequestMapping("/api/example") 13 | public class UserController { 14 | 15 | 16 | @RequestMapping("hello") 17 | public String helloWorld() { 18 | 19 | return "hello world"; 20 | } 21 | 22 | @RequestMapping("world") 23 | public String helloWorld1() { 24 | 25 | return "hello world"; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/java/com/zwd/example/spring/outh/server/CustomAuthenticationServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.spring.outh.server; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.core.userdetails.UserDetailsService; 7 | import org.springframework.security.crypto.password.PasswordEncoder; 8 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 10 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 11 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 12 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 13 | 14 | /** 15 | * @author zwd 16 | * @date 2018/12/21 08:47 17 | * @Email stephen.zwd@gmail.com 18 | */ 19 | @Configuration 20 | @EnableAuthorizationServer 21 | public class CustomAuthenticationServerConfig extends AuthorizationServerConfigurerAdapter{ 22 | 23 | @Autowired 24 | private AuthenticationManager authenticationManager; 25 | 26 | @Autowired 27 | private UserDetailsService userDetailsService; 28 | 29 | @Autowired 30 | private PasswordEncoder passwordEncoder; 31 | 32 | //用来配置令牌端点(Token Endpoint)的安全约束. 33 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 34 | } 35 | 36 | //用来配置客户端详情服务 37 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 38 | clients.inMemory().withClient("yunchongyin") 39 | .secret(passwordEncoder.encode("123456")) 40 | .accessTokenValiditySeconds(7200) 41 | .authorizedGrantTypes("refresh_token", "password","authorization_code") 42 | .redirectUris("https://github.com/despairyoke?tab=repositories") 43 | .scopes("all"); 44 | } 45 | 46 | //来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services) 47 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 48 | endpoints.authenticationManager(authenticationManager) 49 | .userDetailsService(userDetailsService); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/java/com/zwd/example/spring/outh/server/CustomResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.spring.outh.server; 2 | import org.springframework.context.annotation.Configuration; 3 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 4 | import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | 8 | 9 | // 10 | //import org.springframework.context.annotation.Configuration; 11 | //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 12 | //import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 13 | // 14 | ///** 15 | // * @author zwd 16 | // * @date 2018/12/21 08:49 17 | // * @Email stephen.zwd@gmail.com 18 | // */ 19 | @Configuration 20 | @EnableResourceServer 21 | public class CustomResourceServerConfig extends ResourceServerConfigurerAdapter { 22 | 23 | public void configure(HttpSecurity http) throws Exception { 24 | ((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /springboot-outh2.0/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-outh2.0/src/main/resources/application.yml -------------------------------------------------------------------------------- /springboot-property-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /springboot-property-example/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-property-example/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /springboot-property-example/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /springboot-property-example/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: post 3 | title: springboot配置文件详解 4 | category: springboot 5 | tags: [springboot] 6 | --- 7 | ### 自定义属性与加载 8 | 9 | ``` xml 10 | zwd.name=zwd 11 | zwd.password=123456 12 | ``` 13 | 然后通过`@Value("${属性名}")`注解来加载对应的配置属性,具体如下: 14 | ``` java 15 | @Component 16 | public class UserProperties { 17 | 18 | @Value("${zwd.name}") 19 | private String username; 20 | @Value("${zwd.password}") 21 | private String password; 22 | 23 | //省略getter setter 24 | } 25 | ``` 26 | 27 | ### 参数间的引用 28 | 29 | 在`在application.properties`中的各参数间也可以直接引用来使用,具体如下: 30 | ``` YAML 31 | zwd.name=zwd 32 | zwd.password=123456 33 | zwd.content= name:${zwd.name},password:${zwd.password} 34 | ``` 35 | 36 | ### 使用随机数 37 | -------- 38 | 39 | ``` YAML 40 | # 随机字符串 41 | zwd.blog.value=${random.value} 42 | # 随机int 43 | zwd.blog.number=${random.int} 44 | # 随机long 45 | zwd.blog.bignumber=${random.long} 46 | # 10以内的随机数 47 | zwd.blog.test1=${random.int(10)} 48 | # 10-20的随机数 49 | zwd..blog.test2=${random.int[10,20]} 50 | 51 | ``` 52 | 具体使用如下: 53 | ``` java 54 | @Value("${zwd.blog.value}") 55 | private String isString; 56 | @Value("${zwd.blog.number}") 57 | private Integer number; 58 | ``` 59 | ## 配置文件的选择 60 | 项目从开发到测试到生产,这些流程如果都使用同一个数据库的话,显然是不合理的;所以我们应该有多个配置文件供选择。 61 | `application-dev.properties` 62 | ``` js 63 | server.port=8083 64 | ``` 65 | `application-test.properties` 66 | ``` js 67 | server.port=8082 68 | ``` 69 | `application-prod.properties` 70 | ``` js 71 | server.port=8081 72 | ``` 73 | 这里我创建了三个配置文件做为演示,配置文件的内容如上,只是做了简单的启动端口替换。文件的选择是通过`applicaiton.properties`来控制,我具体代码如下: 74 | ``` yml 75 | spring.profiles.active=test 76 | ``` 77 | 想要切换为dev时,只需修改`test`为`dev`即可 78 | -------------------------------------------------------------------------------- /springboot-property-example/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example.zwd 7 | springboot-property-example 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | property-example 12 | Demo project for Spring Boot 13 | 14 | 15 | com.zwd.example.springboot 16 | spring-boot-examples 17 | 1.0-SNAPSHOT 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-test 35 | test 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-maven-plugin 44 | 45 | 46 | 47 | 48 | 49 | 50 | spring-snapshots 51 | Spring Snapshots 52 | https://repo.spring.io/snapshot 53 | 54 | true 55 | 56 | 57 | 58 | spring-milestones 59 | Spring Milestones 60 | https://repo.spring.io/milestone 61 | 62 | false 63 | 64 | 65 | 66 | 67 | 68 | 69 | spring-snapshots 70 | Spring Snapshots 71 | https://repo.spring.io/snapshot 72 | 73 | true 74 | 75 | 76 | 77 | spring-milestones 78 | Spring Milestones 79 | https://repo.spring.io/milestone 80 | 81 | false 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /springboot-property-example/src/main/java/com/example/zwd/propertyexample/PropertyExampleApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.propertyexample; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class PropertyExampleApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(PropertyExampleApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /springboot-property-example/src/main/java/com/example/zwd/propertyexample/properties/UserProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.propertyexample.properties; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @author zwd 8 | * @date 2018/9/29 15:11 9 | * @Email stephen.zwd@gmail.com 10 | */ 11 | @Component 12 | public class UserProperties { 13 | 14 | @Value("${zwd.name}") 15 | private String username; 16 | @Value("${zwd.password}") 17 | private String password; 18 | 19 | @Value("${zwd.content}") 20 | private String content; 21 | @Value("${zwd.blog.value}") 22 | private String isString; 23 | @Value("${zwd.blog.number}") 24 | private Integer number; 25 | 26 | public String getUsername() { 27 | return username; 28 | } 29 | 30 | public void setUsername(String username) { 31 | this.username = username; 32 | } 33 | 34 | public String getPassword() { 35 | return password; 36 | } 37 | 38 | public void setPassword(String password) { 39 | this.password = password; 40 | } 41 | 42 | public String getContent() { 43 | return content; 44 | } 45 | 46 | public void setContent(String content) { 47 | this.content = content; 48 | } 49 | 50 | public String getIsString() { 51 | return isString; 52 | } 53 | 54 | public void setIsString(String isString) { 55 | this.isString = isString; 56 | } 57 | 58 | public Integer getNumber() { 59 | return number; 60 | } 61 | 62 | public void setNumber(Integer number) { 63 | this.number = number; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /springboot-property-example/src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | server.port=8083 -------------------------------------------------------------------------------- /springboot-property-example/src/main/resources/application-prod.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 -------------------------------------------------------------------------------- /springboot-property-example/src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | server.port=8082 -------------------------------------------------------------------------------- /springboot-property-example/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=test 2 | zwd.name=zwd 3 | zwd.password=123456 4 | 5 | zwd.content=name:${zwd.name},password:${zwd.password} 6 | 7 | # 随机字符串 8 | zwd.blog.value=${random.value} 9 | # 随机int 10 | zwd.blog.number=${random.int} 11 | # 随机long 12 | zwd.blog.bignumber=${random.long} 13 | # 10以内的随机数 14 | zwd.blog.test1=${random.int(10)} 15 | # 10-20的随机数 16 | zwd..blog.test2=${random.int[10,20]} 17 | -------------------------------------------------------------------------------- /springboot-property-example/src/test/java/com/example/zwd/propertyexample/PropertyExampleApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.zwd.propertyexample; 2 | 3 | import com.example.zwd.propertyexample.properties.UserProperties; 4 | import org.apache.juli.logging.Log; 5 | import org.apache.juli.logging.LogFactory; 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.SpringJUnit4ClassRunner; 11 | 12 | @RunWith(SpringJUnit4ClassRunner.class) 13 | @SpringBootTest 14 | public class PropertyExampleApplicationTests { 15 | 16 | private static final Log log = LogFactory.getLog(PropertyExampleApplicationTests.class); 17 | @Autowired 18 | private UserProperties userProperties; 19 | 20 | @Test 21 | public void contextLoads() { 22 | 23 | log.info("name: "+userProperties.getUsername()); 24 | log.info("password: "+userProperties.getPassword()); 25 | log.info("content: "+userProperties.getContent()); 26 | log.info("随机字符串:"+userProperties.getIsString()); 27 | log.info("随机int: "+userProperties.getNumber()); 28 | 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /springboot-security/.gitigore: -------------------------------------------------------------------------------- 1 | /target 2 | .idea -------------------------------------------------------------------------------- /springboot-security/img/1536139112248.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-security/img/1536139112248.jpg -------------------------------------------------------------------------------- /springboot-security/img/1536139919870.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-security/img/1536139919870.jpg -------------------------------------------------------------------------------- /springboot-security/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springboot-security-jwt 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springboot-security-jwt 12 | Demo project for Spring Boot 13 | 14 | 15 | com.zwd.example.springboot 16 | spring-boot-examples 17 | 1.0-SNAPSHOT 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-security 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-actuator 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-test 45 | test 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-devtools 51 | 52 | 53 | 54 | io.jsonwebtoken 55 | jjwt 56 | 0.7.0 57 | 58 | 59 | 60 | org.projectlombok 61 | lombok 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author huyunfan 8 | */ 9 | @SpringBootApplication 10 | public class DemoApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(DemoApplication.class, args); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | 15 | 16 | @Configuration 17 | @EnableWebSecurity 18 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 19 | 20 | 21 | @Autowired 22 | private UserDetailsService userDetailsService; 23 | 24 | @Bean 25 | public PasswordEncoder passwordEncoder() { 26 | return new BCryptPasswordEncoder(); 27 | } 28 | 29 | 30 | @Override 31 | public void configure(WebSecurity web) throws Exception { 32 | super.configure(web); 33 | } 34 | 35 | @Override 36 | public void configure(AuthenticationManagerBuilder auth) throws Exception { 37 | // auth.userDetailsService(userDetailsService) 38 | // .passwordEncoder(passwordEncoder());//passwoldEncoder是对密码的加密处理,如果user中密码没有加密,则可以不加此方法。注意加密请使用security自带的加密方式。 39 | auth.inMemoryAuthentication() 40 | .withUser("admin").password("123456").roles("ADMIN") 41 | .and() 42 | .withUser("employee").password("123456").roles("EMPLOYEE"); 43 | } 44 | 45 | @Override 46 | protected void configure(HttpSecurity http) throws Exception { 47 | http.csrf().disable()//禁用了 csrf 功能 48 | .authorizeRequests()//限定签名成功的请求 49 | .antMatchers("/decision/**","/govern/**","/employee/*").hasAnyRole("EMPLOYEE","ADMIN")//对decision和govern 下的接口 需要 USER 或者 ADMIN 权限 50 | .antMatchers("/employee/login").permitAll()///admin/login 不限定 51 | .antMatchers("/admin/**").hasRole("ADMIN")//对admin下的接口 需要ADMIN权限 52 | .antMatchers("/oauth/**").permitAll()//不拦截 oauth 开放的资源 53 | .anyRequest().permitAll()//其他没有限定的请求,允许访问 54 | .and().anonymous()//对于没有配置权限的其他请求允许匿名访问 55 | .and().formLogin()//使用 spring security 默认登录页面 56 | .and().httpBasic();//启用http 基础验证 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | 8 | @RestController 9 | @RequestMapping("/admin") 10 | public class AdminController { 11 | 12 | 13 | @GetMapping("/greeting") 14 | public String greeting() { 15 | return "Hello,World!"; 16 | } 17 | 18 | @GetMapping("/login") 19 | public String login() { 20 | 21 | return "login sucess"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/controller/EmployeeController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | 8 | @RestController 9 | @RequestMapping("/employee") 10 | public class EmployeeController { 11 | 12 | 13 | @GetMapping("/greeting") 14 | public String greeting() { 15 | return "Hello,World!"; 16 | } 17 | 18 | @GetMapping("/login") 19 | public String login() { 20 | 21 | return "login sucess"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/domain/Admin.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | /** 4 | * @author zwd 5 | * @date 2018/12/20 11:05 6 | * @Email stephen.zwd@gmail.com 7 | */ 8 | public class Admin { 9 | 10 | private String username; 11 | 12 | private String password; 13 | 14 | public String getUsername() { 15 | return username; 16 | } 17 | 18 | public void setUsername(String username) { 19 | this.username = username; 20 | } 21 | 22 | public String getPassword() { 23 | return password; 24 | } 25 | 26 | public void setPassword(String password) { 27 | this.password = password; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/domain/Employee.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created with IntelliJ IDEA. 7 | * Date: 2017/11/16 8 | * Time: 10:31 9 | * Email: hyf_spring@163.com 10 | * 11 | * @author huyunfan 12 | */ 13 | @Data 14 | public class Employee { 15 | private String id; 16 | private String username; 17 | private String password; 18 | 19 | 20 | public String getId() { 21 | return id; 22 | } 23 | 24 | public void setId(String id) { 25 | this.id = id; 26 | } 27 | 28 | public String getUsername() { 29 | return username; 30 | } 31 | 32 | public void setUsername(String username) { 33 | this.username = username; 34 | } 35 | 36 | public String getPassword() { 37 | return password; 38 | } 39 | 40 | public void setPassword(String password) { 41 | this.password = password; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/filter/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | //package com.example.demo.filter; 2 | // 3 | //import com.example.demo.util.JwtUtils; 4 | //import io.jsonwebtoken.Jwts; 5 | //import org.springframework.security.authentication.AuthenticationManager; 6 | //import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | //import org.springframework.security.core.context.SecurityContextHolder; 8 | //import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 9 | // 10 | //import javax.servlet.FilterChain; 11 | //import javax.servlet.ServletException; 12 | //import javax.servlet.http.HttpServletRequest; 13 | //import javax.servlet.http.HttpServletResponse; 14 | //import java.io.IOException; 15 | //import java.util.ArrayList; 16 | // 17 | ///** 18 | // * Created with IntelliJ IDEA. 19 | // * Date: 2017/11/16 20 | // * Time: 11:11 21 | // * Email: hyf_spring@163.com 22 | // * 23 | // * @author huyunfan 24 | // */ 25 | //public class JwtAuthenticationFilter extends BasicAuthenticationFilter { 26 | // 27 | // public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { 28 | // super(authenticationManager); 29 | // } 30 | // 31 | // @Override 32 | // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { 33 | // String header = request.getHeader("Authorization"); 34 | // 35 | // if (header == null || !header.startsWith(JwtUtils.getAuthorizationHeaderPrefix())) { 36 | // chain.doFilter(request, response); 37 | // return; 38 | // } 39 | // 40 | // UsernamePasswordAuthenticationToken authenticationToken = getUsernamePasswordAuthenticationToken(header); 41 | // 42 | // SecurityContextHolder.getContext().setAuthentication(authenticationToken); 43 | // chain.doFilter(request, response); 44 | // } 45 | // 46 | // private UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(String token) { 47 | // String user = Jwts.parser() 48 | // .setSigningKey("PrivateSecret") 49 | // .parseClaimsJws(token.replace(JwtUtils.getAuthorizationHeaderPrefix(), "")) 50 | // .getBody() 51 | // .getSubject(); 52 | // 53 | // if (null != user) { 54 | // return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); 55 | // } 56 | // 57 | // return null; 58 | // } 59 | //} 60 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/filter/JwtLoginFilter.java: -------------------------------------------------------------------------------- 1 | //package com.example.demo.filter; 2 | // 3 | //import com.example.demo.domain.Employee; 4 | //import com.example.demo.util.JwtUtils; 5 | //import io.jsonwebtoken.Jwts; 6 | //import io.jsonwebtoken.SignatureAlgorithm; 7 | //import org.springframework.security.authentication.AuthenticationManager; 8 | //import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | //import org.springframework.security.core.Authentication; 10 | //import org.springframework.security.core.AuthenticationException; 11 | //import org.springframework.security.core.userdetails.User; 12 | //import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 13 | // 14 | //import javax.servlet.FilterChain; 15 | //import javax.servlet.ServletException; 16 | //import javax.servlet.http.HttpServletRequest; 17 | //import javax.servlet.http.HttpServletResponse; 18 | //import java.io.IOException; 19 | //import java.util.ArrayList; 20 | //import java.util.Date; 21 | // 22 | ///** 23 | // * Created with IntelliJ IDEA. 24 | // * Date: 2017/11/16 25 | // * Time: 10:47 26 | // * Email: hyf_spring@163.com 27 | // * 28 | // * @author huyunfan 29 | // */ 30 | //public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter { 31 | // 32 | // private AuthenticationManager authenticationManager; 33 | // 34 | // public JwtLoginFilter(AuthenticationManager authenticationManager) { 35 | // this.authenticationManager = authenticationManager; 36 | // } 37 | // 38 | // @Override 39 | // public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 40 | // Employee employee = new Employee(); 41 | // return authenticationManager.authenticate( 42 | // new UsernamePasswordAuthenticationToken( 43 | // employee.getUsername(), 44 | // employee.getPassword(), 45 | // new ArrayList<>() 46 | // ) 47 | // ); 48 | // } 49 | // 50 | // @Override 51 | // protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { 52 | // String token = Jwts.builder() 53 | // .setSubject(((User) authResult.getPrincipal()).getUsername()) 54 | // .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) 55 | // .signWith(SignatureAlgorithm.HS512, "PrivateSecret") 56 | // .compact(); 57 | // 58 | // response.addHeader("Authorization", JwtUtils.getTokenHeader(token)); 59 | // } 60 | //} 61 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/service/impl/UserDetailServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service.impl; 2 | 3 | import com.example.demo.domain.Admin; 4 | import com.example.demo.domain.Employee; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | import org.springframework.security.core.userdetails.User; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | import org.springframework.stereotype.Service; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | import static java.util.Collections.emptyList; 19 | 20 | /** 21 | * Created with IntelliJ IDEA. 22 | * Date: 2017/11/16 23 | * Time: 15:10 24 | * Email: hyf_spring@163.com 25 | * 26 | * @author huyunfan 27 | */ 28 | @Service 29 | public class UserDetailServiceImpl implements UserDetailsService { 30 | 31 | @Override 32 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 33 | 34 | List grantedAuthorities = new ArrayList<>(); 35 | 36 | //生成环境是查询数据库获取username的角色用于后续权限判断(如:张三 admin) 37 | //这里不做数据库操作,给定假数据,有兴趣的人可以使内存模式。 38 | if (username.equals("employee")) { 39 | Employee employee = new Employee(); 40 | employee.setUsername("employee"); 41 | employee.setPassword("123456"); 42 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_EMPLOYEE"); 43 | grantedAuthorities.add(grantedAuthority); 44 | //创建一个用户,用于判断权限,请注意此用户名和方法参数中的username一致;BCryptPasswordEncoder是用来演示加密使用。 45 | return new User(employee.getUsername(), new BCryptPasswordEncoder().encode(employee.getPassword()), grantedAuthorities); 46 | } 47 | if (username.equals("admin")) { 48 | Admin admin = new Admin(); 49 | admin.setUsername("admin"); 50 | admin.setPassword("123456"); 51 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN"); 52 | grantedAuthorities.add(grantedAuthority); 53 | return new User(admin.getUsername(), new BCryptPasswordEncoder().encode(admin.getPassword()), grantedAuthorities); 54 | } 55 | else { 56 | return null; 57 | } 58 | 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /springboot-security/src/main/java/com/example/demo/util/JwtUtils.java: -------------------------------------------------------------------------------- 1 | //package com.example.demo.util; 2 | // 3 | //import org.springframework.util.StringUtils; 4 | // 5 | ///** 6 | // * @author Leon.Yu 7 | // * @date 2017/9/21 8 | // */ 9 | //public class JwtUtils { 10 | // private static final String AUTHORIZATION_HEADER_PREFIX = "Bearer "; 11 | // 12 | // /** 13 | // * remove 'Bearer ' string 14 | // * 15 | // * @param authorizationHeader 16 | // * @return 17 | // */ 18 | // public static String getRawToken(String authorizationHeader) { 19 | // return authorizationHeader.substring(AUTHORIZATION_HEADER_PREFIX.length()); 20 | // } 21 | // 22 | // public static String getTokenHeader(String rawToken) { 23 | // return AUTHORIZATION_HEADER_PREFIX + rawToken; 24 | // } 25 | // 26 | // public static boolean validate(String authorizationHeader) { 27 | // return StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith(AUTHORIZATION_HEADER_PREFIX); 28 | // } 29 | // 30 | // public static String getAuthorizationHeaderPrefix() { 31 | // return AUTHORIZATION_HEADER_PREFIX; 32 | // } 33 | //} 34 | -------------------------------------------------------------------------------- /springboot-security/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DespairYoke/spring-boot-examples/733f7beb8fe759b5de3c7fc57e084a82af46187c/springboot-security/src/main/resources/application.properties -------------------------------------------------------------------------------- /springboot-security/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import io.jsonwebtoken.Claims; 4 | import io.jsonwebtoken.JwtBuilder; 5 | import io.jsonwebtoken.Jwts; 6 | import io.jsonwebtoken.SignatureAlgorithm; 7 | import org.apache.tomcat.util.codec.binary.Base64; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import javax.crypto.SecretKey; 14 | import javax.crypto.spec.SecretKeySpec; 15 | import java.util.Date; 16 | 17 | @RunWith(SpringRunner.class) 18 | @SpringBootTest 19 | public class DemoApplicationTests { 20 | 21 | @Test 22 | public void contextLoads() throws Exception { 23 | DemoApplicationTests util= new DemoApplicationTests(); 24 | String ab=util.createJWT("jwt", "{id:100,name:zhuweidong}", 60000); 25 | System.out.println(ab); 26 | //eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJEU1NGQVdEV0FEQVMuLi4iLCJzdWIiOiJ7aWQ6MTAwLG5hbWU6eGlhb2hvbmd9IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJuaWNrX25hbWUiOiJEQVNEQTEyMSIsImV4cCI6MTUxNzgzNTE0NiwiaWF0IjoxNTE3ODM1MDg2LCJqdGkiOiJqd3QifQ.ncVrqdXeiCfrB9v6BulDRWUDDdROB7f-_Hg5N0po980 27 | String jwt="eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJEU1NGQVdEV0FEQVMuLi4iLCJzdWIiOiJ7aWQ6MTAwLG5hbWU6eGlhb2hvbmd9IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJuaWNrX25hbWUiOiJEQVNEQTEyMSIsImV4cCI6MTUxNzgzNTEwOSwiaWF0IjoxNTE3ODM1MDQ5LCJqdGkiOiJqd3QifQ.G_ovXAVTlB4WcyD693VxRRjOxa4W5Z-fklOp_iHj3Fg"; 28 | Claims c=util.parseJWT(ab);//注意:如果jwt已经过期了,这里会抛出jwt过期异常。 29 | System.out.println(c.getId());//jwt 30 | System.out.println(c.getIssuedAt());//Mon Feb 05 20:50:49 CST 2018 31 | System.out.println(c.getSubject());//{id:100,name:xiaohong} 32 | System.out.println(c.getIssuer());//null 33 | System.out.println(c.get("uid", String.class));//DSSFAWDWADAS... 34 | } 35 | 36 | public String createJWT(String id, String subject, long ttlMillis) throws Exception { 37 | SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 ; 38 | long nowMillis = System. currentTimeMillis(); 39 | Date now = new Date( nowMillis); 40 | SecretKey key = generalKey(); 41 | JwtBuilder builder = Jwts. builder() 42 | .setId(id) 43 | .setIssuedAt(now) 44 | .setSubject(subject) 45 | .signWith(signatureAlgorithm, key); 46 | if (ttlMillis >= 0){ 47 | long expMillis = nowMillis + ttlMillis; 48 | Date exp = new Date( expMillis); 49 | builder.setExpiration( exp); 50 | } 51 | return builder.compact(); 52 | } 53 | 54 | public Claims parseJWT(String jwt) throws Exception{ 55 | SecretKey key = generalKey(); 56 | Claims claims = Jwts. parser() 57 | .setSigningKey( key) 58 | .parseClaimsJws( jwt).getBody(); 59 | return claims; 60 | } 61 | /** 62 | * 由字符串生成加密key 63 | * @return 64 | */ 65 | public SecretKey generalKey(){ 66 | String stringKey = "7786df7fc3a34e26a61c034d5ec8245d";//本地配置文件中加密的密文7786df7fc3a34e26a61c034d5ec8245d 67 | byte[] encodedKey = Base64.decodeBase64(stringKey);//本地的密码解码[B@152f6e2 68 | //System.out.println(encodedKey);//[B@152f6e2 69 | System.out.println(Base64.encodeBase64URLSafeString(encodedKey));//7786df7fc3a34e26a61c034d5ec8245d 70 | SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// 根据给定的字节数组使用AES加密算法构造一个密钥,使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。(后面的文章中马上回推出讲解Java加密和解密的一些算法) 71 | return key; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /springboot-websocket/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | websocket测试 6 | 11 | 12 | 13 | 14 |

WebSocket测试,在控制台查看测试信息输出!

15 |

16 | [url=/api/ws/sendOne?message=单发消息内容&id=none]单发消息链接[/url] 17 | [url=/api/ws/sendAll?message=群发消息内容]群发消息链接[/url] 18 |

19 | 20 | 21 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /springboot-websocket/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | springboot-websocket 9 | 1.0-SNAPSHOT 10 | 11 | 12 | com.zwd.example.springboot 13 | spring-boot-examples 14 | 1.0-SNAPSHOT 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-web 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-websocket 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-thymeleaf 31 | 32 | 33 | -------------------------------------------------------------------------------- /springboot-websocket/src/main/java/com/zwd/example/websocket/Application.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.websocket; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author zwd 8 | * @date 2018/12/18 20:21 9 | * @Email stephen.zwd@gmail.com 10 | */ 11 | @SpringBootApplication 12 | public class Application { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(Application.class); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /springboot-websocket/src/main/java/com/zwd/example/websocket/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.websocket.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.socket.server.standard.ServerEndpointExporter; 6 | 7 | /** 8 | * @author zwd 9 | * @date 2018/12/19 09:12 10 | * @Email stephen.zwd@gmail.com 11 | */ 12 | @Configuration 13 | public class WebSocketConfig { 14 | 15 | @Bean 16 | public ServerEndpointExporter serverEndpointExporter () { 17 | return new ServerEndpointExporter(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /springboot-websocket/src/main/java/com/zwd/example/websocket/contoller/WebSocketController.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.websocket.contoller; 2 | 3 | import com.zwd.example.websocket.domain.WebSocketServer; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestMethod; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.io.IOException; 10 | 11 | /** 12 | * @author zwd 13 | * @date 2018/12/18 20:29 14 | * @Email stephen.zwd@gmail.com 15 | */ 16 | @RestController 17 | @RequestMapping("/api/ws") 18 | public class WebSocketController { 19 | 20 | 21 | /** 22 | * 群发消息内容 23 | * @param message 24 | * @return 25 | */ 26 | @RequestMapping(value="/sendAll", method= RequestMethod.GET) 27 | public String sendAllMessage(@RequestParam(required=true) String message){ 28 | try { 29 | WebSocketServer.BroadCastInfo(message); 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | return "ok"; 34 | } 35 | 36 | /** 37 | * 指定会话ID发消息 38 | * @param message 消息内容 39 | * @param id 连接会话ID 40 | * @return 41 | */ 42 | @RequestMapping(value="/sendOne", method=RequestMethod.GET) 43 | public String sendOneMessage(@RequestParam(required=true) String message,@RequestParam(required=true) String id){ 44 | try { 45 | WebSocketServer.SendMessage(message,id); 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | return "ok"; 50 | } 51 | } -------------------------------------------------------------------------------- /springboot-websocket/src/main/java/com/zwd/example/websocket/domain/WebSocketServer.java: -------------------------------------------------------------------------------- 1 | package com.zwd.example.websocket.domain; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.websocket.*; 9 | import javax.websocket.server.ServerEndpoint; 10 | import java.io.IOException; 11 | import java.util.concurrent.CopyOnWriteArraySet; 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | 14 | /** 15 | * @author zwd 16 | * @date 2018/12/18 20:25 17 | * @Email stephen.zwd@gmail.com 18 | */ 19 | @ServerEndpoint(value = "/ws/asset") 20 | @Component 21 | public class WebSocketServer { 22 | 23 | @PostConstruct 24 | public void init() { 25 | System.out.println("websocket 加载"); 26 | } 27 | private static Logger log = LoggerFactory.getLogger(WebSocketServer.class); 28 | private static final AtomicInteger OnlineCount = new AtomicInteger(0); 29 | // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。 30 | private static CopyOnWriteArraySet SessionSet = new CopyOnWriteArraySet(); 31 | 32 | 33 | /** 34 | * 连接建立成功调用的方法 35 | */ 36 | @OnOpen 37 | public void onOpen(Session session) { 38 | SessionSet.add(session); 39 | int cnt = OnlineCount.incrementAndGet(); // 在线数加1 40 | log.info("有连接加入,当前连接数为:{}", cnt); 41 | SendMessage(session, "连接成功"); 42 | } 43 | 44 | /** 45 | * 连接关闭调用的方法 46 | */ 47 | @OnClose 48 | public void onClose(Session session) { 49 | SessionSet.remove(session); 50 | int cnt = OnlineCount.decrementAndGet(); 51 | log.info("有连接关闭,当前连接数为:{}", cnt); 52 | } 53 | 54 | /** 55 | * 收到客户端消息后调用的方法 56 | * 57 | * @param message 58 | * 客户端发送过来的消息 59 | */ 60 | @OnMessage 61 | public void onMessage(String message, Session session) { 62 | log.info("来自客户端的消息:{}",message); 63 | SendMessage(session, "收到消息,消息内容:"+message); 64 | 65 | } 66 | 67 | /** 68 | * 出现错误 69 | * @param session 70 | * @param error 71 | */ 72 | @OnError 73 | public void onError(Session session, Throwable error) { 74 | log.error("发生错误:{},Session ID: {}",error.getMessage(),session.getId()); 75 | error.printStackTrace(); 76 | } 77 | 78 | /** 79 | * 发送消息,实践表明,每次浏览器刷新,session会发生变化。 80 | * @param session 81 | * @param message 82 | */ 83 | public static void SendMessage(Session session, String message) { 84 | try { 85 | session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId())); 86 | } catch (IOException e) { 87 | log.error("发送消息出错:{}", e.getMessage()); 88 | e.printStackTrace(); 89 | } 90 | } 91 | 92 | /** 93 | * 群发消息 94 | * @param message 95 | * @throws IOException 96 | */ 97 | public static void BroadCastInfo(String message) throws IOException { 98 | for (Session session : SessionSet) { 99 | if(session.isOpen()){ 100 | SendMessage(session, message); 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * 指定Session发送消息 107 | * @param sessionId 108 | * @param message 109 | * @throws IOException 110 | */ 111 | public static void SendMessage(String message,String sessionId) throws IOException { 112 | Session session = null; 113 | for (Session s : SessionSet) { 114 | if(s.getId().equals(sessionId)){ 115 | session = s; 116 | break; 117 | } 118 | } 119 | if(session!=null){ 120 | SendMessage(session, message); 121 | } 122 | else{ 123 | log.warn("没有找到你指定ID的会话:{}",sessionId); 124 | } 125 | } 126 | 127 | } -------------------------------------------------------------------------------- /starter.md: -------------------------------------------------------------------------------- 1 | ## 自定义 Spring Boot Starter 2 | 3 | 众所周知,Spring Boot由众多Starter组成,随着版本的推移Starter家族成员也与日俱增。在传统Maven项目中通常将一些层、组件拆分为模块来管理,以便相互依赖复用,在Spring Boot项目中我们则可以创建自定义Spring Boot Starter来达成该目的。 4 | 5 | 现在我们来创建一个自己的starter。 6 | 7 | - 功能介绍 8 | 9 | 这里讲一下我们的Starter要实现的功能,很简单,提供一个Service,包含一个能够将字符串加上前后缀的方法String wrap(String word)。 10 | 11 | - maven依赖 12 | ```xml 13 | 14 | org.springframework.boot 15 | spring-boot-autoconfigure 16 | 17 | ``` 18 | 19 | 这里说下`artifactId`的命名问题,Spring 官方 Starter通常命名为`spring-boot-starter-{name}`如 `spring-boot-starter-web`, Spring官方建议非官方Starter 20 | 命名应遵循`{name}-spring-boot-starter`的格式。 21 | 22 | - 属性读取类 23 | ```java 24 | @ConfigurationProperties("example.service") 25 | public class ExampleServiceProperties { 26 | 27 | private String prefix; 28 | 29 | private String suffix; 30 | 31 | public String getPrefix() { 32 | return prefix; 33 | } 34 | 35 | public void setPrefix(String prefix) { 36 | this.prefix = prefix; 37 | } 38 | 39 | public String getSuffix() { 40 | return suffix; 41 | } 42 | 43 | public void setSuffix(String suffix) { 44 | this.suffix = suffix; 45 | } 46 | } 47 | ``` 48 | 49 | - service 50 | ```java 51 | public class ExampleService { 52 | 53 | private String prefix; 54 | 55 | private String suffix; 56 | 57 | public ExampleService(String prefix, String suffix) { 58 | this.prefix = prefix; 59 | this.suffix = suffix; 60 | } 61 | 62 | public String wrap(String word) { 63 | return prefix + word + suffix; 64 | } 65 | } 66 | ``` 67 | - 自动加载配置 68 | ```java 69 | @Configuration 70 | @ConditionalOnClass(ExampleService.class) 71 | @EnableConfigurationProperties(ExampleServiceProperties.class) 72 | public class ExampleAutoConfigure { 73 | 74 | @Autowired 75 | private ExampleServiceProperties properties; 76 | 77 | @Bean 78 | @ConditionalOnMissingBean 79 | @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true") 80 | ExampleService exampleService (){ 81 | return new ExampleService(properties.getPrefix(),properties.getSuffix()); 82 | } 83 | 84 | } 85 | ``` 86 | `@ConditionalOnClass` 表示有这个类的存在。 87 | `@EnableConfigurationProperties` 自动配置属性类。 88 | `@ConditionalOnMissingBean` 当ExampleService bean缺失时,执行下段代码。 89 | `@ConditionalOnProperty` 当example.service.enabled=true时,执行代码。 90 | 91 | - spring.factories 92 | 93 | 在resources下创建MATA-INF/spring.factories,内容如下 94 | ```properties 95 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.zwd.springbootstarter.config.ExampleAutoConfigure 96 | ``` 97 | `注意`:value为自动配置类的classpath。 98 | 99 | 创建完成,进行打包。 100 | 101 | [项目地址](./example-spring-boot-starter) 102 | #### 如何使用? 103 | 104 | - 引入依赖 105 | ```xml 106 | 107 | com.java.advance 108 | example-spring-boot-starter 109 | 0.0.1-SNAPSHOT 110 | 111 | ``` 112 | 113 | - application.properties配置参数 114 | ```properties 115 | example.service.enabled=true 116 | example.service.prefix=#### 117 | example.service.suffix=@@@@ 118 | ``` 119 | - 启动类示例 120 | ```java 121 | @SpringBootApplication 122 | @RestController 123 | public class SpringbootStarterTest { 124 | 125 | public static void main(String[] args) { 126 | SpringApplication.run(SpringbootStarterTest.class, args); 127 | } 128 | 129 | @Autowired 130 | private ExampleService exampleService; 131 | 132 | @GetMapping("/input") 133 | public String input(String word){ 134 | return exampleService.wrap(word); 135 | } 136 | } 137 | ``` 138 | 139 | 启动成功和访问 http://localhost:8080/input?word=name,返回结果如下 140 | 141 | ####name@@@@ 142 | 143 | 表示starter可以正常使用。 144 | 145 | [项目地址](./example-spring-boot-starter-test) -------------------------------------------------------------------------------- /swagger.md: -------------------------------------------------------------------------------- 1 | ## springboot整合swagger2 2 | 3 | swagger是一个方便后端编写接口文档的开源项目,并提供界面化测试。 4 | 5 | ### 项目搭建 6 | 7 | - maven依赖 8 | ```xml 9 | 10 | 11 | io.springfox 12 | springfox-swagger2 13 | 2.8.0 14 | 15 | 16 | io.springfox 17 | springfox-swagger-ui 18 | 2.8.0 19 | 20 | ``` 21 | 22 | - 新建配置类 23 | ````java 24 | @Configuration 25 | @EnableSwagger2 26 | public class Swagger2 { 27 | /** 28 | * 通过 createRestApi函数来构建一个DocketBean 29 | * 函数名,可以随意命名,喜欢什么命名就什么命名 30 | */ 31 | @Bean 32 | public Docket createRestApi() { 33 | return new Docket(DocumentationType.SWAGGER_2) 34 | .apiInfo(apiInfo())//调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容 35 | .select() 36 | //控制暴露出去的路径下的实例 37 | //如果某个接口不想暴露,可以使用以下注解 38 | //@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下 39 | .apis(RequestHandlerSelectors.basePackage("com.example.zwd.springbootswagger2.controller")) 40 | .paths(PathSelectors.any()) 41 | .build(); 42 | } 43 | //构建 api文档的详细信息函数 44 | private ApiInfo apiInfo() { 45 | return new ApiInfoBuilder() 46 | //页面标题 47 | .title("Spring Boot Swagger2 构建RESTful API") 48 | //条款地址 49 | .termsOfServiceUrl("http://despairyoke.github.io/") 50 | .contact("zwd") 51 | .version("1.0") 52 | //描述 53 | .description("API 描述") 54 | .build(); 55 | } 56 | } 57 | ```` 58 | 59 | - 新建测试controller类 60 | ````java 61 | @RestController 62 | public class UserController { 63 | 64 | @ApiOperation(value = "接口的功能介绍",notes = "提示接口使用者注意事项",httpMethod = "GET") 65 | @ApiImplicitParam(dataType = "string",name = "name",value = "姓名",required = true) 66 | @RequestMapping(value = "/") 67 | public String index(String name) { 68 | 69 | return "hello "+ name; 70 | } 71 | } 72 | ```` 73 | 启动项目[spring-boot-swagger2](./spring-boot-swagger2),访问 http://localhost:8080/swagger-ui.html 74 | 75 | 可以看到下图效果 76 | 77 | ![](./image/swagger-home.png) 78 | 79 | 展开接口内部 80 | 81 | ![](./image/swagger-info.png) 82 | 83 | 点击try it out 输入姓名, Execute执行,返回如下图效果 84 | 85 | ![](./image/swagger-request.png) 86 | 87 | [项目地址](./spring-boot-swagger2) --------------------------------------------------------------------------------