├── spring-boot-integration-01-starter ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── starter │ │ └── SpringBootStarterApplication.java └── pom.xml ├── spring-boot-integration-02-junit ├── src │ ├── main │ │ ├── resources │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── junit │ │ │ ├── SpringBootJUnitApplication.java │ │ │ └── config │ │ │ └── WebConfig.java │ └── test │ │ └── java │ │ ├── com │ │ └── linkedbear │ │ │ └── boot │ │ │ └── junit │ │ │ ├── demo │ │ │ └── InnerTest.java │ │ │ └── SpringBootApplicationTest.java │ │ └── demo │ │ ├── OuterTest.java │ │ ├── TestingAStackDemo.java │ │ └── AssertTest.java └── pom.xml ├── spring-boot-integration-11-admin ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── actuator │ │ └── SpringBootAdminApplication.java └── pom.xml ├── spring-boot-integration-10-swagger ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── swagger │ │ ├── SpringBootSwaggerApplication.java │ │ ├── entity │ │ └── User.java │ │ ├── config │ │ ├── Swagger3Configuration.java │ │ ├── Knife4jConfiguration.java │ │ └── Swagger2Configuration.java │ │ └── controller │ │ └── DemoController.java └── pom.xml ├── spring-boot-integration-05-elasticsearch ├── src │ ├── main │ │ ├── resources │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── elasticsearch │ │ │ ├── dao │ │ │ └── GraphicsCardRepository.java │ │ │ ├── SpringBootElasticSearchApplication.java │ │ │ ├── entity │ │ │ └── GraphicsCard.java │ │ │ └── config │ │ │ └── ElasticSearchConfiguration.java │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── elasticsearch │ │ ├── DataElasticSearchTest.java │ │ └── ElasticSearchClientTest.java └── pom.xml ├── spring-boot-integration-08-rocketmq-consumer ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── rocketmq │ │ └── consumer │ │ ├── SpringBootRocketMQConsumerApplication.java │ │ ├── service │ │ ├── SoftwareMessageReceiver.java │ │ ├── TransactionalReceiver.java │ │ ├── DelayMessageReceiver.java │ │ ├── DataUpdateTransactionalReceiver.java │ │ ├── OrderedMessageReceiver.java │ │ ├── UserDtoMessageReceiver.java │ │ └── MessageReceiver.java │ │ └── dto │ │ └── UserDTO.java └── pom.xml ├── xxl-job-boot-starter ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── spring.factories │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── xxljob │ │ ├── autoconfigure │ │ └── XxlJobAutoConfiguration.java │ │ └── properties │ │ └── XxlJobProperties.java └── pom.xml ├── spring-boot-integration-09-xxljob ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── xxljob │ │ ├── service │ │ └── DemoService.java │ │ ├── SpringBootXxlJobApplication.java │ │ └── config │ │ └── XxlJobConfiguration.java └── pom.xml ├── spring-boot-integration-06-j2cache ├── src │ ├── main │ │ ├── resources │ │ │ ├── caffeine.properties │ │ │ ├── mapper │ │ │ │ └── UserMapper.xml │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── j2cache │ │ │ ├── SpringBootJ2cacheApplication.java │ │ │ ├── service │ │ │ ├── UserService.java │ │ │ ├── AnnotationUserService.java │ │ │ └── CachedUserService.java │ │ │ ├── entity │ │ │ └── User.java │ │ │ └── mapper │ │ │ └── UserMapper.java │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── j2cache │ │ └── J2cacheTest.java └── pom.xml ├── spring-boot-integration-03-mybatisplus ├── src │ ├── main │ │ ├── resources │ │ │ ├── mapper │ │ │ │ └── UserMapper.xml │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── mybatisplus │ │ │ ├── SpringBootMyBatisPlusApplication.java │ │ │ ├── service │ │ │ └── UserService.java │ │ │ ├── config │ │ │ └── MyBatisPlusConfiguration.java │ │ │ ├── mapper │ │ │ └── UserMapper.java │ │ │ └── entity │ │ │ └── User.java │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── mybatisplus │ │ ├── CodeGenerator.java │ │ └── MyBatisPlusTest.java └── pom.xml ├── spring-boot-integration-09-quartz ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── quartz │ │ ├── SpringBootQuartzApplication.java │ │ ├── quartz │ │ ├── SimpleJob.java │ │ └── ScheduleService.java │ │ └── controller │ │ └── DynamicScheduleController.java └── pom.xml ├── spring-boot-integration-08-rocketmq-producer ├── src │ └── main │ │ ├── resources │ │ └── application.properties │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── rocketmq │ │ └── producer │ │ ├── template │ │ └── DataUpdateRocketMQTemplate.java │ │ ├── SpringBootRocketMQProducerApplication.java │ │ ├── dto │ │ └── UserDTO.java │ │ ├── service │ │ ├── DataService.java │ │ ├── TransactionalStatusChecker.java │ │ ├── DataUpdateTransactionalStatusChecker.java │ │ └── MessageSender.java │ │ └── controller │ │ └── MessageController.java └── pom.xml ├── spring-boot-integration-07-security-webmvc ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── linkedbear │ │ │ │ └── boot │ │ │ │ └── security │ │ │ │ ├── dao │ │ │ │ ├── ResourceDao.java │ │ │ │ └── UserDao.java │ │ │ │ ├── SpringBootSecurityApplication.java │ │ │ │ ├── controller │ │ │ │ ├── DemoController.java │ │ │ │ └── ApiController.java │ │ │ │ ├── jwt │ │ │ │ ├── TokenPayload.java │ │ │ │ ├── JsonUtils.java │ │ │ │ ├── RefreshTokenController.java │ │ │ │ ├── JwtTokenFilter.java │ │ │ │ ├── RsaUtils.java │ │ │ │ └── JwtUtils.java │ │ │ │ ├── entity │ │ │ │ ├── Resource.java │ │ │ │ ├── SecurityUser.java │ │ │ │ └── User.java │ │ │ │ ├── service │ │ │ │ └── UserService.java │ │ │ │ ├── filter │ │ │ │ └── ResourceAuthorizationFilter.java │ │ │ │ └── config │ │ │ │ └── WebSecurityConfiguration.java │ │ └── resources │ │ │ ├── jwt_rsa.pub │ │ │ ├── application.properties │ │ │ └── jwt_rsa │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── security │ │ └── AddUserTest.java └── pom.xml ├── spring-boot-integration-03-mybatis ├── src │ ├── main │ │ ├── resources │ │ │ ├── application.properties │ │ │ └── mapper │ │ │ │ └── UserMapper.xml │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── mybatis │ │ │ ├── SpringBootMyBatisApplication.java │ │ │ ├── entity │ │ │ └── User.java │ │ │ ├── service │ │ │ └── UserService.java │ │ │ └── mapper │ │ │ └── UserMapper.java │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── mybatis │ │ └── MyBatisTest.java └── pom.xml ├── spring-boot-integration-11-actuator ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── actuator │ │ │ ├── SpringBootActuatorApplication.java │ │ │ ├── info │ │ │ └── ApplicationInfoContributor.java │ │ │ ├── controller │ │ │ └── DemoController.java │ │ │ └── health │ │ │ └── XxlJobHealthIndicator.java │ │ └── resources │ │ └── application.properties └── pom.xml ├── spring-boot-integration-06-cache ├── src │ ├── main │ │ ├── resources │ │ │ ├── mapper │ │ │ │ └── UserMapper.xml │ │ │ └── application.properties │ │ └── java │ │ │ └── com │ │ │ └── linkedbear │ │ │ └── boot │ │ │ └── cache │ │ │ ├── component │ │ │ └── UserKeyGenerator.java │ │ │ ├── SpringBootCacheApplication.java │ │ │ ├── service │ │ │ ├── UserService.java │ │ │ ├── RedisCacheService.java │ │ │ ├── AnnotationUserService.java │ │ │ └── CachedUserService.java │ │ │ ├── entity │ │ │ └── User.java │ │ │ ├── config │ │ │ └── RedisConfiguration.java │ │ │ └── mapper │ │ │ └── UserMapper.java │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── cache │ │ ├── RedisCacheTest.java │ │ └── CacheTest.java └── pom.xml ├── spring-boot-integration-04-springdata ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── linkedbear │ │ │ │ └── boot │ │ │ │ └── springdata │ │ │ │ ├── jpa │ │ │ │ ├── dao │ │ │ │ │ ├── DepartmentDao.java │ │ │ │ │ └── UserDao.java │ │ │ │ ├── service │ │ │ │ │ └── UserService.java │ │ │ │ └── entity │ │ │ │ │ ├── User.java │ │ │ │ │ └── Department.java │ │ │ │ ├── mongo │ │ │ │ ├── config │ │ │ │ │ └── MongoConfiguration.java │ │ │ │ ├── dao │ │ │ │ │ └── UserRepository.java │ │ │ │ ├── service │ │ │ │ │ ├── DepartmentService.java │ │ │ │ │ └── UserService.java │ │ │ │ └── entity │ │ │ │ │ ├── Department.java │ │ │ │ │ └── User.java │ │ │ │ ├── redis │ │ │ │ └── RedisConfiguration.java │ │ │ │ └── SpringBootDataApplication.java │ │ └── resources │ │ │ └── application.properties │ └── test │ │ └── java │ │ └── com │ │ └── linkedbear │ │ └── boot │ │ └── springdata │ │ ├── JpaTest.java │ │ └── MongoTest.java └── pom.xml └── spring-boot-integration-parent └── pom.xml /spring-boot-integration-01-starter/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spring-boot-integration-11-admin/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8989 -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | knife4j.enable=true 2 | knife4j.production=false -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.elasticsearch.rest.uris=http://192.168.217.142:9200 -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=32123 2 | 3 | rocketmq.name-server=127.0.0.1:9876 -------------------------------------------------------------------------------- /xxl-job-boot-starter/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | com.linkedbear.boot.xxljob.autoconfigure.XxlJobAutoConfiguration -------------------------------------------------------------------------------- /spring-boot-integration-09-xxljob/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | xxl.job.admin.addresses=http://127.0.0.1:18899/xxl-job-admin 2 | xxl.job.executor.appname=demo-xxl-job-executor 3 | xxl.job.accessToken=default_token -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/resources/caffeine.properties: -------------------------------------------------------------------------------- 1 | ######################################### 2 | # Caffeine configuration 3 | # [name] = size, xxxx[s|m|h|d] 4 | ######################################### 5 | 6 | default = 1000, 30m -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | 6 | spring.quartz.job-store-type=jdbc 7 | spring.quartz.jdbc.initialize-schema=always -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=12321 2 | 3 | rocketmq.name-server=127.0.0.1:9876 4 | rocketmq.producer.group=myproducer 5 | 6 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 8 | spring.datasource.username=root 9 | spring.datasource.password=123456 -------------------------------------------------------------------------------- /spring-boot-integration-09-xxljob/src/main/java/com/linkedbear/boot/xxljob/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.xxljob.service; 2 | 3 | import com.xxl.job.core.handler.annotation.XxlJob; 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service 7 | public class DemoService { 8 | 9 | @XxlJob("demoTest") 10 | public void test() { 11 | System.out.println("触发定时任务 。。。"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/test/java/com/linkedbear/boot/junit/demo/InnerTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.junit.demo; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | public class InnerTest { 8 | 9 | @Test 10 | public void test3() throws Exception { 11 | System.out.println("Inner test run ......"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/dao/ResourceDao.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.dao; 2 | 3 | import com.linkedbear.boot.security.entity.Resource; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface ResourceDao extends JpaRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/resources/jwt_rsa.pub: -------------------------------------------------------------------------------- 1 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7LnU5y0FQ06iluw5H3iIHnVkAipoS3aUzF00ChmX3PyQEWlvOSQCdEezVz9jKI+vzYtuQ6YuVyppSAeRmgzjwQJPyStisJ14cjk5FBXIK/4GiCwAVfzYc2KVb8M7TazkAaKmGgUBu/4gAkIqjDotduiGCgIbhrOlze8EUi3NTl/h3wTr35lXDI+5JM6dkAfyMQj//hy5iu2Z8PbGhKpqZ1Dv3fqOnIYFW0HtqRr0Q07ATUil1OVM4u23hOy3E0R5Pl0WD6ETlkoxHLwyWcxF2poWgDQjVwTbYTrL0K59v4vNDDgi1iqVpmpIpY07jlzriEn+5hoejVw5HLJy9neGDQIDAQAB -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | 6 | mybatis.type-aliases-package=com.linkedbear.boot.mybatis.entity 7 | mybatis.mapper-locations=classpath:mapper/*.xml 8 | mybatis.configuration.map-underscore-to-camel-case=true -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/template/DataUpdateRocketMQTemplate.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.template; 2 | 3 | import org.apache.rocketmq.spring.annotation.ExtRocketMQTemplateConfiguration; 4 | import org.apache.rocketmq.spring.core.RocketMQTemplate; 5 | 6 | @ExtRocketMQTemplateConfiguration 7 | public class DataUpdateRocketMQTemplate extends RocketMQTemplate { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/main/java/com/linkedbear/boot/junit/SpringBootJUnitApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.junit; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootJUnitApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootJUnitApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/main/java/com/linkedbear/boot/junit/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.junit.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.client.RestTemplate; 6 | 7 | @Configuration 8 | public class WebConfig { 9 | 10 | @Bean 11 | public RestTemplate restTemplate() { 12 | return new RestTemplate(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/test/java/demo/OuterTest.java: -------------------------------------------------------------------------------- 1 | package demo; 2 | 3 | import com.linkedbear.boot.junit.SpringBootJUnitApplication; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | 7 | @SpringBootTest(classes = SpringBootJUnitApplication.class) 8 | public class OuterTest { 9 | 10 | @Test 11 | public void test4() throws Exception { 12 | System.out.println("Outer test run ......"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-09-xxljob/src/main/java/com/linkedbear/boot/xxljob/SpringBootXxlJobApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.xxljob; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootXxlJobApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootXxlJobApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-01-starter/src/main/java/com/linkedbear/boot/starter/SpringBootStarterApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.starter; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootStarterApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootStarterApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/main/java/com/linkedbear/boot/elasticsearch/dao/GraphicsCardRepository.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch.dao; 2 | 3 | import com.linkedbear.boot.elasticsearch.entity.GraphicsCard; 4 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface GraphicsCardRepository extends ElasticsearchRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/src/main/java/com/linkedbear/boot/actuator/SpringBootActuatorApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.actuator; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootActuatorApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootActuatorApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/SpringBootSecurityApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootSecurityApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootSecurityApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.security.user.name=user 2 | spring.security.user.password=000000 3 | spring.security.user.roles=admin 4 | 5 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 6 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 7 | spring.datasource.username=root 8 | spring.datasource.password=123456 9 | 10 | spring.jpa.database=mysql 11 | spring.jpa.hibernate.ddl-auto=update 12 | spring.jpa.show-sql=true -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/main/java/com/linkedbear/boot/elasticsearch/SpringBootElasticSearchApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootElasticSearchApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootElasticSearchApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | insert into tbl_user (name, tel) values (#{name}, #{tel}) 8 | 9 | 10 | 13 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | insert into tbl_user (name, tel) values (#{name}, #{tel}) 8 | 9 | 10 | 13 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | insert into tbl_user (name, tel) values (#{name}, #{tel}) 8 | 9 | 10 | 13 | -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/main/java/com/linkedbear/boot/elasticsearch/entity/GraphicsCard.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch.entity; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | import org.springframework.data.elasticsearch.annotations.Document; 6 | 7 | @Data 8 | @Document(indexName = "gpu") 9 | public class GraphicsCard { 10 | 11 | @Id 12 | private Integer id; 13 | 14 | private String name; 15 | 16 | private String brand; 17 | 18 | private Integer price; 19 | } -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/component/UserKeyGenerator.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.component; 2 | 3 | import org.springframework.cache.interceptor.KeyGenerator; 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.lang.reflect.Method; 7 | 8 | @Component 9 | public class UserKeyGenerator implements KeyGenerator { 10 | 11 | @Override 12 | public Object generate(Object target, Method method, Object... params) { 13 | return method.getName() + params[0]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/SpringBootRocketMQConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootRocketMQConsumerApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootRocketMQConsumerApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/SpringBootRocketMQProducerApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootRocketMQProducerApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootRocketMQProducerApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/jpa/dao/DepartmentDao.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.jpa.dao; 2 | 3 | import com.linkedbear.boot.springdata.jpa.entity.Department; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | public interface DepartmentDao extends JpaRepository, JpaSpecificationExecutor { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/SpringBootCacheApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | 7 | @EnableCaching 8 | @SpringBootApplication 9 | public class SpringBootCacheApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootCacheApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/SpringBootJ2cacheApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | 7 | @EnableCaching 8 | @SpringBootApplication 9 | public class SpringBootJ2cacheApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootJ2cacheApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/src/main/java/com/linkedbear/boot/quartz/SpringBootQuartzApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.quartz; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.scheduling.annotation.EnableScheduling; 6 | 7 | @EnableScheduling 8 | @SpringBootApplication 9 | public class SpringBootQuartzApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootQuartzApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-11-admin/src/main/java/com/linkedbear/boot/actuator/SpringBootAdminApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.actuator; 2 | 3 | import de.codecentric.boot.admin.server.config.EnableAdminServer; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @EnableAdminServer 8 | @SpringBootApplication 9 | public class SpringBootAdminApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootAdminApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/src/main/java/com/linkedbear/boot/quartz/quartz/SimpleJob.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.quartz.quartz; 2 | 3 | import org.quartz.Job; 4 | import org.quartz.JobExecutionContext; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | public class SimpleJob implements Job { 9 | 10 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 11 | 12 | @Override 13 | public void execute(JobExecutionContext context) { 14 | logger.info("简单任务执行 ...... " + context.getJobDetail().getKey().getName()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/SpringBootSwaggerApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.swagger; 2 | 3 | import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | @EnableKnife4j 9 | public class SpringBootSwaggerApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootSwaggerApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.dao; 2 | 3 | import com.linkedbear.boot.security.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.List; 9 | 10 | @Repository 11 | public interface UserDao extends JpaRepository, JpaSpecificationExecutor { 12 | 13 | List findAllByUsername(String username); 14 | } 15 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | 6 | spring.jdbc.template.max-rows=100 7 | 8 | spring.jpa.database=mysql 9 | spring.jpa.hibernate.ddl-auto=update 10 | spring.jpa.show-sql=true 11 | 12 | spring.redis.host=localhost 13 | spring.redis.port=6379 14 | 15 | spring.data.mongodb.host=127.0.0.1 16 | spring.data.mongodb.port=27017 17 | spring.data.mongodb.database=spring-data -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | management.endpoints.enabled-by-default=true 2 | management.endpoints.web.exposure.include=* 3 | management.endpoint.health.show-details=always 4 | 5 | xxl.job.admin-addresses=http://127.0.0.1:18899/xxl-job-admin 6 | xxl.job.appname=demo-xxl-job-executor 7 | xxl.job.address=http://192.168.50.130:9999 8 | 9 | info.appName=spring-boot-integration-11-actuator 10 | info.version=@project.version@ 11 | 12 | spring.application.name=spring-boot-integration-11-actuator 13 | spring.boot.admin.client.url=http://localhost:8989 14 | spring.boot.admin.client.instance.prefer-ip=true -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/src/main/java/com/linkedbear/boot/quartz/quartz/ScheduleService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.quartz.quartz; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.scheduling.annotation.Scheduled; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class ScheduleService { 10 | 11 | private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleService.class); 12 | 13 | @Scheduled(cron = "0/5 * * * * *") 14 | public void test() { 15 | LOGGER.info("ScheduleService test invoke ......"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/controller/DemoController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.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 | @RestController 8 | public class DemoController { 9 | 10 | @GetMapping("/demo") 11 | public String demo() { 12 | return "demo"; 13 | } 14 | 15 | @GetMapping("/getData") 16 | public String getData(String name) { 17 | return "userData-" + name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/java/com/linkedbear/boot/mybatis/SpringBootMyBatisApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatis; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.transaction.annotation.EnableTransactionManagement; 7 | 8 | @MapperScan 9 | @EnableTransactionManagement 10 | @SpringBootApplication 11 | public class SpringBootMyBatisApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringBootMyBatisApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | #spring.cache.type=redis 6 | spring.cache.redis.use-key-prefix=true 7 | spring.cache.redis.key-prefix=boot 8 | spring.cache.redis.time-to-live=10s 9 | 10 | mybatis.type-aliases-package=com.linkedbear.boot.cache.entity 11 | mybatis.mapper-locations=classpath:mapper/*.xml 12 | mybatis.configuration.map-underscore-to-camel-case=true 13 | 14 | logging.level.com.linkedbear.boot.cache.mapper.UserMapper=debug -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | 6 | mybatis-plus.type-aliases-package=com.linkedbear.boot.mybatisplus.entity 7 | mybatis-plus.mapper-locations=classpath:mapper/*.xml 8 | mybatis-plus.configuration.map-underscore-to-camel-case=true 9 | 10 | mybatis-plus.global-config.db-config.logic-delete-field=deleted 11 | mybatis-plus.global-config.db-config.logic-delete-value=1 12 | mybatis-plus.global-config.db-config.logic-not-delete-value=0 -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/java/com/linkedbear/boot/mybatisplus/SpringBootMyBatisPlusApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.transaction.annotation.EnableTransactionManagement; 7 | 8 | @MapperScan 9 | @EnableTransactionManagement 10 | @SpringBootApplication 11 | public class SpringBootMyBatisPlusApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringBootMyBatisPlusApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/config/MongoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.mongodb.MongoDatabaseFactory; 6 | import org.springframework.data.mongodb.MongoTransactionManager; 7 | 8 | @Configuration(proxyBeanMethods = false) 9 | public class MongoConfiguration { 10 | 11 | @Bean 12 | public MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory databaseFactory) { 13 | return new MongoTransactionManager(databaseFactory); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/SoftwareMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 4 | import org.apache.rocketmq.spring.core.RocketMQListener; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @RocketMQMessageListener(topic = "test-tags", consumerGroup = "tagsconsumer", selectorExpression = "software") 9 | public class SoftwareMessageReceiver implements RocketMQListener { 10 | 11 | @Override 12 | public void onMessage(String message) { 13 | System.out.println("收到software消息:" + message); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/dao/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.dao; 2 | 3 | import com.linkedbear.boot.springdata.mongo.entity.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | 9 | @Repository 10 | public interface UserRepository extends MongoRepository { 11 | 12 | User findByName(String name); 13 | 14 | List findAllByNameLike(String nameLike); 15 | 16 | List findAllByAgeGreaterThan(Integer age); 17 | 18 | List findAllByNameInOrderByAgeDesc(List names); 19 | } 20 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/TransactionalReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 4 | import org.apache.rocketmq.spring.core.RocketMQListener; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @RocketMQMessageListener(topic = "test-transactional", consumerGroup = "transactionalconsumer") 9 | public class TransactionalReceiver implements RocketMQListener { 10 | 11 | @Override 12 | public void onMessage(String message) { 13 | System.out.println("接收到事务消息!"); 14 | System.out.println(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/DelayMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 4 | import org.apache.rocketmq.spring.core.RocketMQListener; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @RocketMQMessageListener(topic = "test-delay", consumerGroup = "delayconsumer") 9 | public class DelayMessageReceiver implements RocketMQListener { 10 | 11 | @Override 12 | public void onMessage(String message) { 13 | System.out.println("接收到消息:" + message); 14 | System.out.println(System.currentTimeMillis()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-parent/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | org.springframework.boot 9 | spring-boot-starter-parent 10 | 2.5.14 11 | 12 | 13 | com.linkedbear.boot 14 | spring-boot-integration-parent 15 | 1.0.0-RELEASE 16 | pom 17 | 18 | 19 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/test/java/com/linkedbear/boot/junit/SpringBootApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.junit; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | @SpringBootTest 9 | public class SpringBootApplicationTest { 10 | 11 | @Autowired 12 | private RestTemplate restTemplate; 13 | 14 | @Test 15 | public void test1() { 16 | System.out.println("SpringBootApplicationTest test1 run ......"); 17 | } 18 | 19 | @Test 20 | public void test2() { 21 | System.out.println(restTemplate); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/DataUpdateTransactionalReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 4 | import org.apache.rocketmq.spring.core.RocketMQListener; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @RocketMQMessageListener(topic = "test-transactionalupdate", consumerGroup = "transactionalupdateconsumer") 9 | public class DataUpdateTransactionalReceiver implements RocketMQListener { 10 | 11 | @Override 12 | public void onMessage(String message) { 13 | System.out.println("接收到update事务消息!"); 14 | System.out.println(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/OrderedMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.ConsumeMode; 4 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 5 | import org.apache.rocketmq.spring.core.RocketMQListener; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | @RocketMQMessageListener(topic = "test-ordered", consumerGroup = "orderedconsumer", consumeMode = ConsumeMode.ORDERLY) 10 | public class OrderedMessageReceiver implements RocketMQListener { 11 | 12 | @Override 13 | public void onMessage(String message) { 14 | System.out.println(message); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/UserDtoMessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import com.linkedbear.boot.rocketmq.consumer.dto.UserDTO; 4 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 5 | import org.apache.rocketmq.spring.core.RocketMQListener; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | @RocketMQMessageListener(topic = "test-dto", consumerGroup = "dtoconsumer") 10 | public class UserDtoMessageReceiver implements RocketMQListener { 11 | 12 | @Override 13 | public void onMessage(UserDTO message) { 14 | System.out.println("接收到DTO消息"); 15 | System.out.println(message.toString()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/src/main/java/com/linkedbear/boot/actuator/info/ApplicationInfoContributor.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.actuator.info; 2 | 3 | import org.springframework.boot.actuate.info.Info; 4 | import org.springframework.boot.actuate.info.InfoContributor; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | @Component 11 | public class ApplicationInfoContributor implements InfoContributor { 12 | 13 | @Override 14 | public void contribute(Info.Builder builder) { 15 | builder.withDetail("appName", "spring-boot-integration-11-actuator-contributor"); 16 | Map data = new HashMap<>(); 17 | data.put("version", "1.0.0"); 18 | builder.withDetails(data); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/redis/RedisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.redis; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.connection.RedisConnectionFactory; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | 8 | //@Configuration(proxyBeanMethods = false) 9 | public class RedisConfiguration { 10 | 11 | @Bean 12 | public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { 13 | RedisTemplate redisTemplate = new RedisTemplate<>(); 14 | redisTemplate.setConnectionFactory(redisConnectionFactory); 15 | return redisTemplate; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/SpringBootDataApplication.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 6 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 7 | import org.springframework.transaction.annotation.EnableTransactionManagement; 8 | 9 | @SpringBootApplication 10 | @EnableJpaRepositories 11 | @EnableMongoRepositories 12 | @EnableTransactionManagement 13 | public class SpringBootDataApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SpringBootDataApplication.class, args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.service; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import com.linkedbear.boot.cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | 10 | @Service 11 | public class UserService { 12 | 13 | @Autowired 14 | private UserMapper userMapper; 15 | 16 | public User get(Integer id) { 17 | return userMapper.get(id); 18 | } 19 | 20 | public List findAll() { 21 | return userMapper.findAll(); 22 | } 23 | 24 | public List findAllByName(String name) { 25 | return userMapper.findAllByNameLike(name); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache.service; 2 | 3 | import com.linkedbear.boot.j2cache.entity.User; 4 | import com.linkedbear.boot.j2cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | 10 | @Service 11 | public class UserService { 12 | 13 | @Autowired 14 | private UserMapper userMapper; 15 | 16 | public User get(Integer id) { 17 | return userMapper.get(id); 18 | } 19 | 20 | public List findAll() { 21 | return userMapper.findAll(); 22 | } 23 | 24 | public List findAllByName(String name) { 25 | return userMapper.findAllByNameLike(name); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/service/DepartmentService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.service; 2 | 3 | import com.linkedbear.boot.springdata.mongo.entity.Department; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.data.mongodb.core.MongoTemplate; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | @Service 10 | public class DepartmentService { 11 | 12 | @Autowired 13 | private MongoTemplate mongoTemplate; 14 | 15 | @Transactional(rollbackFor = Exception.class) 16 | public void save() { 17 | Department department = new Department(); 18 | department.setName("dept"); 19 | department.setTel("1234321"); 20 | mongoTemplate.save(department); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/test/java/com/linkedbear/boot/cache/RedisCacheTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache; 2 | 3 | import com.linkedbear.boot.cache.service.RedisCacheService; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | 8 | @SpringBootTest 9 | public class RedisCacheTest { 10 | 11 | @Autowired 12 | private RedisCacheService redisCacheService; 13 | 14 | @Test 15 | public void test1() throws Exception { 16 | redisCacheService.getName(1); 17 | redisCacheService.getName(1); 18 | redisCacheService.getName(1); 19 | } 20 | 21 | @Test 22 | public void test2() throws Exception { 23 | redisCacheService.getUser(1); 24 | redisCacheService.getUser(1); 25 | redisCacheService.getUser(1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/TokenPayload.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import org.springframework.security.core.userdetails.User; 4 | 5 | import java.util.Date; 6 | 7 | public class TokenPayload { 8 | 9 | private String id; 10 | 11 | private User user; 12 | 13 | private Date expiration; 14 | 15 | public String getId() { 16 | return id; 17 | } 18 | 19 | public void setId(String id) { 20 | this.id = id; 21 | } 22 | 23 | public User getUser() { 24 | return user; 25 | } 26 | 27 | public void setUser(User user) { 28 | this.user = user; 29 | } 30 | 31 | public Date getExpiration() { 32 | return expiration; 33 | } 34 | 35 | public void setExpiration(Date expiration) { 36 | this.expiration = expiration; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/java/com/linkedbear/boot/mybatis/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatis.entity; 2 | 3 | public class User { 4 | 5 | private Integer id; 6 | 7 | private String name; 8 | 9 | private String tel; 10 | 11 | @Override 12 | public String toString() { 13 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 14 | } 15 | 16 | public Integer getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Integer id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public String getTel() { 33 | return tel; 34 | } 35 | 36 | public void setTel(String tel) { 37 | this.tel = tel; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/src/main/java/com/linkedbear/boot/actuator/controller/DemoController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.actuator.controller; 2 | 3 | import io.micrometer.core.instrument.Counter; 4 | import io.micrometer.core.instrument.MeterRegistry; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import javax.annotation.PostConstruct; 10 | 11 | @RestController 12 | public class DemoController { 13 | 14 | @Autowired 15 | private MeterRegistry meterRegistry; 16 | 17 | private Counter counter; 18 | 19 | @PostConstruct 20 | public void init() { 21 | counter = meterRegistry.counter("demo.request"); 22 | } 23 | 24 | @GetMapping("/demo") 25 | public String demo() { 26 | counter.increment(); 27 | return "demo"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.service; 2 | 3 | import com.linkedbear.boot.springdata.mongo.dao.UserRepository; 4 | import com.linkedbear.boot.springdata.mongo.entity.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | @Service("mongoUserService") 10 | public class UserService { 11 | 12 | @Autowired 13 | private UserRepository userRepository; 14 | 15 | @Transactional(rollbackFor = Exception.class) 16 | public void saveAndPrint() { 17 | User user = new User(); 18 | user.setName("save"); 19 | user.setAge(20); 20 | userRepository.save(user); 21 | 22 | int i = 1 / 0; 23 | 24 | System.out.println(userRepository.findAll()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/main/java/com/linkedbear/boot/elasticsearch/config/ElasticSearchConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch.config; 2 | 3 | import org.apache.http.HttpHost; 4 | import org.elasticsearch.client.RestClient; 5 | import org.elasticsearch.client.RestClientBuilder; 6 | import org.elasticsearch.client.RestHighLevelClient; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | //@Configuration(proxyBeanMethods = false) 12 | public class ElasticSearchConfiguration { 13 | 14 | @Value("${spring.elasticsearch.rest.uris}") 15 | private String esHost; 16 | 17 | @Bean(destroyMethod = "close") 18 | public RestHighLevelClient restHighLevelClient() { 19 | RestClientBuilder builder = RestClient.builder(HttpHost.create(esHost)); 20 | return new RestHighLevelClient(builder); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/controller/ApiController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.controller; 2 | 3 | import com.linkedbear.boot.security.entity.User; 4 | import com.linkedbear.boot.security.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | @RequestMapping("/api") 12 | public class ApiController { 13 | 14 | @Autowired 15 | private UserService userService; 16 | 17 | @GetMapping("/test") 18 | public String test() { 19 | return "test"; 20 | } 21 | 22 | @GetMapping("/getUser") 23 | public String getUser(Integer id) { 24 | System.out.println("进入getUser方法!"); 25 | return userService.get(id).getName(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/java/com/linkedbear/boot/mybatis/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatis.service; 2 | 3 | import com.linkedbear.boot.mybatis.entity.User; 4 | import com.linkedbear.boot.mybatis.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.List; 10 | 11 | @Service 12 | public class UserService { 13 | 14 | @Autowired 15 | private UserMapper userMapper; 16 | 17 | @Transactional(rollbackFor = Exception.class) 18 | public void test() { 19 | User user = new User(); 20 | user.setName("test mybatis"); 21 | user.setTel("7654321"); 22 | userMapper.save(user); 23 | 24 | // int i = 1 / 0; 25 | 26 | List userList = userMapper.findAll(); 27 | userList.forEach(System.out::println); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/service/RedisCacheService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.service; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import com.linkedbear.boot.cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.cache.annotation.Cacheable; 7 | import org.springframework.data.redis.cache.RedisCacheManager; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.Map; 11 | 12 | @Service 13 | public class RedisCacheService { 14 | 15 | @Autowired 16 | private UserMapper userMapper; 17 | 18 | @Cacheable(value = "getName") 19 | public String getName(Integer i) { 20 | System.out.println("getName invoke ......"); 21 | return "name" + i; 22 | } 23 | 24 | @Cacheable(value = "getUser", cacheManager = "userCacheManager") 25 | public User getUser(Integer id) { 26 | return userMapper.get(id); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/jpa/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.jpa.service; 2 | 3 | import com.linkedbear.boot.springdata.jpa.dao.UserDao; 4 | import com.linkedbear.boot.springdata.jpa.entity.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.List; 10 | 11 | @Service 12 | public class UserService { 13 | 14 | @Autowired 15 | private UserDao userDao; 16 | 17 | @Transactional(rollbackFor = Exception.class) 18 | public void test() { 19 | User user = new User(); 20 | user.setName("test mybatis"); 21 | user.setTel("7654321"); 22 | userDao.save(user); 23 | 24 | // int i = 1 / 0; 25 | 26 | List userList = userDao.findAll(); 27 | userList.forEach(System.out::println); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/test/java/com/linkedbear/boot/mybatis/MyBatisTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatis; 2 | 3 | import com.linkedbear.boot.mybatis.entity.User; 4 | import com.linkedbear.boot.mybatis.mapper.UserMapper; 5 | import com.linkedbear.boot.mybatis.service.UserService; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | 10 | import java.util.List; 11 | 12 | @SpringBootTest 13 | public class MyBatisTest { 14 | 15 | @Autowired 16 | private UserMapper userMapper; 17 | 18 | @Autowired 19 | private UserService userService; 20 | 21 | @Test 22 | public void test1() { 23 | userService.test(); 24 | } 25 | 26 | @Test 27 | public void test2() { 28 | List users = userMapper.findAll(); 29 | System.out.println(users); 30 | } 31 | 32 | @Test 33 | public void test3() throws Exception { 34 | userMapper.excuteDDL(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | public class User implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private Integer id; 9 | 10 | private String name; 11 | 12 | private String tel; 13 | 14 | @Override 15 | public String toString() { 16 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 17 | } 18 | 19 | public Integer getId() { 20 | return id; 21 | } 22 | 23 | public void setId(Integer id) { 24 | this.id = id; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getTel() { 36 | return tel; 37 | } 38 | 39 | public void setTel(String tel) { 40 | this.tel = tel; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | public class User implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | 8 | private Integer id; 9 | 10 | private String name; 11 | 12 | private String tel; 13 | 14 | @Override 15 | public String toString() { 16 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 17 | } 18 | 19 | public Integer getId() { 20 | return id; 21 | } 22 | 23 | public void setId(Integer id) { 24 | this.id = id; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getTel() { 36 | return tel; 37 | } 38 | 39 | public void setTel(String tel) { 40 | this.tel = tel; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/java/com/linkedbear/boot/mybatisplus/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 4 | import com.linkedbear.boot.mybatisplus.entity.User; 5 | import com.linkedbear.boot.mybatisplus.mapper.UserMapper; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import java.util.List; 11 | 12 | @Service 13 | public class UserService extends ServiceImpl { 14 | 15 | @Autowired 16 | private UserMapper userMapper; 17 | 18 | @Transactional(rollbackFor = Exception.class) 19 | public void test() { 20 | User user = new User(); 21 | user.setName("test mybatisplus"); 22 | user.setTel("7654321"); 23 | userMapper.insert(user); 24 | 25 | // int i = 1 / 0; 26 | 27 | List userList = userMapper.selectList(null); 28 | userList.forEach(System.out::println); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/java/com/linkedbear/boot/mybatisplus/config/MyBatisPlusConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus.config; 2 | 3 | import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; 4 | import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; 5 | import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; 6 | import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration(proxyBeanMethods = false) 11 | public class MyBatisPlusConfiguration { 12 | 13 | @Bean 14 | public MybatisPlusInterceptor mybatisPlusInterceptor() { 15 | MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); 16 | // 添加乐观锁插件 17 | interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); 18 | // 添加分页插件 19 | interceptor.addInnerInterceptor(new PaginationInnerInterceptor(new MySqlDialect())); 20 | return interceptor; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/java/com/linkedbear/boot/mybatisplus/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.baomidou.mybatisplus.core.metadata.IPage; 5 | import com.linkedbear.boot.mybatisplus.entity.User; 6 | import org.apache.ibatis.annotations.Mapper; 7 | import org.apache.ibatis.annotations.Param; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | @Mapper 14 | @Repository 15 | public interface UserMapper extends BaseMapper { 16 | 17 | /** 18 | * 使用IPage作为入参和返回值 19 | * @param query 20 | * @return 21 | */ 22 | IPage page(IPage query); 23 | 24 | /** 25 | * 使用集合作为返回值 26 | * @param query 27 | * @return 28 | */ 29 | List pageList(IPage query); 30 | 31 | /** 32 | * 使用IPage和其他参数共同作为入参 33 | * @param page 34 | * @param params 35 | * @return 36 | */ 37 | IPage pageParams(@Param("page") IPage page, @Param("params") Map params); 38 | } 39 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/entity/Department.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.entity; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.mapping.Document; 5 | 6 | @Document(collection = "doc_dept") 7 | public class Department { 8 | 9 | @Id 10 | private String id; 11 | 12 | private String name; 13 | 14 | private String tel; 15 | 16 | @Override 17 | public String toString() { 18 | return "Department{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 19 | } 20 | 21 | public String getId() { 22 | return id; 23 | } 24 | 25 | public void setId(String id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public String getTel() { 38 | return tel; 39 | } 40 | 41 | public void setTel(String tel) { 42 | this.tel = tel; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /xxl-job-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.5.14 10 | 11 | com.linkedbear.boot 12 | xxl-job-boot-starter 13 | 1.0-SNAPSHOT 14 | 15 | 16 | 1.8 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter 23 | 24 | 25 | 26 | com.xuxueli 27 | xxl-job-core 28 | 2.3.1 29 | 30 | 31 | -------------------------------------------------------------------------------- /spring-boot-integration-01-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-01-starter 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-maven-plugin 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/mongo/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.mongo.entity; 2 | 3 | import org.springframework.data.mongodb.core.mapping.Document; 4 | import org.springframework.data.mongodb.core.mapping.Field; 5 | 6 | import javax.persistence.Id; 7 | 8 | @Document(collection = "doc_user") 9 | public class User { 10 | 11 | @Id 12 | private String id; 13 | 14 | @Field("username") 15 | private String name; 16 | 17 | private Integer age; 18 | 19 | @Override 20 | public String toString() { 21 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; 22 | } 23 | 24 | public String getId() { 25 | return id; 26 | } 27 | 28 | public void setId(String id) { 29 | this.id = id; 30 | } 31 | 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | 40 | public Integer getAge() { 41 | return age; 42 | } 43 | 44 | public void setAge(Integer age) { 45 | this.age = age; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/src/main/java/com/linkedbear/boot/mybatis/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatis.mapper; 2 | 3 | import com.linkedbear.boot.mybatis.entity.User; 4 | import org.apache.ibatis.annotations.Delete; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.Select; 8 | import org.apache.ibatis.annotations.Update; 9 | import org.springframework.stereotype.Repository; 10 | 11 | import java.util.List; 12 | 13 | @Mapper 14 | @Repository 15 | public interface UserMapper { 16 | 17 | void save(User user); 18 | 19 | List findAll(); 20 | 21 | @Select("select * from tbl_user where name like concat('%', #{name}, '%')") 22 | List findAllByNameLike(@Param("name") String name); 23 | 24 | @Delete("delete from tbl_user where id = #{id}") 25 | int deleteById(String id); 26 | 27 | @Update("CREATE TABLE tbl_role (\n" 28 | + " id int(11) NOT NULL AUTO_INCREMENT,\n" 29 | + " code varchar(20) NULL,\n" 30 | + " name varchar(32) NULL,\n" 31 | + " PRIMARY KEY (id)\n" 32 | + ");") 33 | int excuteDDL(); 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.dto; 2 | 3 | public class UserDTO { 4 | 5 | private Integer userId; 6 | 7 | private String userName; 8 | 9 | private String sexName; 10 | 11 | @Override 12 | public String toString() { 13 | return "UserDTO{" 14 | + "userId=" 15 | + userId 16 | + ", userName='" 17 | + userName 18 | + '\'' 19 | + ", sexName='" 20 | + sexName 21 | + '\'' 22 | + '}'; 23 | } 24 | 25 | public Integer getUserId() { 26 | return userId; 27 | } 28 | 29 | public void setUserId(Integer userId) { 30 | this.userId = userId; 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 getSexName() { 42 | return sexName; 43 | } 44 | 45 | public void setSexName(String sexName) { 46 | this.sexName = sexName; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.dto; 2 | 3 | public class UserDTO { 4 | 5 | private Integer userId; 6 | 7 | private String userName; 8 | 9 | private String sexName; 10 | 11 | @Override 12 | public String toString() { 13 | return "UserDTO{" 14 | + "userId=" 15 | + userId 16 | + ", userName='" 17 | + userName 18 | + '\'' 19 | + ", sexName='" 20 | + sexName 21 | + '\'' 22 | + '}'; 23 | } 24 | 25 | public Integer getUserId() { 26 | return userId; 27 | } 28 | 29 | public void setUserId(Integer userId) { 30 | this.userId = userId; 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 getSexName() { 42 | return sexName; 43 | } 44 | 45 | public void setSexName(String sexName) { 46 | this.sexName = sexName; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/jpa/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.jpa.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.Table; 8 | 9 | @Entity 10 | @Table(name = "tbl_user") 11 | public class User { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Integer id; 16 | 17 | private String name; 18 | 19 | private String tel; 20 | 21 | @Override 22 | public String toString() { 23 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 24 | } 25 | 26 | public Integer getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Integer 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 String getTel() { 43 | return tel; 44 | } 45 | 46 | public void setTel(String tel) { 47 | this.tel = tel; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.swagger.entity; 2 | 3 | import io.swagger.annotations.ApiModel; 4 | import io.swagger.annotations.ApiModelProperty; 5 | 6 | @ApiModel(value = "用户类", description = "封装用户的基本信息") 7 | public class User { 8 | 9 | @ApiModelProperty(value = "用户id", required = true) 10 | private String id; 11 | 12 | @ApiModelProperty(value = "用户姓名", required = true) 13 | private String name; 14 | 15 | @ApiModelProperty(value = "用户年龄", notes = "只能传入大于0的数") 16 | private Integer age; 17 | 18 | @Override 19 | public String toString() { 20 | return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + '}'; 21 | } 22 | 23 | public String getId() { 24 | return id; 25 | } 26 | 27 | public void setId(String id) { 28 | this.id = id; 29 | } 30 | 31 | public String getName() { 32 | return name; 33 | } 34 | 35 | public void setName(String name) { 36 | this.name = name; 37 | } 38 | 39 | public Integer getAge() { 40 | return age; 41 | } 42 | 43 | public void setAge(Integer age) { 44 | this.age = age; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/jpa/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.jpa.dao; 2 | 3 | import com.linkedbear.boot.springdata.jpa.entity.User; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.data.repository.query.Param; 9 | import org.springframework.stereotype.Repository; 10 | 11 | import java.util.List; 12 | 13 | @Repository 14 | public interface UserDao extends JpaRepository, JpaSpecificationExecutor { 15 | 16 | @Query("from User") 17 | List findAllByQuery(); 18 | 19 | @Query("from User where name like %?1%") 20 | List findAllByNameLike(String name); 21 | 22 | @Query("from User where tel = :tel") 23 | List findAllByTel(@Param("tel") String tel); 24 | 25 | @Query("from User where id in :ids") 26 | List findAllByIds(@Param("ids") List ids); 27 | 28 | @Query("from User where name like %?1%") 29 | List findAllByNameLikePage(Pageable pageable, String name); 30 | 31 | List findAllById(Integer id); 32 | } 33 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/service/DataService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.jdbc.core.JdbcTemplate; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | @Service 9 | public class DataService { 10 | 11 | @Autowired 12 | private JdbcTemplate jdbcTemplate; 13 | 14 | @Transactional(rollbackFor = Exception.class) 15 | public void saveData(String data, String txId) { 16 | System.out.println("执行数据库insert操作。。。"); 17 | System.out.println(data); 18 | System.out.println("保存txId......"); 19 | jdbcTemplate.update("insert into tx_id (id) value (?)", txId); 20 | int i = 1 / 0; 21 | } 22 | 23 | public boolean contains(String txId) { 24 | return jdbcTemplate.queryForObject("select count(1) from tx_id where id = ?", Integer.class, txId) > 0; 25 | } 26 | 27 | @Transactional(rollbackFor = Exception.class) 28 | public void updateData(String txId) { 29 | System.out.println("执行数据库update操作。。。"); 30 | jdbcTemplate.update("insert into tx_id (id) value (?)", txId); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/entity/Resource.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.Table; 8 | 9 | @Entity 10 | @Table(name = "sys_resource") 11 | public class Resource { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Integer id; 16 | 17 | private String name; 18 | 19 | private String permission; 20 | 21 | @Override 22 | public String toString() { 23 | return "Resource{" + "id=" + id + ", name='" + name + '\'' + ", permission='" + permission + '\'' + '}'; 24 | } 25 | 26 | public Integer getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Integer 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 String getPermission() { 43 | return permission; 44 | } 45 | 46 | public void setPermission(String permission) { 47 | this.permission = permission; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/src/main/java/com/linkedbear/boot/rocketmq/consumer/service/MessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.consumer.service; 2 | 3 | import org.apache.rocketmq.common.message.MessageExt; 4 | import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; 5 | import org.apache.rocketmq.spring.core.RocketMQListener; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.nio.charset.StandardCharsets; 9 | 10 | @Component 11 | @RocketMQMessageListener(topic = "test-sender", consumerGroup = "myconsumer") 12 | public class MessageReceiver implements RocketMQListener { 13 | 14 | // @Override 15 | // public void onMessage(String message) { 16 | // System.out.println(System.currentTimeMillis()); 17 | // System.out.println("收到消息:" + message); 18 | // int i = 1 / 0; 19 | // } 20 | 21 | @Override 22 | public void onMessage(MessageExt ext) { 23 | int reconsumeTimes = ext.getReconsumeTimes(); 24 | if (reconsumeTimes > 3) { 25 | // 将消息保存到数据库 26 | // 直接返回,代表消息已经消费成功 27 | return; 28 | } 29 | System.out.println(System.currentTimeMillis()); 30 | String message = new String(ext.getBody(), StandardCharsets.UTF_8); 31 | System.out.println("收到消息:" + message); 32 | int i = 1 / 0; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/config/RedisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.data.redis.cache.RedisCacheConfiguration; 6 | import org.springframework.data.redis.cache.RedisCacheManager; 7 | import org.springframework.data.redis.connection.RedisConnectionFactory; 8 | import org.springframework.data.redis.serializer.RedisSerializationContext; 9 | import org.springframework.data.redis.serializer.RedisSerializer; 10 | 11 | import java.time.Duration; 12 | 13 | @Configuration(proxyBeanMethods = false) 14 | public class RedisConfiguration { 15 | 16 | @Bean 17 | public RedisCacheConfiguration redisCacheConfiguration() { 18 | return RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith( 19 | RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json())); 20 | } 21 | 22 | @Bean 23 | public RedisCacheManager userCacheManager(RedisConnectionFactory connectionFactory, 24 | RedisCacheConfiguration redisCacheConfiguration) { 25 | return RedisCacheManager.builder(connectionFactory) 26 | .cacheDefaults(redisCacheConfiguration.entryTtl(Duration.ofMinutes(1))).build(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /spring-boot-integration-09-xxljob/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-09-xxljob 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | com.xuxueli 23 | xxl-job-core 24 | 2.3.1 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-maven-plugin 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /spring-boot-integration-11-admin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-11-admin 14 | 15 | 16 | 17 | de.codecentric 18 | spring-boot-admin-starter-server 19 | 2.5.6 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-maven-plugin 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-02-junit 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-test 24 | test 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-maven-plugin 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-08-rocketmq-consumer 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.apache.rocketmq 23 | rocketmq-spring-boot-starter 24 | 2.2.2 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-maven-plugin 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/entity/SecurityUser.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 7 | import org.springframework.security.core.userdetails.User; 8 | 9 | import java.util.Collection; 10 | import java.util.List; 11 | import java.util.Map; 12 | import java.util.stream.Collectors; 13 | 14 | /** 15 | * 用于解决User无法使用jackson反序列的问题 16 | */ 17 | public class SecurityUser extends User { 18 | 19 | @JsonCreator 20 | public SecurityUser(@JsonProperty("username") String username, @JsonProperty("password") String password, 21 | @JsonProperty("authorities") List> authorities) { 22 | super(username, "", authorities.stream().map(i -> new SimpleGrantedAuthority(i.get("authority"))).collect(Collectors.toList())); 23 | } 24 | 25 | public SecurityUser(String username, String password, boolean enabled, boolean accountNonExpired, 26 | boolean credentialsNonExpired, boolean accountNonLocked, 27 | Collection authorities) { 28 | super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.mapper; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import org.apache.ibatis.annotations.Delete; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.Select; 8 | import org.apache.ibatis.annotations.Update; 9 | import org.springframework.stereotype.Repository; 10 | 11 | import java.util.List; 12 | 13 | @Mapper 14 | @Repository 15 | public interface UserMapper { 16 | 17 | void save(User user); 18 | 19 | List findAll(); 20 | 21 | @Select("select * from tbl_user where id = #{value}") 22 | User get(Integer id); 23 | 24 | @Select("select * from tbl_user where name like concat('%', #{name}, '%')") 25 | List findAllByNameLike(@Param("name") String name); 26 | 27 | @Delete("delete from tbl_user where id = #{id}") 28 | int deleteById(String id); 29 | 30 | @Update("CREATE TABLE tbl_role (\n" 31 | + " id int(11) NOT NULL AUTO_INCREMENT,\n" 32 | + " code varchar(20) NULL,\n" 33 | + " name varchar(32) NULL,\n" 34 | + " PRIMARY KEY (id)\n" 35 | + ");") 36 | int excuteDDL(); 37 | 38 | @Update("update tbl_user set name = #{name} where id = #{id}") 39 | void updateById(User user); 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache.mapper; 2 | 3 | import com.linkedbear.boot.j2cache.entity.User; 4 | import org.apache.ibatis.annotations.Delete; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.Select; 8 | import org.apache.ibatis.annotations.Update; 9 | import org.springframework.stereotype.Repository; 10 | 11 | import java.util.List; 12 | 13 | @Mapper 14 | @Repository 15 | public interface UserMapper { 16 | 17 | void save(User user); 18 | 19 | List findAll(); 20 | 21 | @Select("select * from tbl_user where id = #{value}") 22 | User get(Integer id); 23 | 24 | @Select("select * from tbl_user where name like concat('%', #{name}, '%')") 25 | List findAllByNameLike(@Param("name") String name); 26 | 27 | @Delete("delete from tbl_user where id = #{id}") 28 | int deleteById(String id); 29 | 30 | @Update("CREATE TABLE tbl_role (\n" 31 | + " id int(11) NOT NULL AUTO_INCREMENT,\n" 32 | + " code varchar(20) NULL,\n" 33 | + " name varchar(32) NULL,\n" 34 | + " PRIMARY KEY (id)\n" 35 | + ");") 36 | int excuteDDL(); 37 | 38 | @Update("update tbl_user set name = #{name} where id = #{id}") 39 | void updateById(User user); 40 | } 41 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/test/java/com/linkedbear/boot/mybatisplus/CodeGenerator.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus; 2 | 3 | import com.baomidou.mybatisplus.generator.FastAutoGenerator; 4 | import com.baomidou.mybatisplus.generator.config.OutputFile; 5 | import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; 6 | 7 | import java.util.Collections; 8 | 9 | public class CodeGenerator { 10 | 11 | public static void main(String[] args) { 12 | FastAutoGenerator.create("jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8", "root", "123456") 13 | .globalConfig(builder -> { 14 | builder.author("LinkedBear") // 设置代码的author 15 | .outputDir("D://codegenerator"); // 指定输出目录 16 | }) 17 | .packageConfig(builder -> { 18 | builder.parent("com.linkedbear.boot.mybatisplus") // 设置父包名 19 | .moduleName("user") // 设置父包模块名 20 | .pathInfo(Collections.singletonMap(OutputFile.xml, "D://codegenerator")); // 设置mapperXml生成路径 21 | }) 22 | .strategyConfig(builder -> { 23 | builder.addInclude("tbl_user") // 设置需要生成的表名 24 | .addTablePrefix("tbl_"); // 设置过滤表前缀 25 | }) 26 | .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板 27 | .execute(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/service/AnnotationUserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache.service; 2 | 3 | import com.linkedbear.boot.j2cache.entity.User; 4 | import com.linkedbear.boot.j2cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.cache.annotation.CacheEvict; 7 | import org.springframework.cache.annotation.CachePut; 8 | import org.springframework.cache.annotation.Cacheable; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | @Service 14 | public class AnnotationUserService { 15 | 16 | @Autowired 17 | private UserMapper userMapper; 18 | 19 | @Cacheable(value = "j2cache.user.get", key = "#id") 20 | public User get(Integer id) { 21 | return userMapper.get(id); 22 | } 23 | 24 | public List findAll() { 25 | return userMapper.findAll(); 26 | } 27 | 28 | public List findAllByName(String name) { 29 | return userMapper.findAllByNameLike(name); 30 | } 31 | 32 | @CachePut(value = "j2cache.user.get", key = "#user.id") 33 | public User update(User user) { 34 | userMapper.updateById(user); 35 | return user; 36 | } 37 | 38 | @CacheEvict(value = "j2cache.user.get", key = "#id") 39 | public void deleteById(Integer id) { 40 | // userMapper.deleteById(id); 41 | System.out.println("deleteById invoke ......"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/test/java/com/linkedbear/boot/security/AddUserTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security; 2 | 3 | import com.linkedbear.boot.security.dao.UserDao; 4 | import com.linkedbear.boot.security.entity.User; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | 10 | @SpringBootTest 11 | public class AddUserTest { 12 | 13 | @Autowired 14 | private PasswordEncoder passwordEncoder; 15 | 16 | @Autowired 17 | private UserDao userDao; 18 | 19 | @Test 20 | public void testAddUser() throws Exception { 21 | User user = new User(); 22 | user.setUsername("xiaoshuai"); 23 | user.setPassword(passwordEncoder.encode("123456")); 24 | user.setName("小帅"); 25 | user.setTel("123456789"); 26 | userDao.save(user); 27 | 28 | user = new User(); 29 | user.setUsername("xiaoming"); 30 | user.setPassword(passwordEncoder.encode("654321")); 31 | user.setName("小明"); 32 | user.setTel("987654321"); 33 | userDao.save(user); 34 | 35 | user = new User(); 36 | user.setUsername("boss"); 37 | user.setPassword(passwordEncoder.encode("111111")); 38 | user.setName("老板"); 39 | user.setTel("147852369"); 40 | userDao.save(user); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/config/Swagger3Configuration.java: -------------------------------------------------------------------------------- 1 | //package com.linkedbear.boot.swagger.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.service.Contact; 10 | //import springfox.documentation.spi.DocumentationType; 11 | //import springfox.documentation.spring.web.plugins.Docket; 12 | // 13 | //@Configuration(proxyBeanMethods = false) 14 | //public class Swagger3Configuration { 15 | // 16 | // @Bean 17 | // public Docket createRestApi() { 18 | // return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()) 19 | // .select() 20 | // .apis(RequestHandlerSelectors.basePackage("com.linkedbear.boot.swagger")) 21 | // .paths(PathSelectors.any()).build(); 22 | // } 23 | // 24 | // private ApiInfo apiInfo() { 25 | // return new ApiInfoBuilder() 26 | // .title("SpringBoot自动集成Swagger3") 27 | // .description("test swagger document") 28 | // .contact(new Contact("LinkedBear", "https://github.com/LinkedBear", "")) 29 | // .version("1.0") 30 | // .build(); 31 | // } 32 | //} 33 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/config/Knife4jConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.swagger.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.RequestHandlerSelectors; 7 | import springfox.documentation.service.ApiInfo; 8 | import springfox.documentation.service.Contact; 9 | import springfox.documentation.spi.DocumentationType; 10 | import springfox.documentation.spring.web.plugins.Docket; 11 | import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; 12 | 13 | @Configuration(proxyBeanMethods = false) 14 | @EnableSwagger2WebMvc 15 | public class Knife4jConfiguration { 16 | 17 | @Bean 18 | public Docket docket() { 19 | return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) 20 | .select().apis(RequestHandlerSelectors.basePackage("com.linkedbear.boot.swagger")).build(); 21 | } 22 | 23 | private ApiInfo apiInfo() { 24 | return new ApiInfoBuilder() 25 | // 标题 26 | .title("SpringBoot集成Knife4j") 27 | // 接口描述 28 | .description("test swagger document") 29 | // 联系方式 30 | .contact(new Contact("LinkedBear", "https://github.com/LinkedBear", "")) 31 | // 版本信息 32 | .version("1.0") 33 | // 构建 34 | .build(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/controller/DemoController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.swagger.controller; 2 | 3 | import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; 4 | import com.github.xiaoymin.knife4j.annotations.ApiSupport; 5 | import com.linkedbear.boot.swagger.entity.User; 6 | import io.swagger.annotations.Api; 7 | import io.swagger.annotations.ApiOperation; 8 | import io.swagger.annotations.ApiParam; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @Api(tags = "这是一个测试接口类") 15 | @ApiSupport(author = "LinkedBear") 16 | public class DemoController { 17 | 18 | @GetMapping("/test") 19 | @ApiOperation(value = "这是一个测试的接口", notes = "仅供测试,切勿当真") 20 | @ApiOperationSupport(author = "LinkedBear", order = 100) 21 | public String test(@ApiParam(value = "测试姓名", defaultValue = "zhangsan", 22 | allowableValues = "zhangsan,lisi,wangwu", required = true) String name, 23 | @ApiParam(value = "测试年龄", allowableValues = "10, 20, 30, 40, 50", example = "10") Integer age) { 24 | System.out.println(name); 25 | System.out.println(age); 26 | return "test"; 27 | } 28 | 29 | @PostMapping(value = "/save") 30 | @ApiOperationSupport(author = "Baby", order = 1) 31 | public User save(User user) { 32 | System.out.println(user); 33 | return user; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-03-mybatis 14 | 15 | 16 | 17 | org.mybatis.spring.boot 18 | mybatis-spring-boot-starter 19 | 2.2.0 20 | 21 | 22 | mysql 23 | mysql-connector-java 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 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/resources/jwt_rsa: -------------------------------------------------------------------------------- 1 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDsudTnLQVDTqKW7DkfeIgedWQCKmhLdpTMXTQKGZfc/JARaW85JAJ0R7NXP2Moj6/Ni25Dpi5XKmlIB5GaDOPBAk/JK2KwnXhyOTkUFcgr/gaILABV/NhzYpVvwztNrOQBoqYaBQG7/iACQiqMOi126IYKAhuGs6XN7wRSLc1OX+HfBOvfmVcMj7kkzp2QB/IxCP/+HLmK7Znw9saEqmpnUO/d+o6chgVbQe2pGvRDTsBNSKXU5Uzi7beE7LcTRHk+XRYPoROWSjEcvDJZzEXamhaANCNXBNthOsvQrn2/i80MOCLWKpWmakiljTuOXOuISf7mGh6NXDkcsnL2d4YNAgMBAAECggEAd+ZfyX9qDP9FJsAa5q+78gFvWBF2pdI355LFiuAPpSRfLBKE/SIaBB9U3LoEVUUBvFAE10rSad/XV15OBwLEULwFAVVyNRZtLR2CpYOq0W1mjY4L1YGteDPUkLkHzn3lNlbVXpRunnNGbx5oQoItCO8ZBPSwUHepYTbQr3b3Z9v7IZ0t2pE8dd2oOzYeTO2KE5RepdQcwUR0uVZz+Vv0Tfuo2rN+vSi47o3yjQ8PbQH2aVrRxok3F43n51zik6yCdtdRJnAXSMWo6SfwZAGJVlW64gqjzE2o6qzMPj6c1I2FLKNzhZAlIZRjVBcWzL6gEV8G+zWXBvyaoeF4uOiWgQKBgQD+EorpUkiX2cXcO3kMQNEEkJWaUeS1gdZ+VE4eZ2OcbIGeOZ3lH9a7VQwMo6ZujU3skui9GpWAotXm0KMu4M4iJnzu+YP3mhnKXl9Asfvj1mZjSj5BYAlBcGI9NPPpi5ODsz3jFDK7sIQpBRe/m3rwvE/hVac50yhVzm2Q7rPc8QKBgQDuhZlHjDJKgPV3mMjySltqL6nf6QA0nKmMQit2J+uGcQX2HETlsvunr+9B2TCeupq8qITfcnzbCVgIEX3Cf1BlGou0KRd3UntSCaSzvfrCTAaHHS1RyPHnxSaNMlebcYqquJbKcl1ycvLnRwo/EdQjPWJ9fLtfCfsdBTfMXxZq3QKBgQDjhTdgOY9IbHwC/D8p+eEzdUaDK1LkN6Ec/+H02CEbsw9f4bjDtf9VQpPHvcUMuv1NHUHOFkBLMYbba3q2QBpX+p9mYYsL77OoxVoHVVt8bELEJ3gYkye2si1HImRKf/NZvOlusGe+LBQtp6HctB8j9X6TC2D1J2K3dGQppZjsAQKBgGuYMnOW51y6XYBMmGDLb/8vbwbFOUWCYe0WMDrFeTYVJ+ZEDEQ9f829zES873S6onB16DJPl8jKpz5EfaFOAvsIhXqIisBVobF5DiXSjho1Z0BtxfK9nXm6clCBJAnHpxCp4cOC4WpuNepkHlgi97nJx/LpYDBX9UG7B9eWESu1AoGAM0V9n0K0J9cVThwhNlNlfRS933RZkjVYZaKmNXcXDGCm6ZcZ8d2cljbkKlqwq25rYvxzk36UhXdHhuDid1CNye209hEGuBY4MNX7Bu3j2kK739z96Kn1Ind9Dy441fLoVjMCZniOOAD/C3igXE6ZS6lxGnbrfQvXWcEZlFwuzSI= -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-05-elasticsearch 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-data-elasticsearch 19 | 20 | 21 | 22 | org.projectlombok 23 | lombok 24 | true 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-maven-plugin 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import org.springframework.boot.json.JsonParseException; 6 | import org.springframework.util.StringUtils; 7 | 8 | import java.io.IOException; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | public abstract class JsonUtils { 13 | 14 | public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 15 | 16 | /** 17 | * json转Map 18 | * @param json 19 | * @return 20 | */ 21 | public static Map parseObject(String json) { 22 | if (StringUtils.hasText(json)) { 23 | return parseObject(json, Map.class); 24 | } 25 | return new HashMap<>(); 26 | } 27 | 28 | /** 29 | * json转指定类型 30 | * @param json 31 | * @param type 32 | * @param 33 | * @return 34 | */ 35 | public static T parseObject(String json, Class type) { 36 | try { 37 | return OBJECT_MAPPER.readValue(json, type); 38 | } catch (IOException e) { 39 | throw new JsonParseException(e); 40 | } 41 | } 42 | 43 | 44 | public static String toJson(Object obj) { 45 | if (obj == null) { 46 | return ""; 47 | } 48 | try { 49 | return OBJECT_MAPPER.writeValueAsString(obj); 50 | } catch (JsonProcessingException e) { 51 | throw new JsonParseException(e); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/service/AnnotationUserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.service; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import com.linkedbear.boot.cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.cache.annotation.CacheEvict; 7 | import org.springframework.cache.annotation.CachePut; 8 | import org.springframework.cache.annotation.Cacheable; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | @Service 14 | public class AnnotationUserService { 15 | 16 | @Autowired 17 | private UserMapper userMapper; 18 | 19 | // @Cacheable(value = "user.get", key = "#root.caches[0]") 20 | // @Cacheable(value = "user.get", keyGenerator = "userKeyGenerator") 21 | @Cacheable(value = "user.get", key = "#id", condition = "#id % 2 == 1", unless = "#result.name.contains('jpa')") 22 | public User get(Integer id) { 23 | return userMapper.get(id); 24 | } 25 | 26 | public List findAll() { 27 | return userMapper.findAll(); 28 | } 29 | 30 | public List findAllByName(String name) { 31 | return userMapper.findAllByNameLike(name); 32 | } 33 | 34 | @CachePut(value = "user.get", key = "#user.id") 35 | public User update(User user) { 36 | userMapper.updateById(user); 37 | return user; 38 | } 39 | 40 | @CacheEvict(value = "user.get", key = "#id") 41 | public void deleteById(Integer id) { 42 | // userMapper.deleteById(id); 43 | System.out.println("deleteById invoke ......"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /xxl-job-boot-starter/src/main/java/com/linkedbear/boot/xxljob/autoconfigure/XxlJobAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.xxljob.autoconfigure; 2 | 3 | import com.linkedbear.boot.xxljob.properties.XxlJobProperties; 4 | import com.xxl.job.core.executor.impl.XxlJobSpringExecutor; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration(proxyBeanMethods = false) 12 | @EnableConfigurationProperties(XxlJobProperties.class) 13 | public class XxlJobAutoConfiguration { 14 | 15 | @Autowired 16 | private XxlJobProperties properties; 17 | 18 | @Bean 19 | @ConditionalOnMissingBean 20 | public XxlJobSpringExecutor xxlJobExecutor() { 21 | XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); 22 | xxlJobSpringExecutor.setAdminAddresses(properties.getAdminAddresses()); 23 | xxlJobSpringExecutor.setAppname(properties.getAppname()); 24 | xxlJobSpringExecutor.setAddress(properties.getAddress()); 25 | xxlJobSpringExecutor.setIp(properties.getIp()); 26 | xxlJobSpringExecutor.setPort(properties.getPort()); 27 | xxlJobSpringExecutor.setAccessToken(properties.getAccessToken()); 28 | xxlJobSpringExecutor.setLogPath(properties.getLogPath()); 29 | xxlJobSpringExecutor.setLogRetentionDays(properties.getLogRetentionDays()); 30 | return xxlJobSpringExecutor; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-09-quartz 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-quartz 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-jdbc 29 | 30 | 31 | mysql 32 | mysql-connector-java 33 | 34 | 35 | 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-maven-plugin 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-08-rocketmq-producer 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.apache.rocketmq 23 | rocketmq-spring-boot-starter 24 | 2.2.2 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-jdbc 30 | 31 | 32 | mysql 33 | mysql-connector-java 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-maven-plugin 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/test/java/com/linkedbear/boot/elasticsearch/DataElasticSearchTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch; 2 | 3 | import com.linkedbear.boot.elasticsearch.dao.GraphicsCardRepository; 4 | import com.linkedbear.boot.elasticsearch.entity.GraphicsCard; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | @SpringBootTest 10 | public class DataElasticSearchTest { 11 | 12 | @Autowired 13 | private GraphicsCardRepository graphicsCardRepository; 14 | 15 | @Test 16 | public void test1() throws Exception { 17 | GraphicsCard graphicsCard = new GraphicsCard(); 18 | graphicsCard.setId(1); 19 | graphicsCard.setName("ROG 玩家国度-STRIX-RTX4090-O24G-GAMING"); 20 | graphicsCard.setBrand("ROG"); 21 | graphicsCard.setPrice(15999); 22 | graphicsCardRepository.save(graphicsCard); 23 | } 24 | 25 | @Test 26 | public void test2() throws Exception { 27 | GraphicsCard graphicsCard = new GraphicsCard(); 28 | graphicsCard.setId(2); 29 | graphicsCard.setName("七彩虹(Colorful)战斧GeForce RTX 4090 豪华版"); 30 | graphicsCard.setBrand("七彩虹"); 31 | graphicsCard.setPrice(12999); 32 | graphicsCardRepository.save(graphicsCard); 33 | } 34 | 35 | @Test 36 | public void test3() throws Exception { 37 | GraphicsCard graphicsCard = new GraphicsCard(); 38 | graphicsCard.setId(3); 39 | graphicsCard.setName("华硕 ASUS TUF-GeForce RTX 3080 Ti-O12G-GAMING"); 40 | graphicsCard.setBrand("华硕"); 41 | graphicsCard.setPrice(7999); 42 | graphicsCardRepository.save(graphicsCard); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/main/java/com/linkedbear/boot/cache/service/CachedUserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache.service; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import com.linkedbear.boot.cache.mapper.UserMapper; 5 | import org.springframework.beans.factory.InitializingBean; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.cache.Cache; 8 | import org.springframework.cache.CacheManager; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | @Service 14 | public class CachedUserService implements InitializingBean { 15 | 16 | @Autowired 17 | private UserMapper userMapper; 18 | 19 | @Autowired 20 | private CacheManager cacheManager; 21 | 22 | private Cache cache; 23 | 24 | @Override 25 | public void afterPropertiesSet() throws Exception { 26 | // this.cache = cacheManager.getCache("user"); 27 | } 28 | 29 | public User get(Integer id) { 30 | // 1. 通过CacheManager拿到名为user的缓存对象Cache 31 | Cache cache = cacheManager.getCache("user"); 32 | // 2. 从Cache中尝试获取一个指定id的User类型的对象 33 | User user = cache.get(id, User.class); 34 | // 3. 如果对象数据存在,则直接返回 35 | if (user != null) { 36 | return user; 37 | } 38 | // 4. 如果数据不存在,则需要查询数据库,并将查询的结果放入Cache中 39 | User userFromDatabase = userMapper.get(id); 40 | cache.put(id, userFromDatabase); 41 | return userFromDatabase; 42 | } 43 | 44 | public List findAll() { 45 | return userMapper.findAll(); 46 | } 47 | 48 | public List findAllByName(String name) { 49 | return cache.get(name, () -> userMapper.findAllByNameLike(name)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/main/java/com/linkedbear/boot/springdata/jpa/entity/Department.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata.jpa.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.Table; 8 | import java.util.Objects; 9 | 10 | @Entity 11 | @Table(name = "tbl_department") 12 | public class Department { 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Integer id; 17 | 18 | private String name; 19 | 20 | private String address; 21 | 22 | @Override 23 | public String toString() { 24 | return "Department{" + "id=" + id + ", name='" + name + '\'' + ", address='" + address + '\'' + '}'; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | if (this == o) 30 | return true; 31 | if (o == null || getClass() != o.getClass()) 32 | return false; 33 | Department that = (Department) o; 34 | return Objects.equals(id, that.id); 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | return Objects.hash(id); 40 | } 41 | 42 | public Integer getId() { 43 | return id; 44 | } 45 | 46 | public void setId(Integer id) { 47 | this.id = id; 48 | } 49 | 50 | public String getName() { 51 | return name; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | public String getAddress() { 59 | return address; 60 | } 61 | 62 | public void setAddress(String address) { 63 | this.address = address; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/main/java/com/linkedbear/boot/mybatisplus/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus.entity; 2 | 3 | import com.baomidou.mybatisplus.annotation.IdType; 4 | import com.baomidou.mybatisplus.annotation.TableId; 5 | import com.baomidou.mybatisplus.annotation.TableLogic; 6 | import com.baomidou.mybatisplus.annotation.TableName; 7 | import com.baomidou.mybatisplus.annotation.Version; 8 | 9 | @TableName("tbl_user") 10 | public class User { 11 | 12 | @TableId(type = IdType.AUTO) 13 | private Integer id; 14 | 15 | @Version 16 | private Integer version; 17 | 18 | private String name; 19 | 20 | private String tel; 21 | 22 | @TableLogic 23 | private Integer deleted; 24 | 25 | @Override 26 | public String toString() { 27 | return "User{" + "id=" + id + ", name='" + name + '\'' + ", tel='" + tel + '\'' + '}'; 28 | } 29 | 30 | public Integer getId() { 31 | return id; 32 | } 33 | 34 | public void setId(Integer id) { 35 | this.id = id; 36 | } 37 | 38 | public Integer getVersion() { 39 | return version; 40 | } 41 | 42 | public void setVersion(Integer version) { 43 | this.version = version; 44 | } 45 | 46 | public String getName() { 47 | return name; 48 | } 49 | 50 | public void setName(String name) { 51 | this.name = name; 52 | } 53 | 54 | public String getTel() { 55 | return tel; 56 | } 57 | 58 | public void setTel(String tel) { 59 | this.tel = tel; 60 | } 61 | 62 | public Integer getDeleted() { 63 | return deleted; 64 | } 65 | 66 | public void setDeleted(Integer deleted) { 67 | this.deleted = deleted; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/service/TransactionalStatusChecker.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; 4 | import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; 5 | import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.messaging.Message; 8 | 9 | import java.nio.charset.StandardCharsets; 10 | 11 | @RocketMQTransactionListener 12 | public class TransactionalStatusChecker implements RocketMQLocalTransactionListener { 13 | 14 | @Autowired 15 | private DataService dataService; 16 | 17 | @Override 18 | public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { 19 | String payload = new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8); 20 | System.out.println(payload); 21 | System.out.println(arg); 22 | 23 | RocketMQLocalTransactionState state = RocketMQLocalTransactionState.COMMIT; 24 | try { 25 | dataService.saveData(payload, msg.getHeaders().get("txId", String.class)); 26 | } catch (Exception e) { 27 | state = RocketMQLocalTransactionState.UNKNOWN; 28 | } 29 | return state; 30 | } 31 | 32 | @Override 33 | public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { 34 | System.out.println(new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8)); 35 | return dataService.contains(msg.getHeaders().get("txId", String.class)) 36 | ? RocketMQLocalTransactionState.COMMIT 37 | : RocketMQLocalTransactionState.ROLLBACK; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-integration-09-xxljob/src/main/java/com/linkedbear/boot/xxljob/config/XxlJobConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.xxljob.config; 2 | 3 | import com.xxl.job.core.executor.impl.XxlJobSpringExecutor; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | @Configuration(proxyBeanMethods = false) 9 | public class XxlJobConfiguration { 10 | 11 | @Value("${xxl.job.admin.addresses}") 12 | private String adminAddresses; 13 | 14 | @Value("${xxl.job.accessToken:}") 15 | private String accessToken; 16 | 17 | @Value("${xxl.job.executor.appname}") 18 | private String appname; 19 | 20 | @Value("${xxl.job.executor.address:}") 21 | private String address; 22 | 23 | @Value("${xxl.job.executor.ip:}") 24 | private String ip; 25 | 26 | @Value("${xxl.job.executor.port:9999}") 27 | private int port; 28 | 29 | @Value("${xxl.job.executor.logpath:}") 30 | private String logPath; 31 | 32 | @Value("${xxl.job.executor.logretentiondays:30}") 33 | private int logRetentionDays; 34 | 35 | @Bean 36 | public XxlJobSpringExecutor xxlJobExecutor() { 37 | XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); 38 | xxlJobSpringExecutor.setAdminAddresses(adminAddresses); 39 | xxlJobSpringExecutor.setAppname(appname); 40 | xxlJobSpringExecutor.setAddress(address); 41 | xxlJobSpringExecutor.setIp(ip); 42 | xxlJobSpringExecutor.setPort(port); 43 | xxlJobSpringExecutor.setAccessToken(accessToken); 44 | xxlJobSpringExecutor.setLogPath(logPath); 45 | xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays); 46 | return xxlJobSpringExecutor; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/service/DataUpdateTransactionalStatusChecker.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.service; 2 | 3 | import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; 4 | import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; 5 | import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.messaging.Message; 8 | 9 | import java.nio.charset.StandardCharsets; 10 | 11 | @RocketMQTransactionListener(rocketMQTemplateBeanName = "dataUpdateRocketMQTemplate") 12 | public class DataUpdateTransactionalStatusChecker implements RocketMQLocalTransactionListener { 13 | 14 | @Autowired 15 | private DataService dataService; 16 | 17 | @Override 18 | public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { 19 | String payload = new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8); 20 | System.out.println(payload); 21 | System.out.println(arg); 22 | 23 | RocketMQLocalTransactionState state = RocketMQLocalTransactionState.COMMIT; 24 | try { 25 | dataService.updateData(msg.getHeaders().get("txId", String.class)); 26 | } catch (Exception e) { 27 | state = RocketMQLocalTransactionState.UNKNOWN; 28 | } 29 | return state; 30 | } 31 | 32 | @Override 33 | public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { 34 | System.out.println(new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8)); 35 | return dataService.contains(msg.getHeaders().get("txId", String.class)) 36 | ? RocketMQLocalTransactionState.COMMIT 37 | : RocketMQLocalTransactionState.ROLLBACK; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/java/com/linkedbear/boot/j2cache/service/CachedUserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache.service; 2 | 3 | import com.linkedbear.boot.j2cache.entity.User; 4 | import com.linkedbear.boot.j2cache.mapper.UserMapper; 5 | import net.oschina.j2cache.CacheChannel; 6 | import net.oschina.j2cache.CacheObject; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.cache.annotation.CacheEvict; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | @Service 14 | public class CachedUserService { 15 | 16 | @Autowired 17 | private CacheChannel cacheChannel; 18 | 19 | @Autowired 20 | private UserMapper userMapper; 21 | 22 | public User get(Integer id) { 23 | String cacheKey = "getUser." + id; 24 | CacheObject cacheObject = cacheChannel.get("default", cacheKey); 25 | if (cacheObject.getValue() != null) { 26 | return (User) cacheObject.getValue(); 27 | } 28 | User user = userMapper.get(id); 29 | cacheChannel.set("default", cacheKey, user); 30 | return user; 31 | } 32 | 33 | public List findAll() { 34 | return userMapper.findAll(); 35 | } 36 | 37 | public List findAllByName(String name) { 38 | return userMapper.findAllByNameLike(name); 39 | } 40 | 41 | public User update(User user) { 42 | userMapper.updateById(user); 43 | String cacheKey = "getUser." + user.getId(); 44 | cacheChannel.set("default", cacheKey, user); 45 | return user; 46 | } 47 | 48 | public void deleteById(Integer id) { 49 | // userMapper.deleteById(id); 50 | System.out.println("deleteById invoke ......"); 51 | String cacheKey = "getUser." + id; 52 | cacheChannel.evict("default", cacheKey); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-03-mybatisplus 14 | 15 | 16 | 17 | com.baomidou 18 | mybatis-plus-boot-starter 19 | 3.5.0 20 | 21 | 22 | mysql 23 | mysql-connector-java 24 | 25 | 26 | 27 | com.baomidou 28 | mybatis-plus-generator 29 | 3.5.2 30 | 31 | 32 | 33 | org.freemarker 34 | freemarker 35 | 2.3.31 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.service; 2 | 3 | import com.linkedbear.boot.security.dao.UserDao; 4 | import com.linkedbear.boot.security.entity.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.util.StringUtils; 12 | 13 | import java.util.List; 14 | 15 | @Service 16 | public class UserService implements UserDetailsService { 17 | 18 | @Autowired 19 | private UserDao userDao; 20 | 21 | @Override 22 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 23 | List users = userDao.findAllByUsername(username); 24 | if (users.isEmpty()) { 25 | throw new UsernameNotFoundException("用户名" + username + "不存在!"); 26 | } 27 | User user = users.get(0); 28 | org.springframework.security.core.userdetails.User.UserBuilder userBuilder = org.springframework.security.core.userdetails.User 29 | .withUsername(user.getUsername()).password(user.getPassword()); 30 | if (StringUtils.hasText(user.getRoles())) { 31 | userBuilder = userBuilder.roles(user.getRoles().split(",")); 32 | } 33 | if (StringUtils.hasText(user.getResources())) { 34 | userBuilder = userBuilder.authorities(user.getResources().split(",")); 35 | } 36 | return userBuilder.build(); 37 | } 38 | 39 | @PreAuthorize("hasAuthority('getUser')") 40 | public User get(Integer id) { 41 | System.out.println("进入UserService的get方法!"); 42 | return userDao.getById(id); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-11-actuator 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-actuator 24 | 25 | 26 | 32 | 33 | 40 | 41 | 42 | de.codecentric 43 | spring-boot-admin-starter-client 44 | 2.5.6 45 | 46 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-maven-plugin 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /spring-boot-integration-11-actuator/src/main/java/com/linkedbear/boot/actuator/health/XxlJobHealthIndicator.java: -------------------------------------------------------------------------------- 1 | //package com.linkedbear.boot.actuator.health; 2 | // 3 | //import com.linkedbear.boot.xxljob.properties.XxlJobProperties; 4 | //import com.xxl.job.core.biz.AdminBiz; 5 | //import com.xxl.job.core.biz.client.AdminBizClient; 6 | //import com.xxl.job.core.biz.model.RegistryParam; 7 | //import com.xxl.job.core.biz.model.ReturnT; 8 | //import com.xxl.job.core.enums.RegistryConfig; 9 | //import com.xxl.job.core.executor.XxlJobExecutor; 10 | //import org.springframework.beans.factory.annotation.Autowired; 11 | //import org.springframework.boot.actuate.health.AbstractHealthIndicator; 12 | //import org.springframework.boot.actuate.health.Health; 13 | //import org.springframework.stereotype.Component; 14 | //import org.springframework.util.ReflectionUtils; 15 | // 16 | //import java.lang.reflect.Field; 17 | //import java.util.List; 18 | // 19 | //@Component 20 | //public class XxlJobHealthIndicator extends AbstractHealthIndicator { 21 | // 22 | // @Autowired 23 | // private XxlJobProperties prop; 24 | // 25 | // @Override 26 | // protected void doHealthCheck(Health.Builder builder) throws Exception { 27 | // RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), prop.getAppname(), 28 | // prop.getAddress()); 29 | // 30 | // List adminBizList = XxlJobExecutor.getAdminBizList(); 31 | // for (AdminBiz adminBiz : adminBizList) { 32 | // ReturnT ret = adminBiz.registry(registryParam); 33 | // if (ret == null || ReturnT.SUCCESS_CODE != ret.getCode()) { 34 | // builder.down(); 35 | // Field field = ReflectionUtils.findField(AdminBizClient.class, "addressUrl"); 36 | // ReflectionUtils.makeAccessible(field); 37 | // String addressUrl = (String) ReflectionUtils.getField(field, adminBiz); 38 | // builder.withDetail("errorAdminServer", addressUrl); 39 | // return; 40 | // } 41 | // } 42 | // builder.up(); 43 | // } 44 | //} 45 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-10-swagger 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 33 | 34 | 41 | 42 | 43 | com.github.xiaoymin 44 | knife4j-spring-boot-starter 45 | 2.0.9 46 | 47 | 49 | 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-maven-plugin 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /spring-boot-integration-10-swagger/src/main/java/com/linkedbear/boot/swagger/config/Swagger2Configuration.java: -------------------------------------------------------------------------------- 1 | //package com.linkedbear.boot.swagger.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.service.Contact; 10 | //import springfox.documentation.spi.DocumentationType; 11 | //import springfox.documentation.spring.web.plugins.Docket; 12 | //import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 | // 14 | //@Configuration(proxyBeanMethods = false) 15 | //@EnableSwagger2 16 | //public class Swagger2Configuration { 17 | // 18 | // @Bean 19 | // public Docket createRestApi() { 20 | // return new Docket(DocumentationType.SWAGGER_2) 21 | // // 指定构建api文档的详细信息的方法:apiInfo() 22 | // .apiInfo(apiInfo()) 23 | // .select() 24 | // // 指定要生成api接口的包路径 25 | // .apis(RequestHandlerSelectors.basePackage("com.linkedbear.boot.swagger")) 26 | // //使用了 @ApiOperation 注解的方法生成api接口文档 27 | // //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 28 | // .paths(PathSelectors.any()) 29 | // //可以根据url路径设置哪些请求加入文档,忽略哪些请求 30 | // .build(); 31 | // } 32 | // 33 | // /** 34 | // * 设置api文档的详细信息 35 | // */ 36 | // private ApiInfo apiInfo() { 37 | // return new ApiInfoBuilder() 38 | // // 标题 39 | // .title("SpringBoot手动集成Swagger2") 40 | // // 接口描述 41 | // .description("test swagger document") 42 | // // 联系方式 43 | // .contact(new Contact("LinkedBear", "https://github.com/LinkedBear", "")) 44 | // // 版本信息 45 | // .version("1.0") 46 | // // 构建 47 | // .build(); 48 | // } 49 | //} 50 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/controller/MessageController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.controller; 2 | 3 | import com.linkedbear.boot.rocketmq.producer.service.MessageSender; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | public class MessageController { 10 | 11 | @Autowired 12 | private MessageSender messageSender; 13 | 14 | @GetMapping("/sendMessage") 15 | public String sendMessage() { 16 | messageSender.sendMessage(); 17 | //messageSender.sendOneway(); 18 | return "success"; 19 | } 20 | 21 | @GetMapping("/asyncSend") 22 | public String asyncSend() { 23 | messageSender.asyncSend(); 24 | return "success"; 25 | } 26 | 27 | @GetMapping("/sendTagsMessage") 28 | public String sendTagsMessage() { 29 | messageSender.sendTagsMessage(); 30 | return "success"; 31 | } 32 | 33 | @GetMapping("/sendDto") 34 | public String sendDto() { 35 | messageSender.sendDto(); 36 | return "success"; 37 | } 38 | 39 | @GetMapping("/sendDelayMessage") 40 | public String sendDelayMessage() { 41 | messageSender.sendDelayMessage(); 42 | return "success"; 43 | } 44 | 45 | @GetMapping("/sendTransactionalMessage") 46 | public String sendTransactionalMessage() { 47 | messageSender.sendTransactionalMessage(); 48 | return "success"; 49 | } 50 | 51 | @GetMapping("/sendUpdateTransactionalMessage") 52 | public String sendUpdateTransactionalMessage() { 53 | messageSender.sendUpdateTransactionalMessage(); 54 | return "success"; 55 | } 56 | 57 | @GetMapping("/send10Message") 58 | public String send10Message() { 59 | messageSender.send10Message(); 60 | return "success"; 61 | } 62 | @GetMapping("/sendOrderedMessage") 63 | public String sendOrderedMessage() { 64 | messageSender.sendOrderedMessage(); 65 | return "success"; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/src/test/java/com/linkedbear/boot/cache/CacheTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.cache; 2 | 3 | import com.linkedbear.boot.cache.entity.User; 4 | import com.linkedbear.boot.cache.service.AnnotationUserService; 5 | import com.linkedbear.boot.cache.service.CachedUserService; 6 | import com.linkedbear.boot.cache.service.UserService; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | @SpringBootTest 12 | public class CacheTest { 13 | 14 | @Autowired 15 | private UserService userService; 16 | 17 | @Autowired 18 | private CachedUserService cachedUserService; 19 | 20 | @Autowired 21 | private AnnotationUserService annotationUserService; 22 | 23 | @Test 24 | public void test1() throws Exception { 25 | System.out.println(userService.findAll()); 26 | User user1 = userService.get(1); 27 | User user2 = userService.get(1); 28 | System.out.println(user1 == user2); 29 | } 30 | 31 | @Test 32 | public void test2() throws Exception { 33 | User user1 = cachedUserService.get(1); 34 | User user2 = cachedUserService.get(1); 35 | System.out.println(user1); 36 | System.out.println(user1 == user2); 37 | } 38 | 39 | @Test 40 | public void test3() throws Exception { 41 | User user1 = annotationUserService.get(6); 42 | User user2 = annotationUserService.get(6); 43 | System.out.println(user1 == user2); 44 | } 45 | 46 | @Test 47 | public void test4() throws Exception { 48 | User user = annotationUserService.get(1); 49 | user.setName("mybatis test"); 50 | annotationUserService.update(user); 51 | User user2 = annotationUserService.get(1); 52 | System.out.println(user == user2); 53 | } 54 | 55 | @Test 56 | public void test5() throws Exception { 57 | User user1 = annotationUserService.get(1); 58 | User user2 = annotationUserService.get(1); 59 | annotationUserService.deleteById(1); 60 | User user3 = annotationUserService.get(1); 61 | System.out.println(user1 == user3); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/filter/ResourceAuthorizationFilter.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.filter; 2 | 3 | import com.linkedbear.boot.security.dao.ResourceDao; 4 | import com.linkedbear.boot.security.entity.Resource; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.AccessDeniedException; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.context.SecurityContextHolder; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.stereotype.Component; 11 | 12 | import javax.servlet.Filter; 13 | import javax.servlet.FilterChain; 14 | import javax.servlet.ServletException; 15 | import javax.servlet.ServletRequest; 16 | import javax.servlet.ServletResponse; 17 | import javax.servlet.http.HttpServletRequest; 18 | import java.io.IOException; 19 | import java.util.List; 20 | import java.util.stream.Collectors; 21 | 22 | @Component 23 | public class ResourceAuthorizationFilter implements Filter { 24 | 25 | @Autowired 26 | private ResourceDao resourceDao; 27 | 28 | @Override 29 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 30 | throws IOException, ServletException { 31 | // 在继续向后调用过滤器链之前,连接数据库判断是否当前登录人是否允许访问 32 | HttpServletRequest req = (HttpServletRequest) request; 33 | String uri = req.getRequestURI(); 34 | // 首先判断当前请求是否在限制访问的列表中 35 | List resources = resourceDao.findAll().stream().map(Resource::getPermission).collect(Collectors.toList()); 36 | if (!resources.contains(uri)) { 37 | chain.doFilter(request, response); 38 | return; 39 | } 40 | // 在限制访问的列表中,需要鉴权 41 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 42 | UserDetails userDetails = (UserDetails) authentication.getPrincipal(); 43 | if (userDetails.getAuthorities().stream().anyMatch(i -> i.getAuthority().equals(uri))) { 44 | chain.doFilter(request, response); 45 | return; 46 | } 47 | throw new AccessDeniedException("权限不足"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /xxl-job-boot-starter/src/main/java/com/linkedbear/boot/xxljob/properties/XxlJobProperties.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.xxljob.properties; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | @ConfigurationProperties(prefix = "xxl.job") 7 | public class XxlJobProperties { 8 | 9 | private String adminAddresses; 10 | 11 | private String accessToken = "default_token"; 12 | 13 | private String appname; 14 | 15 | private String address; 16 | 17 | private String ip; 18 | 19 | private int port = 9999; 20 | 21 | private String logPath; 22 | 23 | private int logRetentionDays = 30; 24 | 25 | public String getAdminAddresses() { 26 | return adminAddresses; 27 | } 28 | 29 | public void setAdminAddresses(String adminAddresses) { 30 | this.adminAddresses = adminAddresses; 31 | } 32 | 33 | public String getAccessToken() { 34 | return accessToken; 35 | } 36 | 37 | public void setAccessToken(String accessToken) { 38 | this.accessToken = accessToken; 39 | } 40 | 41 | public String getAppname() { 42 | return appname; 43 | } 44 | 45 | public void setAppname(String appname) { 46 | this.appname = appname; 47 | } 48 | 49 | public String getAddress() { 50 | return address; 51 | } 52 | 53 | public void setAddress(String address) { 54 | this.address = address; 55 | } 56 | 57 | public String getIp() { 58 | return ip; 59 | } 60 | 61 | public void setIp(String ip) { 62 | this.ip = ip; 63 | } 64 | 65 | public int getPort() { 66 | return port; 67 | } 68 | 69 | public void setPort(int port) { 70 | this.port = port; 71 | } 72 | 73 | public String getLogPath() { 74 | return logPath; 75 | } 76 | 77 | public void setLogPath(String logPath) { 78 | this.logPath = logPath; 79 | } 80 | 81 | public int getLogRetentionDays() { 82 | return logRetentionDays; 83 | } 84 | 85 | public void setLogRetentionDays(int logRetentionDays) { 86 | this.logRetentionDays = logRetentionDays; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-04-springdata 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-data-jpa 19 | 20 | 21 | mysql 22 | mysql-connector-java 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-data-redis 28 | 36 | 37 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-data-mongodb 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-maven-plugin 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/test/java/com/linkedbear/boot/j2cache/J2cacheTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.j2cache; 2 | 3 | import com.linkedbear.boot.j2cache.entity.User; 4 | import com.linkedbear.boot.j2cache.service.AnnotationUserService; 5 | import com.linkedbear.boot.j2cache.service.CachedUserService; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.BeanUtils; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | @SpringBootTest 12 | public class J2cacheTest { 13 | 14 | @Autowired 15 | private CachedUserService userService; 16 | 17 | @Test 18 | public void test1() throws Exception { 19 | userService.get(1); 20 | userService.get(1); 21 | userService.get(1); 22 | } 23 | 24 | @Test 25 | public void test2() throws Exception { 26 | User user = userService.get(1); 27 | // 使用临时对象,防止有误解 28 | User temp = new User(); 29 | BeanUtils.copyProperties(user, temp); 30 | temp.setName(temp.getName() + "-j2cache"); 31 | userService.update(temp); 32 | User user1 = userService.get(1); 33 | System.out.println(user == user1); 34 | System.out.println(temp == user1); 35 | } 36 | 37 | @Test 38 | public void test3() throws Exception { 39 | User user = userService.get(1); 40 | userService.deleteById(1); 41 | User user1 = userService.get(1); 42 | System.out.println(user == user1); 43 | } 44 | 45 | @Autowired 46 | private AnnotationUserService annotationUserService; 47 | 48 | @Test 49 | public void test4() throws Exception { 50 | User user1 = annotationUserService.get(6); 51 | User user2 = annotationUserService.get(6); 52 | System.out.println(user1 == user2); 53 | } 54 | 55 | @Test 56 | public void test5() throws Exception { 57 | User user = annotationUserService.get(1); 58 | user.setName("mybatis test j2cache"); 59 | annotationUserService.update(user); 60 | User user2 = annotationUserService.get(1); 61 | System.out.println(user == user2); 62 | } 63 | 64 | @Test 65 | public void test6() throws Exception { 66 | User user1 = annotationUserService.get(1); 67 | User user2 = annotationUserService.get(1); 68 | annotationUserService.deleteById(1); 69 | User user3 = annotationUserService.get(1); 70 | System.out.println(user1 == user3); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-07-security-webmvc 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-web 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-security 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-jpa 29 | 30 | 31 | mysql 32 | mysql-connector-java 33 | 34 | 35 | 36 | 37 | io.jsonwebtoken 38 | jjwt-api 39 | 0.11.5 40 | 41 | 42 | io.jsonwebtoken 43 | jjwt-impl 44 | 0.11.5 45 | 46 | 47 | io.jsonwebtoken 48 | jjwt-jackson 49 | 0.11.5 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-maven-plugin 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /spring-boot-integration-06-cache/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-06-j2cache 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter 19 | 20 | 21 | 22 | net.oschina.j2cache 23 | j2cache-spring-boot2-starter 24 | 2.8.0-release 25 | 26 | 27 | net.oschina.j2cache 28 | j2cache-core 29 | 2.8.5-release 30 | 31 | 32 | 33 | org.mybatis.spring.boot 34 | mybatis-spring-boot-starter 35 | 2.2.0 36 | 37 | 38 | mysql 39 | mysql-connector-java 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-cache 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-data-redis 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-maven-plugin 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-boot-integration-parent 7 | com.linkedbear.boot 8 | 1.0.0-RELEASE 9 | ../spring-boot-integration-parent/pom.xml 10 | 11 | 4.0.0 12 | 13 | spring-boot-integration-06-j2cache 14 | 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter 19 | 20 | 21 | 22 | net.oschina.j2cache 23 | j2cache-spring-boot2-starter 24 | 2.8.0-release 25 | 26 | 27 | net.oschina.j2cache 28 | j2cache-core 29 | 2.8.5-release 30 | 31 | 32 | 33 | org.mybatis.spring.boot 34 | mybatis-spring-boot-starter 35 | 2.2.0 36 | 37 | 38 | mysql 39 | mysql-connector-java 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-cache 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-data-redis 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-maven-plugin 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /spring-boot-integration-03-mybatisplus/src/test/java/com/linkedbear/boot/mybatisplus/MyBatisPlusTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.mybatisplus; 2 | 3 | import com.baomidou.mybatisplus.core.toolkit.Wrappers; 4 | import com.linkedbear.boot.mybatisplus.entity.User; 5 | import com.linkedbear.boot.mybatisplus.mapper.UserMapper; 6 | import com.linkedbear.boot.mybatisplus.service.UserService; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.util.StringUtils; 11 | 12 | import java.util.List; 13 | 14 | @SpringBootTest 15 | public class MyBatisPlusTest { 16 | 17 | @Autowired 18 | private UserMapper userMapper; 19 | 20 | @Autowired 21 | private UserService userService; 22 | 23 | @Test 24 | public void test1() { 25 | userService.test(); 26 | } 27 | 28 | @Test 29 | public void test2() { 30 | userMapper.selectList(null).forEach(System.out::println); 31 | System.out.println("=================="); 32 | userService.list().forEach(System.out::println); 33 | System.out.println(userService.count()); 34 | } 35 | 36 | @Test 37 | public void test3() throws Exception { 38 | List users = userMapper.selectList(Wrappers.query().like("tel", "123")); 39 | users.forEach(System.out::println); 40 | } 41 | 42 | @Test 43 | public void test4() throws Exception { 44 | List users = userMapper.selectList(Wrappers.lambdaQuery(User.class).eq(User::getTel, "7654321")); 45 | users.forEach(System.out::println); 46 | } 47 | 48 | @Test 49 | public void test5() throws Exception { 50 | List users = userMapper.selectList(Wrappers.lambdaQuery(User.class).select(User::getName)); 51 | users.forEach(System.out::println); 52 | } 53 | 54 | @Test 55 | public void test6() throws Exception { 56 | User user = userMapper.selectOne(Wrappers.query().select("max(id) as id")); 57 | System.out.println(user); 58 | } 59 | 60 | @Test 61 | public void test7() throws Exception { 62 | User qo = new User(); 63 | 64 | List users = userMapper.selectList( 65 | Wrappers.lambdaQuery(User.class).like(StringUtils.hasText(qo.getName()), User::getName, qo.getName())); 66 | System.out.println(users.size()); 67 | 68 | qo.setName("mybatisplus"); 69 | users = userMapper.selectList( 70 | Wrappers.lambdaQuery(User.class).like(StringUtils.hasText(qo.getName()), User::getName, qo.getName())); 71 | System.out.println(users.size()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/test/java/demo/TestingAStackDemo.java: -------------------------------------------------------------------------------- 1 | package demo; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | import java.util.EmptyStackException; 9 | import java.util.Stack; 10 | 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.DisplayName; 13 | import org.junit.jupiter.api.Nested; 14 | import org.junit.jupiter.api.Test; 15 | 16 | @DisplayName("A stack") 17 | class TestingAStackDemo { 18 | 19 | Stack stack; 20 | 21 | @Test 22 | @DisplayName("is instantiated with new Stack()") 23 | void isInstantiatedWithNew() { 24 | new Stack<>(); 25 | } 26 | 27 | @Nested 28 | @DisplayName("when new") 29 | class WhenNew { 30 | 31 | @BeforeEach 32 | void createNewStack() { 33 | stack = new Stack<>(); 34 | } 35 | 36 | @Test 37 | @DisplayName("is empty") 38 | void isEmpty() { 39 | assertTrue(stack.isEmpty()); 40 | } 41 | 42 | @Test 43 | @DisplayName("throws EmptyStackException when popped") 44 | void throwsExceptionWhenPopped() { 45 | assertThrows(EmptyStackException.class, () -> stack.pop()); 46 | } 47 | 48 | @Test 49 | @DisplayName("throws EmptyStackException when peeked") 50 | void throwsExceptionWhenPeeked() { 51 | assertThrows(EmptyStackException.class, () -> stack.peek()); 52 | } 53 | 54 | @Nested 55 | @DisplayName("after pushing an element") 56 | class AfterPushing { 57 | 58 | String anElement = "an element"; 59 | 60 | @BeforeEach 61 | void pushAnElement() { 62 | stack.push(anElement); 63 | } 64 | 65 | @Test 66 | @DisplayName("it is no longer empty") 67 | void isNotEmpty() { 68 | assertFalse(stack.isEmpty()); 69 | } 70 | 71 | @Test 72 | @DisplayName("returns the element when popped and is empty") 73 | void returnElementWhenPopped() { 74 | assertEquals(anElement, stack.pop()); 75 | assertTrue(stack.isEmpty()); 76 | } 77 | 78 | @Test 79 | @DisplayName("returns the element when peeked but remains not empty") 80 | void returnElementWhenPeeked() { 81 | assertEquals(anElement, stack.peek()); 82 | assertFalse(stack.isEmpty()); 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/RefreshTokenController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import com.linkedbear.boot.security.entity.SecurityUser; 4 | import io.jsonwebtoken.ExpiredJwtException; 5 | import io.jsonwebtoken.JwtException; 6 | import org.springframework.util.StringUtils; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | import java.security.PrivateKey; 14 | import java.security.PublicKey; 15 | 16 | /** 17 | * 基于WebMvc的jwt访问令牌刷新 18 | */ 19 | @RestController 20 | public class RefreshTokenController { 21 | 22 | public static final String REFRESH_HEADER = "refreshtoken"; 23 | 24 | private PrivateKey privateKey; 25 | private PublicKey publicKey; 26 | 27 | public RefreshTokenController() { 28 | this.privateKey = RsaUtils.getPrivateKey("jwt_rsa"); 29 | this.publicKey = RsaUtils.getPublicKey("jwt_rsa.pub"); 30 | } 31 | 32 | @PostMapping("/refreshToken") 33 | public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException { 34 | String refreshJwt = request.getHeader(REFRESH_HEADER); 35 | if (!StringUtils.hasText(refreshJwt)) { 36 | response.setContentType("application/json;charset=utf-8"); 37 | response.getWriter().write("没有携带刷新令牌!"); 38 | response.getWriter().flush(); 39 | response.getWriter().close(); 40 | } 41 | // 解析刷新jwt令牌 42 | try { 43 | String payloadEncodedJson = JwtUtils.getTokenPayload(refreshJwt, publicKey); 44 | String userTokenJson = JwtUtils.decodeRefreshToken(payloadEncodedJson); 45 | SecurityUser user = JsonUtils.parseObject(userTokenJson, SecurityUser.class); 46 | JwtUtils.writeJwtToken(response, user, privateKey, 30, 3600); 47 | response.setContentType("application/json;charset=utf-8"); 48 | response.getWriter().write("刷新成功!"); 49 | response.getWriter().flush(); 50 | response.getWriter().close(); 51 | } catch (ExpiredJwtException e) { 52 | response.setContentType("application/json;charset=utf-8"); 53 | response.getWriter().write("刷新令牌已过期!"); 54 | response.getWriter().flush(); 55 | response.getWriter().close(); 56 | } catch (JwtException e) { 57 | response.setContentType("application/json;charset=utf-8"); 58 | response.getWriter().write("刷新令牌解析失败!"); 59 | response.getWriter().flush(); 60 | response.getWriter().close(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/JwtTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import io.jsonwebtoken.ExpiredJwtException; 4 | import io.jsonwebtoken.JwtException; 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.security.core.context.SecurityContextImpl; 8 | import org.springframework.security.core.userdetails.User; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.util.StringUtils; 11 | 12 | import javax.servlet.Filter; 13 | import javax.servlet.FilterChain; 14 | import javax.servlet.ServletException; 15 | import javax.servlet.ServletRequest; 16 | import javax.servlet.ServletResponse; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | import java.io.IOException; 20 | import java.security.PublicKey; 21 | 22 | @Component 23 | public class JwtTokenFilter implements Filter { 24 | 25 | private PublicKey publicKey; 26 | 27 | public JwtTokenFilter() { 28 | this.publicKey = RsaUtils.getPublicKey("jwt_rsa.pub"); 29 | } 30 | 31 | @Override 32 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 33 | throws IOException, ServletException { 34 | HttpServletRequest req = (HttpServletRequest) request; 35 | try { 36 | // 解析jwt令牌 37 | String jwt = req.getHeader(JwtUtils.JWT_HEADER); 38 | // 忽略oauth2.0的Bearer令牌 39 | if (StringUtils.hasText(jwt) && !jwt.startsWith("Bearer")) { 40 | TokenPayload payload = JwtUtils.parseToken(jwt, publicKey); 41 | User user = payload.getUser(); 42 | 43 | SecurityContextHolder.setContext(new SecurityContextImpl( 44 | new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()))); 45 | } else { 46 | SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); 47 | } 48 | chain.doFilter(request, response); 49 | } catch (ExpiredJwtException e) { 50 | response.setContentType("application/json;charset=utf-8"); 51 | response.getWriter().write("jwt令牌已过期!"); 52 | response.getWriter().flush(); 53 | response.getWriter().close(); 54 | } catch (JwtException e) { 55 | response.setContentType("application/json;charset=utf-8"); 56 | response.getWriter().write("解析jwt令牌失败!"); 57 | response.getWriter().flush(); 58 | response.getWriter().close(); 59 | } finally { 60 | SecurityContextHolder.clearContext(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.Table; 8 | 9 | @Entity 10 | @Table(name = "sys_user") 11 | public class User { 12 | 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Integer id; 16 | 17 | private String username; 18 | 19 | private String password; 20 | 21 | private String name; 22 | 23 | private String tel; 24 | 25 | private String roles; 26 | 27 | private String resources; 28 | 29 | @Override 30 | public String toString() { 31 | return "User{" 32 | + "id=" 33 | + id 34 | + ", username='" 35 | + username 36 | + '\'' 37 | + ", password='" 38 | + password 39 | + '\'' 40 | + ", name='" 41 | + name 42 | + '\'' 43 | + ", tel='" 44 | + tel 45 | + '\'' 46 | + ", roles='" 47 | + roles 48 | + '\'' 49 | + ", resources='" 50 | + resources 51 | + '\'' 52 | + '}'; 53 | } 54 | 55 | public Integer getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Integer id) { 60 | this.id = id; 61 | } 62 | 63 | public String getUsername() { 64 | return username; 65 | } 66 | 67 | public void setUsername(String username) { 68 | this.username = username; 69 | } 70 | 71 | public String getPassword() { 72 | return password; 73 | } 74 | 75 | public void setPassword(String password) { 76 | this.password = password; 77 | } 78 | 79 | public String getName() { 80 | return name; 81 | } 82 | 83 | public void setName(String name) { 84 | this.name = name; 85 | } 86 | 87 | public String getTel() { 88 | return tel; 89 | } 90 | 91 | public void setTel(String tel) { 92 | this.tel = tel; 93 | } 94 | 95 | public String getRoles() { 96 | return roles; 97 | } 98 | 99 | public void setRoles(String roles) { 100 | this.roles = roles; 101 | } 102 | 103 | public String getResources() { 104 | return resources; 105 | } 106 | 107 | public void setResources(String resources) { 108 | this.resources = resources; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /spring-boot-integration-06-j2cache/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/sringboot-dao?characterEncoding=utf8 3 | spring.datasource.username=root 4 | spring.datasource.password=123456 5 | 6 | mybatis.type-aliases-package=com.linkedbear.boot.j2cache.entity 7 | mybatis.mapper-locations=classpath:mapper/*.xml 8 | mybatis.configuration.map-underscore-to-camel-case=true 9 | 10 | logging.level.com.linkedbear.boot.j2cache.mapper.UserMapper=debug 11 | 12 | # \u4E00\u7EA7\u7F13\u5B58\u7684\u63D0\u4F9B\u65B9\uFF0C\u53EF\u9009\u62E9caffeine/ehcache 13 | j2cache.L1.provider_class=caffeine 14 | # \u4E8C\u7EA7\u7F13\u5B58\u7684\u63D0\u4F9B\u65B9\uFF0C\u7531\u4E8E\u6574\u5408\u4E86SpringBoot\uFF0C\u6240\u4EE5\u8981\u4F7F\u7528\u9002\u914DSpring\u7684Redis\u63D0\u4F9B\u65B9 15 | j2cache.L2.provider_class=net.oschina.j2cache.cache.support.redis.SpringRedisProvider 16 | # \u5BFC\u5165SpringDataRedis\u65F6\u9ED8\u8BA4\u5E26\u7684lettuce\uFF0C\u800Cj2cache\u9ED8\u8BA4\u4F7F\u7528jedis\uFF0C\u6240\u4EE5\u6B64\u5904\u9700\u8981\u663E\u5F0F\u914D\u7F6E 17 | j2cache.L2.config_section=lettuce 18 | # \u624B\u52A8\u5F00\u542F\u4E8C\u7EA7\u7F13\u5B58\uFF0C\u6784\u6210\u4E24\u5C42\u7EA7\u7F13\u5B58 19 | j2cache.l2-cache-open=true 20 | # \u6307\u5B9ARedis\u7684\u5BA2\u6237\u7AEF\u4E3Alettuce\uFF08\u9ED8\u8BA4\u662Fjedis\uFF09 21 | j2cache.redis-client=lettuce 22 | # \u5C06\u4E00\u7EA7\u7F13\u5B58\u4E2D\u7684\u8FC7\u671F\u65F6\u95F4\u540C\u6B65\u5230\u4E8C\u7EA7\u7F13\u5B58Redis\u4E2D 23 | j2cache.sync_ttl_to_redis=true 24 | # \u5411\u4E8C\u7EA7\u7F13\u5B58\u4FDD\u5B58\u6570\u636E\u65F6\u4F7F\u7528json\u5E8F\u5217\u5316 25 | j2cache.serialization=json 26 | # \u5F00\u542FSpringCache\u7684\u9002\u914D 27 | j2cache.open-spring-cache=true 28 | # \u542F\u7528\u7F13\u5B58\u8FC7\u671F\u7684\u5E7F\u64AD\uFF0C\u8BE5\u914D\u7F6E\u53EF\u4EE5\u5B9E\u73B0\u591A\u8282\u70B9\u7F13\u5B58\u6570\u636E\u7684\u53D1\u5E03\u8BA2\u9605\u66F4\u65B0 29 | j2cache.broadcast=net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy 30 | # \u7F13\u5B58\u8FC7\u671F\u7B56\u7565\uFF0C\u53EF\u9009\u503C\uFF1Aactive:\u4E3B\u52A8\u6E05\u9664(\u4E8C\u7EA7\u7F13\u5B58\u8FC7\u671F\u65F6\u901A\u77E5\u4E00\u7EA7\u7F13\u5B58),passive:\u88AB\u52A8\u6E05\u9664(\u4E00\u7EA7\u7F13\u5B58\u8FC7\u671F\u65F6\u901A\u77E5\u4E8C\u7EA7\u7F13\u5B58),blend:\u4E24\u79CD\u6A21\u5F0F\u4E00\u8D77\u8FD0\u4F5C 31 | j2cache.cache-clean-mode=passive 32 | 33 | # caffeine\u7684\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84 34 | caffeine.properties=/caffeine.properties 35 | 36 | # lettuce\u7684\u914D\u7F6E 37 | lettuce.channel=j2cache 38 | lettuce.schema=redis 39 | lettuce.hosts=${spring.redis.host}:${spring.redis.port} 40 | 41 | # SpringCache\u7684\u914D\u7F6E\uFF0C\u8BBE\u7F6Egeneric\u7684\u610F\u56FE\u4E3A\u8BA9j2cache\u6765\u63A5\u7BA1CacheManager 42 | spring.cache.type=generic 43 | spring.redis.host=localhost 44 | spring.redis.port=6379 45 | -------------------------------------------------------------------------------- /spring-boot-integration-09-quartz/src/main/java/com/linkedbear/boot/quartz/controller/DynamicScheduleController.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.quartz.controller; 2 | 3 | import com.linkedbear.boot.quartz.quartz.SimpleJob; 4 | import org.quartz.*; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.util.concurrent.ThreadLocalRandom; 10 | 11 | @RestController 12 | public class DynamicScheduleController { 13 | 14 | @Autowired 15 | private Scheduler scheduler; 16 | 17 | @GetMapping("/addSchedule") 18 | public String addSchedule() throws SchedulerException { 19 | int random = ThreadLocalRandom.current().nextInt(1000); 20 | JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class) 21 | .withIdentity("test-schedule" + random, "test-group").build(); 22 | CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule("0/3 * * * * ?"); 23 | Trigger trigger = TriggerBuilder.newTrigger().withIdentity("test-trigger" + random, "test-trigger-group") 24 | .withSchedule(cron).build(); 25 | scheduler.scheduleJob(jobDetail, trigger); 26 | return "success"; 27 | } 28 | 29 | @GetMapping("/pauseSchedule") 30 | public String pauseSchedule(String jobName, String jobGroup) throws SchedulerException { 31 | JobKey jobKey = JobKey.jobKey(jobName, jobGroup); 32 | // 获取定时任务 33 | JobDetail jobDetail = scheduler.getJobDetail(jobKey); 34 | if (jobDetail == null) { 35 | return "error"; 36 | } 37 | scheduler.pauseJob(jobKey); 38 | return "success"; 39 | } 40 | 41 | @GetMapping("/remuseSchedule") 42 | public String remuseSchedule(String jobName, String jobGroup) throws SchedulerException { 43 | JobKey jobKey = JobKey.jobKey(jobName, jobGroup); 44 | // 获取定时任务 45 | JobDetail jobDetail = scheduler.getJobDetail(jobKey); 46 | if (jobDetail == null) { 47 | return "error"; 48 | } 49 | scheduler.pauseJob(jobKey); 50 | return "success"; 51 | } 52 | 53 | @GetMapping("/removeSchedule") 54 | public String removeSchedule(String jobName, String jobGroup, String triggerName, String triggerGroup) throws SchedulerException { 55 | TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroup); 56 | JobKey jobKey = JobKey.jobKey(jobName, jobGroup); 57 | Trigger trigger = scheduler.getTrigger(triggerKey); 58 | if (trigger == null) { 59 | return "error"; 60 | } 61 | // 停止触发器 62 | scheduler.pauseTrigger(triggerKey); 63 | // 移除触发器 64 | scheduler.unscheduleJob(triggerKey); 65 | // 删除任务 66 | scheduler.deleteJob(jobKey); 67 | return "success"; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /spring-boot-integration-02-junit/src/test/java/demo/AssertTest.java: -------------------------------------------------------------------------------- 1 | package demo; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Assumptions; 5 | import org.junit.jupiter.api.RepetitionInfo; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.TestInfo; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.MethodSource; 10 | import org.junit.jupiter.params.provider.ValueSource; 11 | 12 | import java.time.Duration; 13 | import java.time.ZonedDateTime; 14 | import java.util.concurrent.TimeUnit; 15 | import java.util.stream.Stream; 16 | 17 | public class AssertTest { 18 | 19 | @Test 20 | public void testSimple() { 21 | // 最简单的断言,断言计算值与预期值是否相等 22 | int num = 3 + 5; 23 | Assertions.assertEquals(num, 8); 24 | 25 | double result = 10.0 / 3; 26 | // 断言计算值是否在浮点数的指定范围内上下浮动 27 | Assertions.assertEquals(result, 3, 0.5); 28 | // 如果浮动空间不够,则会断言失败 29 | // Assertions.assertEquals(result, 3, 0.2); 30 | // 传入message可以自定义错误提示信息 31 | Assertions.assertEquals(result, 3, 0.2, "计算数值偏差较大!"); 32 | 33 | // 断言两个对象是否是同一个 34 | Object o1 = new Object(); 35 | Object o2 = o1; 36 | Object o3 = new Object(); 37 | Assertions.assertSame(o1, o2); 38 | Assertions.assertSame(o1, o3); 39 | 40 | // 断言两个数组的元素是否完全相同 41 | String[] arr1 = {"aa", "bb"}; 42 | String[] arr2 = {"aa", "bb"}; 43 | String[] arr3 = {"bb", "aa"}; 44 | Assertions.assertArrayEquals(arr1, arr2); 45 | Assertions.assertArrayEquals(arr1, arr3); 46 | } 47 | 48 | @Test 49 | public void testCombination() { 50 | Assertions.assertAll( 51 | () -> { 52 | int num = 3 + 5; 53 | Assertions.assertEquals(num, 8); 54 | }, 55 | () -> { 56 | String[] arr1 = {"aa", "bb"}; 57 | String[] arr2 = {"bb", "aa"}; 58 | Assertions.assertArrayEquals(arr1, arr2); 59 | } 60 | ); 61 | } 62 | 63 | @Test 64 | public void testException() { 65 | Assertions.assertThrows(ArithmeticException.class, () -> { 66 | int i = 1 / 0; 67 | }); 68 | } 69 | 70 | @Test 71 | public void testTimeout() { 72 | Assertions.assertTimeout(Duration.ofMillis(500), () -> { 73 | System.out.println("testTimeout run ......"); 74 | TimeUnit.SECONDS.sleep(1); 75 | System.out.println("testTimeout finished ......"); 76 | }); 77 | } 78 | 79 | @Test 80 | public void testFail() { 81 | if (ZonedDateTime.now().getHour() > 12) { 82 | Assertions.fail(); 83 | } 84 | } 85 | 86 | @Test 87 | public void testAssumptions() { 88 | int num = 3 + 5; 89 | Assumptions.assumeTrue(num < 10); 90 | 91 | Assertions.assertTrue(10 - num > 0); 92 | } 93 | 94 | @Test 95 | public void testArgumentInject(TestInfo testInfo) { 96 | System.out.println(testInfo.getTestClass().get().getName()); 97 | } 98 | 99 | @ParameterizedTest 100 | @ValueSource(strings = {"aa", "bb", "cc"}) 101 | public void testSimpleParameterized(String value) throws Exception { 102 | System.out.println(value); 103 | Assertions.assertTrue(value.length() < 3); 104 | } 105 | 106 | @ParameterizedTest 107 | @MethodSource("dataProvider") 108 | public void testDataStreamParameterized(Integer value) throws Exception { 109 | System.out.println(value); 110 | Assertions.assertTrue(value < 10); 111 | } 112 | 113 | private static Stream dataProvider() { 114 | return Stream.of(1, 2, 3, 4, 5); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/test/java/com/linkedbear/boot/springdata/JpaTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata; 2 | 3 | import com.linkedbear.boot.springdata.jpa.dao.DepartmentDao; 4 | import com.linkedbear.boot.springdata.jpa.dao.UserDao; 5 | import com.linkedbear.boot.springdata.jpa.entity.Department; 6 | import com.linkedbear.boot.springdata.jpa.entity.User; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.PageRequest; 14 | import org.springframework.transaction.support.TransactionTemplate; 15 | 16 | import javax.persistence.EntityManager; 17 | import javax.persistence.EntityManagerFactory; 18 | import javax.persistence.Query; 19 | import javax.persistence.criteria.Predicate; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | @SpringBootTest 24 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) 25 | public class JpaTest { 26 | 27 | @Autowired 28 | private TransactionTemplate transactionTemplate; 29 | 30 | @Autowired 31 | private EntityManagerFactory entityManagerFactory; 32 | 33 | @Autowired 34 | private UserDao userDao; 35 | 36 | @Autowired 37 | private DepartmentDao departmentDao; 38 | 39 | @Test 40 | public void test1() throws Exception { 41 | List users = userDao.findAll(); 42 | System.out.println(users); 43 | } 44 | 45 | @Test 46 | public void test2() throws Exception { 47 | User user = new User(); 48 | user.setName("test springdatajpa"); 49 | user.setTel("123321"); 50 | userDao.save(user); 51 | } 52 | 53 | @Test 54 | public void testSave() throws Exception { 55 | Department department = new Department(); 56 | department.setName("测试部门"); 57 | department.setAddress("test test"); 58 | departmentDao.save(department); 59 | } 60 | 61 | @Test 62 | public void testUpdate() throws Exception { 63 | transactionTemplate.executeWithoutResult(status -> { 64 | Department department = departmentDao.getById(1); 65 | department.setName("测试修改部门"); 66 | departmentDao.save(department); 67 | }); 68 | } 69 | 70 | @Test 71 | public void testDelete() throws Exception { 72 | transactionTemplate.executeWithoutResult(status -> { 73 | departmentDao.deleteById(1); 74 | }); 75 | } 76 | 77 | @Test 78 | public void testQuery() throws Exception { 79 | List all = departmentDao.findAll(); 80 | System.out.println(all); 81 | 82 | boolean exists = departmentDao.existsById(20); 83 | System.out.println(exists); 84 | 85 | Page userPage = userDao.findAll(PageRequest.of(0, 2)); 86 | System.out.println(userPage.getTotalElements()); 87 | System.out.println(userPage.getTotalPages()); 88 | System.out.println(userPage.getContent()); 89 | } 90 | 91 | @Test 92 | public void testJPQL() throws Exception { 93 | EntityManager entityManager = entityManagerFactory.createEntityManager(); 94 | List userList = entityManager.createQuery("from User").getResultList(); 95 | System.out.println(userList); 96 | 97 | // userDao.findAllByQuery(); 98 | userDao.findAllById(1); 99 | } 100 | 101 | @Test 102 | public void testFind() throws Exception { 103 | User example = new User(); 104 | example.setName("my"); 105 | List users = userDao.findAll((root, query, criteriaBuilder) -> { 106 | List criterias = new ArrayList<>(); 107 | criterias.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + example.getName() + "%")); 108 | return criteriaBuilder.and(criterias.toArray(new Predicate[0])); 109 | }); 110 | users.forEach(System.out::println); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /spring-boot-integration-04-springdata/src/test/java/com/linkedbear/boot/springdata/MongoTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.springdata; 2 | 3 | import com.linkedbear.boot.springdata.mongo.dao.UserRepository; 4 | import com.linkedbear.boot.springdata.mongo.entity.Department; 5 | import com.linkedbear.boot.springdata.mongo.entity.User; 6 | import com.linkedbear.boot.springdata.mongo.service.DepartmentService; 7 | import com.linkedbear.boot.springdata.mongo.service.UserService; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.data.domain.Example; 12 | import org.springframework.data.domain.Sort; 13 | import org.springframework.data.mongodb.core.MongoTemplate; 14 | import org.springframework.data.mongodb.core.query.Criteria; 15 | import org.springframework.data.mongodb.core.query.Query; 16 | import org.springframework.data.mongodb.core.query.Update; 17 | 18 | import java.util.List; 19 | import java.util.Optional; 20 | 21 | //@DataMongoTest 22 | @SpringBootTest 23 | public class MongoTest { 24 | 25 | @Autowired 26 | private UserRepository userRepository; 27 | 28 | @Autowired 29 | private UserService userService; 30 | 31 | @Autowired 32 | private DepartmentService departmentService; 33 | 34 | @Autowired 35 | private MongoTemplate mongoTemplate; 36 | 37 | @Test 38 | public void test1() throws Exception { 39 | User user = new User(); 40 | user.setName("mongo"); 41 | user.setAge(20); 42 | userRepository.save(user); 43 | } 44 | 45 | @Test 46 | public void test2() throws Exception { 47 | List users = userRepository.findAll(); 48 | System.out.println(users); 49 | } 50 | 51 | @Test 52 | public void testSave() throws Exception { 53 | User user = new User(); 54 | user.setName("template"); 55 | user.setAge(12); 56 | // mongoTemplate.save(user); 57 | 58 | User userWithId = mongoTemplate.insert(User.class).one(user); 59 | System.out.println(user); 60 | System.out.println(userWithId); 61 | System.out.println(user == userWithId); 62 | } 63 | 64 | @Test 65 | public void testUpdate() throws Exception { 66 | /* 67 | Optional op = userRepository.findById("62f0eb78332a95603b13c35b"); 68 | op.ifPresent(user -> { 69 | user.setAge(60); 70 | userRepository.save(user); 71 | }); 72 | 73 | userRepository.findById("62f0eb78332a95603b13c35b").ifPresent(System.out::println); 74 | */ 75 | 76 | // --- 77 | 78 | /* 79 | User replace = new User(); 80 | replace.setAge(100); 81 | mongoTemplate.update(User.class).matching(Criteria.where("name").is("mongo")).replaceWith(replace).as(User.class).findAndReplaceValue(); 82 | userRepository.findById("62f0eb78332a95603b13c35b").ifPresent(System.out::println); 83 | */ 84 | 85 | mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("mongo")), Update.update("age", 200), User.class); 86 | userRepository.findById("62f0eb78332a95603b13c35b").ifPresent(System.out::println); 87 | } 88 | 89 | @Test 90 | public void testDelete() throws Exception { 91 | userRepository.deleteById("62f0eb78332a95603b13c35b"); 92 | userRepository.findById("62f0eb78332a95603b13c35b").ifPresent(System.out::println); 93 | 94 | mongoTemplate.remove(Query.query(Criteria.where("age").gt(30)), User.class); 95 | mongoTemplate.findAll(User.class).forEach(System.out::println); 96 | } 97 | 98 | @Test 99 | public void testQuery() throws Exception { 100 | System.out.println("userRepository.findAll(): " + userRepository.findAll()); 101 | System.out.println("order by: " + userRepository.findAll(Sort.by(Sort.Order.desc("age")))); 102 | System.out.println("mongoTemplate.find: " + mongoTemplate.find(Query.query(Criteria.where("age").lt(18)), User.class)); 103 | System.out.println("mongoTemplate.findById: " + mongoTemplate.findById("62f0f24e618cfd7eb146b14c", User.class)); 104 | } 105 | 106 | @Test 107 | public void testUserService() throws Exception { 108 | userService.saveAndPrint(); 109 | } 110 | 111 | @Test 112 | public void testSaveDepartment() throws Exception { 113 | departmentService.save(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/RsaUtils.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import org.springframework.core.io.ClassPathResource; 4 | import org.springframework.util.Base64Utils; 5 | import org.springframework.util.FileCopyUtils; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.nio.file.Files; 10 | import java.security.KeyFactory; 11 | import java.security.KeyPair; 12 | import java.security.KeyPairGenerator; 13 | import java.security.NoSuchAlgorithmException; 14 | import java.security.PrivateKey; 15 | import java.security.PublicKey; 16 | import java.security.SecureRandom; 17 | import java.security.spec.InvalidKeySpecException; 18 | import java.security.spec.PKCS8EncodedKeySpec; 19 | import java.security.spec.X509EncodedKeySpec; 20 | import java.util.Base64; 21 | 22 | public abstract class RsaUtils { 23 | 24 | public static final int DEFAULT_KEY_SIZE = 2048; 25 | public static final String RSA_SECURT = "websecurity"; 26 | 27 | /** 28 | * 根据路径加载公钥 29 | * @param filename 30 | * @return 31 | */ 32 | public static PublicKey getPublicKey(String filename) { 33 | try { 34 | ClassPathResource resource = new ClassPathResource(filename); 35 | byte[] publicKeyBytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); 36 | byte[] decode = Base64Utils.decode(publicKeyBytes); 37 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decode); 38 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 39 | return keyFactory.generatePublic(keySpec); 40 | } catch (IOException e) { 41 | throw new SecurityException("加载公钥文件失败!", e); 42 | } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 43 | throw new SecurityException(e.getMessage(), e); 44 | } 45 | } 46 | 47 | /** 48 | * 根据路径加载私钥 49 | * @param filename 50 | * @return 51 | */ 52 | public static PrivateKey getPrivateKey(String filename) { 53 | try { 54 | ClassPathResource resource = new ClassPathResource(filename); 55 | byte[] privateKeyBytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); 56 | byte[] decode = Base64Utils.decode(privateKeyBytes); 57 | PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decode); 58 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 59 | return keyFactory.generatePrivate(keySpec); 60 | } catch (IOException e) { 61 | throw new SecurityException("加载私钥文件失败!", e); 62 | } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 63 | throw new SecurityException(e.getMessage(), e); 64 | } 65 | } 66 | 67 | /** 68 | * 生成公钥、私钥 69 | * @param publicKeyFilename 70 | * @param privateKeyFilename 71 | * @param secret 72 | */ 73 | public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) { 74 | try { 75 | KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); 76 | SecureRandom secureRandom = new SecureRandom(secret.getBytes()); 77 | keyPairGenerator.initialize(DEFAULT_KEY_SIZE, secureRandom); 78 | KeyPair keyPair = keyPairGenerator.genKeyPair(); 79 | 80 | // 获取公钥并写出 81 | byte[] publicKeyBytes = keyPair.getPublic().getEncoded(); 82 | publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes); 83 | writeFile(publicKeyFilename, publicKeyBytes); 84 | 85 | // 获取私钥并写出 86 | byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); 87 | privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes); 88 | writeFile(privateKeyFilename, privateKeyBytes); 89 | } catch (NoSuchAlgorithmException e) { 90 | throw new SecurityException(e.getMessage(), e); 91 | } 92 | } 93 | 94 | private static void writeFile(String filename, byte[] bytes) { 95 | try { 96 | File file = new File(filename); 97 | if (!file.exists()) { 98 | file.createNewFile(); 99 | } 100 | Files.write(file.toPath(), bytes); 101 | } catch (IOException e) { 102 | throw new SecurityException("保存密钥文件失败!", e); 103 | } 104 | } 105 | 106 | public static void main(String[] args) { 107 | generateKey("D:/jwt_rsa.pub", "D:/jwt_rsa", RSA_SECURT); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /spring-boot-integration-08-rocketmq-producer/src/main/java/com/linkedbear/boot/rocketmq/producer/service/MessageSender.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.rocketmq.producer.service; 2 | 3 | import com.linkedbear.boot.rocketmq.producer.dto.UserDTO; 4 | import org.apache.rocketmq.client.producer.SendCallback; 5 | import org.apache.rocketmq.client.producer.SendResult; 6 | import org.apache.rocketmq.spring.core.RocketMQTemplate; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.messaging.Message; 10 | import org.springframework.messaging.support.MessageBuilder; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.UUID; 14 | 15 | @Service 16 | public class MessageSender { 17 | 18 | @Autowired 19 | private RocketMQTemplate rocketMQTemplate; 20 | 21 | @Autowired 22 | @Qualifier("dataUpdateRocketMQTemplate") 23 | private RocketMQTemplate dataUpdateRocketMQTemplate; 24 | 25 | public void sendMessage() { 26 | // 同步发送消息 27 | System.out.println(System.currentTimeMillis()); 28 | rocketMQTemplate.convertAndSend("test-sender", "test message"); 29 | System.out.println("发送同步消息成功"); 30 | System.out.println(System.currentTimeMillis()); 31 | } 32 | 33 | public void asyncSend() { 34 | // 异步发送消息 35 | rocketMQTemplate.asyncSend("test-sender", "test async message", new SendCallback() { 36 | @Override 37 | public void onSuccess(SendResult sendResult) { 38 | System.out.println("异步消息发送成功"); 39 | System.out.println(sendResult); 40 | } 41 | 42 | @Override 43 | public void onException(Throwable e) { 44 | System.out.println("消息发送失败,异常:" + e.getMessage()); 45 | e.printStackTrace(); 46 | } 47 | }); 48 | } 49 | 50 | public void sendOneway() { 51 | System.out.println(System.currentTimeMillis()); 52 | // 发送单向消息 53 | rocketMQTemplate.sendOneWay("test-sender", "test oneway message"); 54 | System.out.println("发送单向消息成功"); 55 | System.out.println(System.currentTimeMillis()); 56 | } 57 | 58 | public void sendTagsMessage() { 59 | // 发送tags为"software"和"hardware"的消息 60 | rocketMQTemplate.convertAndSend("test-tags:software", "test software message"); 61 | rocketMQTemplate.convertAndSend("test-tags:hardware", "test hardware message"); 62 | } 63 | 64 | public void sendDto() { 65 | // 构造发送一个DTO模型 66 | UserDTO dto = new UserDTO(); 67 | dto.setUserId(1); 68 | dto.setUserName("haha"); 69 | dto.setSexName("male"); 70 | rocketMQTemplate.convertAndSend("test-dto", dto); 71 | } 72 | 73 | public void sendDelayMessage() { 74 | // 同步发送延迟消息 75 | Message message = MessageBuilder.withPayload("delay message").build(); 76 | rocketMQTemplate.syncSend("test-delay", message, 3000, 2); 77 | System.out.println("同步延迟消息发送成功!时间:" + System.currentTimeMillis()); 78 | 79 | // 异步发送延迟消息 80 | rocketMQTemplate.asyncSend("test-delay", message, new SendCallback() { 81 | @Override 82 | public void onSuccess(SendResult sendResult) { 83 | System.out.println("异步延迟消息发送成功!时间:" + System.currentTimeMillis()); 84 | System.out.println(sendResult.toString()); 85 | } 86 | 87 | @Override 88 | public void onException(Throwable e) { 89 | System.out.println("异步延迟消息发送失败!"); 90 | e.printStackTrace(); 91 | } 92 | }, 3000, 3); 93 | } 94 | 95 | public void sendTransactionalMessage() { 96 | // 第1步:发送事务消息,为了能识别出某个事务消息对应的本地事务,此处生成一个uuid设置到消息头上 97 | String txId = UUID.randomUUID().toString(); 98 | rocketMQTemplate.sendMessageInTransaction("test-transactional", 99 | MessageBuilder.withPayload("事务消息").setHeaderIfAbsent("txId", txId).build(), txId); 100 | // 第三个参数可以传入任意参数,此处来传入对应的事务标识uuid(根据业务需求来,通常不传) 101 | } 102 | 103 | public void sendUpdateTransactionalMessage() { 104 | // 换一个Template发送 105 | String txId = UUID.randomUUID().toString(); 106 | dataUpdateRocketMQTemplate.sendMessageInTransaction("test-transactionalupdate", 107 | MessageBuilder.withPayload("update事务消息").setHeaderIfAbsent("txId", txId).build(), null); 108 | } 109 | 110 | 111 | public void send10Message() { 112 | for (int i = 0; i < 10; i++) { 113 | rocketMQTemplate.syncSend("test-ordered", "message" + i); 114 | } 115 | } 116 | public void sendOrderedMessage() { 117 | for (int i = 0; i < 10; i++) { 118 | rocketMQTemplate.syncSendOrderly("test-ordered", "ordered-message" + i, "ordered"); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/jwt/JwtUtils.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.jwt; 2 | 3 | import com.linkedbear.boot.security.entity.SecurityUser; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.Jws; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.SignatureAlgorithm; 8 | import org.springframework.security.core.userdetails.User; 9 | import org.springframework.util.Base64Utils; 10 | import org.springframework.util.StringUtils; 11 | 12 | import javax.servlet.http.HttpServletResponse; 13 | import java.security.PrivateKey; 14 | import java.security.PublicKey; 15 | import java.util.Base64; 16 | import java.util.Date; 17 | import java.util.UUID; 18 | 19 | public abstract class JwtUtils { 20 | 21 | public static final String JWT_PAYLOAD = "user"; 22 | public static final String JWT_HEADER = "authorization"; 23 | /** 分割jwt与刷新令牌的标识 */ 24 | public static final String JWT_SLIPTER = "abcdefg.uvwxyz"; 25 | 26 | public static final char ENCODE_CHAR = 'a'; 27 | 28 | /** 29 | * 向客户端响应jwt访问+刷新令牌 30 | * @param response 31 | * @param user 32 | * @param privateKey 33 | * @param accessExpire 34 | * @param refreshExpire 35 | */ 36 | public static void writeJwtToken(HttpServletResponse response, User user, PrivateKey privateKey, 37 | int accessExpire, int refreshExpire) { 38 | String jwtToken = JwtUtils.generateJwtToken(user, privateKey, accessExpire); 39 | String refreshToken = JwtUtils.generateRefreshToken(user, privateKey, refreshExpire); 40 | // response.addHeader(JWT_HEADER, jwtToken); 41 | response.addHeader(JWT_HEADER, jwtToken + JWT_SLIPTER + refreshToken); 42 | } 43 | 44 | /** 45 | * 生成jwt令牌 46 | * @param user 47 | * @param privateKey 48 | * @param expire 秒 49 | * @return 50 | */ 51 | public static String generateJwtToken(User user, PrivateKey privateKey, int expire) { 52 | return Jwts.builder().claim(JWT_PAYLOAD, JsonUtils.toJson(user)).setId(createJtl()) 53 | .setExpiration(new Date(System.currentTimeMillis() + expire * 1000)) 54 | .signWith(privateKey, SignatureAlgorithm.RS256).compact(); 55 | } 56 | 57 | /** 58 | * 生成刷新令牌 59 | * @param user 60 | * @param expire 秒 61 | * @return 62 | */ 63 | public static String generateRefreshToken(User user, PrivateKey privateKey, int expire) { 64 | String tokenJson = JsonUtils.toJson(user); 65 | String encodedTokenJson = encodeRefreshToken(tokenJson); 66 | return Jwts.builder().claim(JWT_PAYLOAD, encodedTokenJson).setId(createJtl()) 67 | .setExpiration(new Date(System.currentTimeMillis() + expire * 1000)) 68 | .signWith(privateKey, SignatureAlgorithm.RS256).compact(); 69 | } 70 | 71 | /** 72 | * 解析jwt令牌 73 | * @param token 74 | * @param publicKey 75 | * @return 76 | */ 77 | public static TokenPayload parseToken(String token, PublicKey publicKey) { 78 | Jws claimsJws = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token); 79 | Claims claims = claimsJws.getBody(); 80 | TokenPayload payload = new TokenPayload(); 81 | payload.setId(claims.getId()); 82 | payload.setExpiration(claims.getExpiration()); 83 | payload.setUser(JsonUtils.parseObject(claims.get(JWT_PAYLOAD).toString(), SecurityUser.class)); 84 | return payload; 85 | } 86 | 87 | /** 88 | * 解析jwt令牌中的载荷部分 89 | * @param token 90 | * @param publicKey 91 | * @return 92 | */ 93 | public static String getTokenPayload(String token, PublicKey publicKey) { 94 | Jws claimsJws = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token); 95 | Claims claims = claimsJws.getBody(); 96 | return claims.get(JWT_PAYLOAD).toString(); 97 | } 98 | 99 | public static String createJtl() { 100 | return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())); 101 | } 102 | 103 | /** 104 | * 编码token中的信息 105 | * @param tokenJson 106 | * @return 107 | */ 108 | public static String encodeRefreshToken(String tokenJson) { 109 | StringBuilder sb = new StringBuilder(tokenJson.length() + 10); 110 | sb.append("refresh "); 111 | char[] chars = tokenJson.toCharArray(); 112 | for (char c : chars) { 113 | c ^= ENCODE_CHAR; 114 | sb.append(c); 115 | } 116 | String encodedTokenJson = sb.toString(); 117 | return new String(Base64Utils.encode(encodedTokenJson.getBytes())); 118 | } 119 | 120 | /** 121 | * 解码token中的信息 122 | * @param encodedToken 123 | * @return 124 | */ 125 | public static String decodeRefreshToken(String encodedToken) { 126 | if (!StringUtils.hasText(encodedToken)) { 127 | return ""; 128 | } 129 | 130 | String encodedTokenJson = new String(Base64Utils.decode(encodedToken.getBytes())); 131 | if (encodedTokenJson.length() <= 8) { 132 | return ""; 133 | } 134 | encodedTokenJson = encodedTokenJson.substring(8); 135 | StringBuilder sb = new StringBuilder(encodedTokenJson.length()); 136 | char[] chars = encodedTokenJson.toCharArray(); 137 | for (char c : chars) { 138 | c ^= ENCODE_CHAR; 139 | sb.append(c); 140 | } 141 | return sb.toString(); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /spring-boot-integration-05-elasticsearch/src/test/java/com/linkedbear/boot/elasticsearch/ElasticSearchClientTest.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.elasticsearch; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.linkedbear.boot.elasticsearch.entity.GraphicsCard; 5 | import org.apache.http.HttpHost; 6 | import org.elasticsearch.action.get.GetRequest; 7 | import org.elasticsearch.action.get.GetResponse; 8 | import org.elasticsearch.action.index.IndexRequest; 9 | import org.elasticsearch.action.search.SearchRequest; 10 | import org.elasticsearch.action.search.SearchResponse; 11 | import org.elasticsearch.client.RequestOptions; 12 | import org.elasticsearch.client.RestClient; 13 | import org.elasticsearch.client.RestClientBuilder; 14 | import org.elasticsearch.client.RestHighLevelClient; 15 | import org.elasticsearch.common.xcontent.XContentType; 16 | import org.elasticsearch.index.query.QueryBuilders; 17 | import org.elasticsearch.search.SearchHit; 18 | import org.elasticsearch.search.builder.SearchSourceBuilder; 19 | import org.junit.jupiter.api.Test; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.beans.factory.annotation.Value; 22 | import org.springframework.boot.test.context.SpringBootTest; 23 | import org.springframework.cglib.beans.BeanMap; 24 | import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; 25 | import org.springframework.data.elasticsearch.core.SearchHits; 26 | import org.springframework.data.elasticsearch.core.query.Criteria; 27 | import org.springframework.data.elasticsearch.core.query.CriteriaQuery; 28 | import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; 29 | import org.springframework.data.elasticsearch.core.query.Query; 30 | 31 | import java.util.Map; 32 | 33 | @SpringBootTest 34 | public class ElasticSearchClientTest { 35 | 36 | @Value("${spring.elasticsearch.rest.uris}") 37 | private String esHost; 38 | 39 | @Test 40 | public void test1() throws Exception { 41 | RestClientBuilder builder = RestClient.builder(HttpHost.create(esHost)); 42 | RestHighLevelClient client = new RestHighLevelClient(builder); 43 | System.out.println(client); 44 | client.close(); 45 | } 46 | 47 | @Autowired 48 | private RestHighLevelClient restHighLevelClient; 49 | 50 | @Test 51 | public void testIndex() throws Exception { 52 | GraphicsCard graphicsCard = new GraphicsCard(); 53 | graphicsCard.setId(2); 54 | graphicsCard.setName("七彩虹(Colorful)战斧GeForce RTX 4090 豪华版"); 55 | graphicsCard.setBrand("七彩虹"); 56 | graphicsCard.setPrice(12999); 57 | String jsonString = new ObjectMapper().writeValueAsString(graphicsCard); 58 | IndexRequest request = new IndexRequest("gpu").id(graphicsCard.getId().toString()) 59 | .source(jsonString, XContentType.JSON); 60 | restHighLevelClient.index(request, RequestOptions.DEFAULT); 61 | } 62 | 63 | @Test 64 | public void testIndex3() throws Exception { 65 | GraphicsCard graphicsCard = new GraphicsCard(); 66 | graphicsCard.setId(3); 67 | graphicsCard.setName("华硕 ASUS TUF-GeForce RTX 3080 Ti-O12G-GAMING"); 68 | graphicsCard.setBrand("华硕"); 69 | graphicsCard.setPrice(7999); 70 | Map data = BeanMap.create(graphicsCard); 71 | IndexRequest request = new IndexRequest("gpu").id(graphicsCard.getId().toString()).source(data); 72 | restHighLevelClient.index(request, RequestOptions.DEFAULT); 73 | } 74 | 75 | @Test 76 | public void testSearch() throws Exception { 77 | SearchRequest request = new SearchRequest("gpu"); 78 | 79 | // 添加查询条件 80 | SearchSourceBuilder builder = new SearchSourceBuilder(); 81 | // builder.query(QueryBuilders.termQuery("name", "3080")); 82 | // builder.query(QueryBuilders.rangeQuery("price").lt(10000)); 83 | builder.query(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", "七彩虹")) 84 | .filter(QueryBuilders.rangeQuery("price").gte(10000))); 85 | request.source(builder); 86 | 87 | SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT); 88 | for (SearchHit hit : response.getHits()) { 89 | System.out.println(hit.getSourceAsString()); 90 | } 91 | } 92 | 93 | @Test 94 | public void testGet() throws Exception { 95 | GetRequest request = new GetRequest("gpu").id("3"); 96 | GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT); 97 | System.out.println(response.getSourceAsString()); 98 | GraphicsCard graphicsCard = new ObjectMapper().readValue(response.getSourceAsString(), GraphicsCard.class); 99 | System.out.println(graphicsCard); 100 | } 101 | 102 | @Autowired 103 | private ElasticsearchRestTemplate elasticsearchRestTemplate; 104 | 105 | @Test 106 | public void testTemplate() throws Exception { 107 | SearchHits hits = elasticsearchRestTemplate 108 | .search(new CriteriaQuery(Criteria.where("name").contains("ROG")), GraphicsCard.class); 109 | for (org.springframework.data.elasticsearch.core.SearchHit hit : hits) { 110 | System.out.println(hit.getContent()); 111 | } 112 | 113 | hits = elasticsearchRestTemplate.search(new NativeSearchQuery(QueryBuilders.termQuery("name", "ROG")), GraphicsCard.class); 114 | for (org.springframework.data.elasticsearch.core.SearchHit hit : hits) { 115 | System.out.println(hit.getContent()); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /spring-boot-integration-07-security-webmvc/src/main/java/com/linkedbear/boot/security/config/WebSecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.linkedbear.boot.security.config; 2 | 3 | import com.linkedbear.boot.security.filter.ResourceAuthorizationFilter; 4 | import com.linkedbear.boot.security.jwt.JwtTokenFilter; 5 | import com.linkedbear.boot.security.jwt.JwtUtils; 6 | import com.linkedbear.boot.security.jwt.RsaUtils; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.jdbc.core.JdbcTemplate; 11 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.config.http.SessionCreationPolicy; 16 | import org.springframework.security.core.userdetails.User; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 19 | import org.springframework.security.crypto.password.PasswordEncoder; 20 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 21 | import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; 22 | import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; 23 | import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; 24 | 25 | import java.security.PrivateKey; 26 | 27 | @Configuration 28 | @EnableWebSecurity 29 | @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true, proxyTargetClass = true) 30 | public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 31 | 32 | @Autowired 33 | private UserDetailsService userDetailsService; 34 | 35 | @Autowired 36 | private JdbcTemplate jdbcTemplate; 37 | 38 | @Autowired 39 | private ResourceAuthorizationFilter resourceAuthorizationFilter; 40 | 41 | private PrivateKey privateKey; 42 | 43 | @Autowired 44 | private JwtTokenFilter jwtTokenFilter; 45 | 46 | private static String[] ignoreUrls = {"/login", "/logout", "/refreshToken"}; 47 | 48 | @Override 49 | protected void configure(HttpSecurity http) throws Exception { 50 | // 开启表单登录功能 51 | // http.formLogin().successHandler((request, response, authentication) -> { 52 | // System.out.println(authentication); 53 | // response.setContentType("application/json;charset=utf-8"); 54 | // response.getWriter().write("登录成功"); 55 | // }).failureHandler((request, response, exception) -> { 56 | // exception.printStackTrace(); 57 | // response.setContentType("application/json;charset=utf-8"); 58 | // response.getWriter().write("登录失败"); 59 | // }); 60 | // 限制所有接口都需要认证后访问 61 | // http.authorizeRequests().anyRequest().authenticated(); 62 | // 限制/api开头的接口需要拥有admin角色,其余接口需要认证后访问 63 | // http.authorizeRequests().antMatchers("/api/**").hasRole("admin").anyRequest().authenticated(); 64 | // 引入用户管理机制 65 | // http.userDetailsService(userDetailsService()); 66 | // 关闭CSRF 67 | http.csrf().disable(); 68 | // 使用cookie存放CSRF标识 69 | // http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); 70 | // 引用IOC容器中注册的UserDetailsService实现(即基于数据库管理的实现) 71 | http.userDetailsService(userDetailsService); 72 | // 开启记住我 73 | // http.rememberMe(); 74 | // 持久化存储记住我的信息 75 | JdbcTokenRepositoryImpl remembermeRepository = new JdbcTokenRepositoryImpl(); 76 | remembermeRepository.setJdbcTemplate(jdbcTemplate); 77 | http.rememberMe().tokenRepository(remembermeRepository); 78 | 79 | // 限制/api开头的接口需要拥有api权限,其余接口需要认证后访问 80 | // http.authorizeRequests().antMatchers("/api/**").hasAuthority("api").anyRequest().authenticated(); 81 | // 限制/api/test接口需要拥有/api/test权限 82 | // http.authorizeRequests().antMatchers("/api/test").hasAuthority("/api/test").anyRequest().authenticated(); 83 | 84 | // 默认的权限控制只检查是否已登录 85 | // http.authorizeRequests().anyRequest().authenticated(); 86 | // 注入自定义过滤器,连接数据库动态鉴权 87 | http.addFilterAfter(resourceAuthorizationFilter, FilterSecurityInterceptor.class); 88 | 89 | // 开启表单登录功能,设置认证成功后响应jwt信息 90 | this.privateKey = RsaUtils.getPrivateKey("jwt_rsa"); 91 | http.formLogin().successHandler((request, response, authentication) -> { 92 | User user = (User) authentication.getPrincipal(); 93 | JwtUtils.writeJwtToken(response, user, privateKey, 30, 3600); 94 | response.setContentType("application/json;charset=utf-8"); 95 | response.getWriter().write("登录成功"); 96 | }).failureHandler((request, response, exception) -> { 97 | exception.printStackTrace(); 98 | response.setContentType("application/json;charset=utf-8"); 99 | response.getWriter().write("登录失败"); 100 | }); 101 | // 设置jwt令牌的解析过滤器执行时机比AnonymousAuthenticationFilter靠前 102 | http.addFilterBefore(jwtTokenFilter, AnonymousAuthenticationFilter.class); 103 | // 设置无状态session 104 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 105 | // 设置访问白名单 106 | http.authorizeRequests().antMatchers(ignoreUrls).permitAll().anyRequest().authenticated(); 107 | } 108 | 109 | // @Bean 110 | public UserDetailsService userDetailsService() { 111 | InMemoryUserDetailsManager userManager = new InMemoryUserDetailsManager(); 112 | userManager.createUser(User.withUsername("xiaoshuai").password(passwordEncoder().encode("123456")).roles("admin").build()); 113 | userManager.createUser(User.withUsername("xiaoming").password(passwordEncoder().encode("654321")).roles("user").build()); 114 | userManager.createUser(User.withUsername("boss").password(passwordEncoder().encode("123456")).roles("admin", "manager").build()); 115 | return userManager; 116 | } 117 | 118 | @Bean 119 | public PasswordEncoder passwordEncoder() { 120 | return new BCryptPasswordEncoder(); 121 | } 122 | } 123 | --------------------------------------------------------------------------------