├── README.md ├── desing-pattern ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── desingpattern │ │ │ └── DesingPatternApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── desingpattern │ └── DesingPatternApplicationTests.java ├── elastic-search ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── elasticsearch │ │ │ └── ElasticSearchApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── elasticsearch │ └── ElasticSearchApplicationTests.java ├── pom.xml ├── springbootdemo-consumer ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemoconsumer │ │ ├── SpringbootdemoConsumerApplication.java │ │ ├── config │ │ └── webConfig │ │ │ └── WebConfig.java │ │ ├── controller │ │ ├── ConsumerController.java │ │ ├── ErrorController.java │ │ ├── JspController.java │ │ ├── RedisController.java │ │ └── UserController.java │ │ ├── dao │ │ └── UserMapper.java │ │ ├── execption │ │ └── ExecptionController.java │ │ └── service │ │ ├── ProductService.java │ │ └── UserService.java │ ├── resources │ ├── application-dev.yml │ ├── application-pre.yml │ ├── application-uat.yml │ ├── application.yml │ └── mapper │ │ └── UserMapper.xml │ └── webapp │ ├── WEB-INF │ └── jsp │ │ └── index.jsp │ └── web.xml ├── springbootdemo-entity ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── example │ └── springbootdemoentity │ ├── config │ └── repeatCommitConfig │ │ ├── AvoidRepeatableCommit.java │ │ └── AvoidRepeatableCommitAspect.java │ ├── entity │ ├── Consumer.java │ ├── Pool.java │ ├── Product.java │ └── User.java │ └── redisConfig │ ├── JedisClient.java │ ├── JedisClientCluster.java │ ├── RedisConfig.java │ └── RedisProperties.java ├── springbootdemo-eureka ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemoeureka │ │ └── SpringbootdemoEurekaApplication.java │ └── resources │ └── application.yml ├── springbootdemo-filter ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemofilter │ │ ├── SpringbootdemoFilterApplication.java │ │ ├── configure │ │ └── Configuration.java │ │ ├── controller │ │ └── WebController.java │ │ └── filterTest │ │ ├── FirstFilter.java │ │ └── SecondFilter.java │ └── resources │ └── application.yml ├── springbootdemo-foundation ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootdemofoundation │ │ │ └── SpringbootdemoFoundationApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── example │ └── springbootdemofoundation │ ├── SpringbootdemoFoundationApplicationTests.java │ ├── Test.java │ └── entity │ ├── AbsExexEntity.java │ ├── AbsExtendsEntity.java │ ├── AbstractEntity.java │ ├── InterfaceEntity.java │ ├── InterfaceEntity2.java │ └── interfaceImpEntity.java ├── springbootdemo-product ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemoproduct │ │ ├── SpringbootdemoProductApplication.java │ │ ├── controller │ │ └── ProductController.java │ │ └── exception │ │ ├── MyControllerAdvice.java │ │ └── MyException.java │ └── resources │ ├── application.yml │ └── templates │ └── error.ftl ├── springbootdemo-rabbitmq ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemorabbitmq │ │ ├── RabbitMQDemo02 │ │ ├── Readme.md │ │ └── util │ │ │ └── ConnectionUtil.java │ │ ├── SpringbootdemoRabbitmqApplication.java │ │ └── rabbitMQDemo01 │ │ ├── Readme.md │ │ ├── entity │ │ ├── ConsumerEntity.java │ │ └── ProductEntity.java │ │ └── util │ │ └── ConnectionUtil.java │ └── resources │ └── application.properties ├── springbootdemo-test ├── pom.xml ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootdemotest │ │ │ ├── DateTest.java │ │ │ ├── DoubleTest.java │ │ │ ├── JsonFormatTest.java │ │ │ ├── SpringbootdemoTestApplication.java │ │ │ ├── byteCode │ │ │ ├── Class文件二进制码 │ │ │ └── class文件结构 │ │ │ ├── classLoader │ │ │ ├── MainClass.java │ │ │ ├── PersionClass.java │ │ │ └── 自定义类加载力器 │ │ │ ├── controller │ │ │ └── WebController.java │ │ │ ├── enumTest │ │ │ ├── EnumDemo01.java │ │ │ └── EnumDemo02.java │ │ │ ├── interfaces │ │ │ ├── LambdaNonReturnMutipleParameter.java │ │ │ ├── LambdaNonReturnNonParameter.java │ │ │ ├── LambdaNonReturnSingleParameter.java │ │ │ ├── LambdaSingleRetrunSingleParameter.java │ │ │ ├── LambdaSingleReturnMutiplyParameter.java │ │ │ └── LambdaSingleReturnNoneParameter.java │ │ │ ├── lambdaPackage │ │ │ ├── Program.java │ │ │ └── ProgramDemo02.java │ │ │ ├── proxy │ │ │ ├── clibPackage │ │ │ │ ├── MainClass.java │ │ │ │ ├── ProxyFactory.java │ │ │ │ └── Singer.java │ │ │ ├── jdkPackage │ │ │ │ ├── ISinger.java │ │ │ │ ├── MainClass.java │ │ │ │ └── Singer.java │ │ │ ├── principle │ │ │ │ ├── $Proxy1.class │ │ │ │ ├── $Proxy1.java │ │ │ │ ├── InvocationHandler.java │ │ │ │ ├── Moveable.java │ │ │ │ ├── Proxy.java │ │ │ │ ├── Tank.java │ │ │ │ ├── TimeHandler.java │ │ │ │ └── 底层动态生成代理类和编译过程 │ │ │ └── staticPacakge │ │ │ │ ├── ISinger.java │ │ │ │ ├── MainClass.java │ │ │ │ ├── Singer.java │ │ │ │ └── SingerProxy.java │ │ │ ├── qas │ │ │ └── QasTest.java │ │ │ ├── reflect │ │ │ ├── MainClass.java │ │ │ ├── User.java │ │ │ └── 反射.txt │ │ │ ├── streamTest │ │ │ └── StreamTest.java │ │ │ └── syntax │ │ │ ├── Syntax1.java │ │ │ └── Syntax2.java │ │ └── resources │ │ └── application.properties └── target │ └── classes │ └── com │ └── example │ └── springbootdemotest │ └── proxy │ ├── clibPackage │ ├── MainClass.class │ ├── ProxyFactory.class │ └── Singer.class │ ├── jdkPackage │ ├── ISinger.class │ ├── MainClass$1.class │ ├── MainClass.class │ └── Singer.class │ └── staticPacakge │ ├── ISinger.class │ ├── MainClass.class │ ├── Singer.class │ └── SingerProxy.class ├── springbootdemo-thread ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── springbootdemothread │ │ ├── BlockQueueTest.java │ │ ├── ConcurrentContainer │ │ └── ContainerTest.java │ │ ├── controller │ │ ├── HttpReqController.java │ │ ├── ThreadPoolController.java │ │ └── UserController.java │ │ ├── dao │ │ └── UserMapper.java │ │ ├── entity │ │ ├── Consumer.java │ │ ├── Producer.java │ │ ├── ThreadEntity.java │ │ ├── ThreadEntity2.java │ │ └── ThreadTestEntity.java │ │ ├── execption │ │ ├── ExecptionController.java │ │ └── RejectedExecutionHandler.java │ │ ├── producerAndConsumer02 │ │ └── ProducerAndConsumer.java │ │ ├── productAndConsumer │ │ ├── productAndConsumerDemo01 │ │ │ ├── Consumer.java │ │ │ ├── Producer.java │ │ │ ├── ProducerAndConsumserTest.java │ │ │ ├── Product.java │ │ │ └── Storage.java │ │ └── productAndConsumerDemo02 │ │ │ ├── Consumer.java │ │ │ ├── Produce.java │ │ │ ├── Product.java │ │ │ └── ProductAndConsumerDemo02.java │ │ ├── service │ │ └── UserService.java │ │ └── utils │ │ ├── HttpUtils.java │ │ └── WriteUtils.java │ └── resources │ ├── application.yml │ └── mapper │ └── UserMapper.xml └── springbootdemo-token ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── springbootdemotoken │ │ ├── SpringbootdemoTokenApplication.java │ │ ├── consts │ │ ├── HttpConst.java │ │ └── SysConst.java │ │ ├── exceptions │ │ ├── BaseException.java │ │ └── TokenException.java │ │ ├── extend │ │ ├── BodyReaderHttpRequestWrapper.java │ │ └── BodyReaderHttpResponseWrapper.java │ │ ├── filter │ │ ├── BaseFilter.java │ │ └── TokenFilter.java │ │ ├── redis │ │ ├── JedisClusterConfig.java │ │ └── RedisProperties.java │ │ ├── tokens │ │ └── JsonWebToken.java │ │ ├── utils │ │ ├── FileUtils.java │ │ ├── HttpUtils.java │ │ ├── RedisCacheUtil.java │ │ ├── StrUtil.java │ │ └── TimeUtils.java │ │ └── webController │ │ └── WebController.java └── resources │ ├── application.yml │ └── static │ └── tokenWhite.txt └── test └── java └── com └── example └── springbootdemotoken └── SpringbootdemoTokenApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # springbootdemo 2 | springboot2.0+springcloud+eureka+fegin demo 3 | springboot分布式项目demo,主要使用了springboot2.0+ springcloud(Finchley.SR1)+eureka+fegin完成一个分布式的微服务项目; 4 | -------------------------------------------------------------------------------- /desing-pattern/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | desing-pattern 13 | 0.0.1-SNAPSHOT 14 | desing-pattern 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 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 | 43 | 44 | -------------------------------------------------------------------------------- /desing-pattern/src/main/java/com/example/desingpattern/DesingPatternApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.desingpattern; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DesingPatternApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DesingPatternApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /desing-pattern/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /desing-pattern/src/test/java/com/example/desingpattern/DesingPatternApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.desingpattern; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DesingPatternApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /elastic-search/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | elastic-search 13 | 0.0.1-SNAPSHOT 14 | elastic-search 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 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 | 43 | 44 | -------------------------------------------------------------------------------- /elastic-search/src/main/java/com/example/elasticsearch/ElasticSearchApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.elasticsearch; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ElasticSearchApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ElasticSearchApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /elastic-search/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /elastic-search/src/test/java/com/example/elasticsearch/ElasticSearchApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.elasticsearch; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ElasticSearchApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | pom 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.1.3.RELEASE 10 | 11 | 12 | com.example 13 | springbootdemo 14 | 0.0.1-SNAPSHOT 15 | springbootdemo 16 | Demo project for Spring Boot 17 | 18 | 1.8 19 | 20 | 21 | springbootdemo-entity 22 | springbootdemo-consumer 23 | springbootdemo-product 24 | springbootdemo-eureka 25 | springbootdemo-foundation 26 | springbootdemo-test 27 | springbootdemo-rabbitmq 28 | desing-pattern 29 | 30 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-web 64 | 65 | 69 | 70 | 71 | 75 | 76 | 77 | org.springframework.cloud 78 | spring-cloud-starter-netflix-eureka-client 79 | 80 | 81 | 82 | org.apache.tomcat.embed 83 | tomcat-embed-jasper 84 | 85 | 86 | 87 | 88 | javax.servlet 89 | jstl 90 | 91 | 92 | javax.servlet 93 | javax.servlet-api 94 | provided 95 | 96 | 97 | 98 | org.projectlombok 99 | lombok 100 | 101 | 102 | 103 | 104 | org.projectlombok 105 | lombok 106 | 107 | 108 | 109 | 110 | 111 | 112 | org.springframework.cloud 113 | spring-cloud-dependencies 114 | Finchley.SR1 115 | pom 116 | import 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | org.springframework.boot 125 | spring-boot-maven-plugin 126 | 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /springbootdemo-consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-consumer 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-consumer 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | com.example 24 | springbootdemo-entity 25 | 0.0.1-SNAPSHOT 26 | compile 27 | 28 | 29 | org.springframework.cloud 30 | spring-cloud-starter-openfeign 31 | 32 | 33 | org.apache.tomcat.embed 34 | tomcat-embed-jasper 35 | 36 | 37 | redis.clients 38 | jedis 39 | 40 | 41 | 42 | 43 | 44 | 45 | com.alibaba 46 | druid 47 | 1.1.0 48 | 49 | 50 | 51 | mysql 52 | mysql-connector-java 53 | runtime 54 | 55 | 56 | 57 | org.mybatis.spring.boot 58 | mybatis-spring-boot-starter 59 | 1.3.1 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/SpringbootdemoConsumerApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 6 | import org.springframework.cloud.openfeign.EnableFeignClients; 7 | import org.springframework.context.annotation.ComponentScan; 8 | 9 | @SpringBootApplication 10 | @EnableEurekaClient 11 | @EnableFeignClients 12 | /** 13 | * 在多模块项目中,需要用到其他模块中的对象时,需要添加@ComponentScan注解,value指的是对应的包, 14 | * 这样才能把相关的对象引入过来,不然项目启动时会报错(此处的报错针对的时consumer项目启动时,redis报错,无法注入, 15 | * 加入该注解即可将redis注入到到该module中; 16 | */ 17 | @ComponentScan(value = "com.example.*") 18 | public class SpringbootdemoConsumerApplication { 19 | 20 | public static void main(String[] args) { 21 | SpringApplication.run(SpringbootdemoConsumerApplication.class, args); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/config/webConfig/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.config.webConfig; 2 | 3 | 4 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 5 | import org.springframework.boot.web.server.WebServerFactoryCustomizer; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import java.io.File; 10 | 11 | /** 12 | * @Title: WebConfig 13 | * @ProjectName springbootdemo 14 | * @Description: spring boot 父子工程中子工程整合jsp页面配置类,该类将子模块的webapp相对路径添加到tomcat的文件路径中; 15 | * @author YangPeng 16 | * @company ccxcredit 17 | * @date 2019/4/4-17:38 18 | */ 19 | @Configuration 20 | public class WebConfig { 21 | @Bean 22 | public WebServerFactoryCustomizer customizer() { 23 | return (factory) -> { 24 | factory.addContextCustomizers((context) -> { 25 | //模块中webapp相对路径 26 | String relativePath = "springbootdemo-consumer/src/main/webapp"; 27 | File docBaseFile = new File(relativePath); 28 | // 路径是否存在 29 | if (docBaseFile.exists()) { 30 | context.setDocBase(docBaseFile.getAbsolutePath()); 31 | } 32 | } 33 | ); 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/controller/ConsumerController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.controller; 2 | 3 | 4 | import com.example.springbootdemoconsumer.service.ProductService; 5 | import com.example.springbootdemoentity.entity.Consumer; 6 | import com.netflix.discovery.converters.Auto; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * @Title: ConsumerController 14 | * @ProjectName springbootdemo 15 | * @Description: TODO 16 | * @author YangPeng 17 | * @date 2019/3/27-11:32 18 | */ 19 | @RestController 20 | public class ConsumerController { 21 | @Autowired 22 | private ProductService productService; 23 | 24 | 25 | //使用@Value注解可以直接获取配置文件中的属性并注入到spring容器中; 26 | @Autowired 27 | @Value("${name}") 28 | private String name; 29 | 30 | @RequestMapping(value = "getConsumer") 31 | public String getConsumer(){ 32 | String str = productService.getProduct(); 33 | Consumer consumer = new Consumer(); 34 | System.out.println(consumer.toString()); 35 | System.out.println(consumer.getAdd()); 36 | System.out.println(consumer.getAge()); 37 | consumer.setAge(12333); 38 | System.out.println(consumer.getAge()); 39 | System.out.println(name); 40 | return str; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/controller/ErrorController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.controller; 2 | 3 | 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * @Title: ErrorController 9 | * @ProjectName springbootdemo 10 | * @Description: 测试全局异常处理controller 11 | * @author YangPeng 12 | * @date 2019/3/27-18:07 13 | */ 14 | @RestController 15 | public class ErrorController { 16 | @RequestMapping(value = "/getErrorMsg") 17 | public String getErrorMsg(Integer n,Integer m){ 18 | int i = n/m; 19 | System.out.println(i); 20 | return i+""; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/controller/JspController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.controller; 2 | 3 | 4 | import com.example.springbootdemoentity.config.repeatCommitConfig.AvoidRepeatableCommit; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | /** 9 | * @Title: JspController 10 | * @ProjectName springbootdemo 11 | * @Description: jsp跳转controller 12 | * @author YangPeng 13 | * @date 2019/4/4-17:19 14 | */ 15 | @Controller 16 | public class JspController { 17 | @AvoidRepeatableCommit 18 | @RequestMapping(value = "/getJsp") 19 | public String getJsp(){ 20 | return "index"; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/controller/RedisController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.controller; 2 | 3 | 4 | import com.example.springbootdemoentity.redisConfig.JedisClientCluster; 5 | import com.example.springbootdemoentity.redisConfig.RedisConfig; 6 | import com.example.springbootdemoentity.redisConfig.RedisProperties; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * @Title: RedisController 13 | * @ProjectName springbootdemo 14 | * @Description: TODO 15 | * @author YangPeng 16 | * @date 2019/4/3-17:55 17 | */ 18 | @RestController 19 | public class RedisController { 20 | @Autowired 21 | private RedisProperties redisProperties; 22 | 23 | @Autowired 24 | private RedisConfig redisConfig; 25 | 26 | @Autowired 27 | private JedisClientCluster jedisClientCluster; 28 | 29 | @RequestMapping(value = "getRedisValue") 30 | public String getRedisValue(){ 31 | System.out.println(redisProperties.toString()); 32 | System.out.println(redisConfig.getJedisCluster().getClusterNodes()); 33 | System.out.println(jedisClientCluster.get("yp")); 34 | jedisClientCluster.set("12","yangpeng"); 35 | jedisClientCluster.set("121212","yangpeng"); 36 | System.out.println(jedisClientCluster.get("12")); 37 | return jedisClientCluster.get("12"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.controller; 2 | 3 | import com.example.springbootdemoconsumer.service.UserService; 4 | import com.example.springbootdemoentity.entity.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class UserController { 11 | @Autowired 12 | private UserService userService; 13 | 14 | @RequestMapping(value = "/getUser") 15 | public String getUser() { 16 | System.out.println("调用getUser方法"); 17 | User user = userService.getUser(); 18 | System.out.println(user.toString()); 19 | return user.toString(); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/dao/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.dao; 2 | 3 | 4 | import com.example.springbootdemoentity.entity.User; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Mapper 9 | @Component 10 | public interface UserMapper { 11 | User getUser(); 12 | } 13 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/execption/ExecptionController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.execption; 2 | 3 | 4 | import org.springframework.web.bind.annotation.ControllerAdvice; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * @Title: ExecptionController 13 | * @ProjectName springbootdemo 14 | * @Description: TODO 15 | * @author YangPeng 16 | * @date 2019/3/27-17:30 17 | */ 18 | 19 | /** 20 | * @ControllerAdvice(basePackages = "com.example") 注解不添加basePackages 表示加了@Controller和@RestController都能控制 21 | */ 22 | @ControllerAdvice 23 | public class ExecptionController { 24 | 25 | @ResponseBody 26 | @ExceptionHandler(value = Exception.class) 27 | public Map excptionhandler(Exception ex) { 28 | HashMap map = new HashMap<>(); 29 | 30 | map.put("errorCode", "500"); 31 | map.put("errorMsg", "系统内部错误"); 32 | map.put("errorInfo", ex.getMessage()); 33 | 34 | return map; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/service/ProductService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.service; 2 | 3 | 4 | import org.springframework.cloud.openfeign.FeignClient; 5 | import org.springframework.stereotype.Component; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | /** 9 | * @author YangPeng 10 | * @Title: ProductService 11 | * @ProjectName springbootdemo 12 | * @Description: TODO 13 | * @date 2019/3/27-11:23 14 | */ 15 | //name 为product项目中application.yml配置文件中的application.name; 16 | //path 为product项目中application.yml配置文件中的context.path; 17 | @FeignClient(name = "product-server",path ="/product" ) 18 | @Component 19 | public interface ProductService { 20 | @RequestMapping(value = "getProduct") 21 | String getProduct(); 22 | } 23 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/java/com/example/springbootdemoconsumer/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoconsumer.service; 2 | 3 | import com.example.springbootdemoconsumer.dao.UserMapper; 4 | import com.example.springbootdemoentity.entity.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class UserService { 10 | @Autowired 11 | private UserMapper userMapper; 12 | 13 | public User getUser(){ 14 | return userMapper.getUser(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | #server: 2 | # servlet: 3 | # # 定义项目的访问访问路径 4 | # context-path: /consumer 5 | # #定义端口号 6 | # port: 7001 7 | spring: 8 | redis: 9 | cluster: 10 | #设置key的生存时间,当key过期时,它会被自动删除; 11 | expire-seconds: 120 12 | #设置命令的执行时间,如果超过这个时间,则报错; 13 | command-timeout: 5000 14 | #设置redis集群的节点信息,其中namenode为域名解析,通过解析域名来获取相应的地址; 15 | nodes: namenode22:6379,datanode23:6379,datanode24:6379,datanode25:6379,datanode26:6379,datanode27:6379 16 | application: 17 | #定义应用名称,即服务名称 18 | name: consumer-server 19 | mvc: 20 | view: 21 | suffix: .jsp 22 | prefix: /WEB-INF/jsp/ 23 | 24 | #数据库配置 25 | datasource: 26 | url: jdbc:mysql://localhost:3306/mysql?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 27 | username: root 28 | password: 5Wy43g&mvI+u 29 | # 使用druid数据源 30 | #type: com.alibaba.druid.pool.DruidDataSource 31 | main: 32 | allow-bean-definition-overriding: true 33 | #eureka配置 34 | eureka: 35 | client: 36 | service-url: 37 | defaultZone: http://localhost:5060/eureka/eureka 38 | server: 39 | servlet: 40 | # 定义项目的访问访问路径 41 | context-path: /consumer 42 | #定义端口号 43 | port: 7001 44 | 45 | #mybatis中mapper配置文件位置扫描 46 | mybatis: 47 | mapper-locations: classpath:mapper/*.xml 48 | 49 | name: name 50 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/resources/application-pre.yml: -------------------------------------------------------------------------------- 1 | server: 2 | servlet: 3 | # 定义项目的访问访问路径 4 | context-path: /consumer 5 | #定义端口号 6 | port: 7002 7 | spring: 8 | redis: 9 | cluster: 10 | #设置key的生存时间,当key过期时,它会被自动删除; 11 | expire-seconds: 120 12 | #设置命令的执行时间,如果超过这个时间,则报错; 13 | command-timeout: 5000 14 | #设置redis集群的节点信息,其中namenode为域名解析,通过解析域名来获取相应的地址; 15 | nodes: namenode22:6379,datanode23:6379,datanode24:6379,datanode25:6379,datanode26:6379,datanode27:6379 16 | application: 17 | #定义应用名称,即服务名称 18 | name: consumer-server 19 | eureka: 20 | client: 21 | service-url: 22 | defaultZone: http://localhost:5060/eureka/eureka 23 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/resources/application-uat.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-consumer/src/main/resources/application-uat.yml -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #spring.profiles.active表示启用哪一个配置文件,并且可以同时配置多个配置文件,同时启用多个配置文件 2 | spring: 3 | profiles: 4 | active: dev 5 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/webapp/WEB-INF/jsp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | 4 | 5 | 6 | Full Layout - jQuery EasyUI Demo 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /springbootdemo-consumer/src/main/webapp/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | -------------------------------------------------------------------------------- /springbootdemo-entity/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-entity 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-entity 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | redis.clients 23 | jedis 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/config/repeatCommitConfig/AvoidRepeatableCommit.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.config.repeatCommitConfig; 2 | 3 | 4 | import java.lang.annotation.*; 5 | 6 | /** 7 | * @author YangPeng 8 | * @Title: AvoidRepeatableCommit 9 | * @ProjectName springbootdemo 10 | * @Description: 编写一个自定义注解 11 | * @company ccxcredit 12 | * @date 2019/4/8-11:43 13 | */ 14 | @Target(ElementType.METHOD) 15 | @Documented 16 | @Retention(RetentionPolicy.RUNTIME) 17 | public @interface AvoidRepeatableCommit { 18 | long timeout() default 3000; 19 | } 20 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/config/repeatCommitConfig/AvoidRepeatableCommitAspect.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.config.repeatCommitConfig; 2 | 3 | 4 | import com.example.springbootdemoentity.redisConfig.JedisClientCluster; 5 | import org.apache.commons.lang.StringUtils; 6 | import org.aspectj.lang.ProceedingJoinPoint; 7 | import org.aspectj.lang.annotation.Around; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.reflect.MethodSignature; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.context.request.RequestContextHolder; 13 | import org.springframework.web.context.request.ServletRequestAttributes; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | import java.lang.reflect.Method; 17 | import java.util.UUID; 18 | 19 | /** 20 | * @Title: AvoidRepeatableCommitAspect 21 | * @ProjectName springbootdemo 22 | * @Description: 对自定义注解进行切面编程,该注解为防止接口重复提交的注解 23 | * @author YangPeng 24 | * @company ccxcredit 25 | * @date 2019/4/8-11:44 26 | */ 27 | 28 | @Aspect 29 | @Component 30 | public class AvoidRepeatableCommitAspect { 31 | @Autowired 32 | private JedisClientCluster redisTemplate; 33 | /** 34 | * 实现逻辑: 35 | * 1、当客户端请求接口时,获取接口的ip地址、接口访问方法等信息,并将以上信息按照某种格式进行处理,得到一个字符串; 36 | * 2、以字符串为key,value为自动生成的字符,将上述信息保存到reids中,并保持3s(相关指令为setx),超过3s后该信息就被删除; 37 | * 3、当用户每次请求时都会生成key,并根据key查询是否存在value,如果存在,则表示该接口在3s内被同一个ip进行了多次请求,则返回相关信息, 38 | * 4、否则该请求能够正常执行,即某一用户3s内第一次请求该接口; 39 | */ 40 | @Around("@annotation(com.example.springbootdemoentity.config.repeatCommitConfig.AvoidRepeatableCommit)") 41 | public Object around(ProceedingJoinPoint point) throws Throwable { 42 | 43 | HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); 44 | //这里ip写死,生产上实际使用的时候需要获取ip地址; 45 | String ip = "10.0.3.116"; 46 | //获取注解 47 | MethodSignature signature = (MethodSignature) point.getSignature(); 48 | Method method = signature.getMethod(); 49 | //目标类、方法 50 | String className = method.getDeclaringClass().getName(); 51 | String name = method.getName(); 52 | String ipKey = String.format("%s#%s",className,name); 53 | int hashCode = Math.abs(ipKey.hashCode()); 54 | String key = String.format("%s_%d",ip,hashCode+2); 55 | AvoidRepeatableCommit avoidRepeatableCommit = method.getAnnotation(AvoidRepeatableCommit.class); 56 | //long timeout = avoidRepeatableCommit.timeout(); 57 | String value = redisTemplate.get(key); 58 | if (StringUtils.isNotBlank(value)){ 59 | System.out.println("请勿重新提交"); 60 | return "请勿重复提交"; 61 | } 62 | redisTemplate.setx(key,3,UUID.randomUUID().toString()); 63 | //执行方法 64 | Object object = point.proceed(); 65 | return object; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/entity/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.entity; 2 | 3 | 4 | import lombok.Data; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | /** 9 | * @author YangPeng 10 | * @Title: Product 11 | * @ProjectName springboot 12 | * @Description: 实体类使用@Data注解(该注解对应依赖为lombok,使用该注解可以省略getset方法、toString方法、构造方法等方法的书写 13 | * 使代码看起来更加整洁美观; 14 | * @date 2019/3/25-16:23 15 | */ 16 | @Data 17 | public class Consumer { 18 | 19 | private String name; 20 | private int age; 21 | private String add; 22 | private String email; 23 | 24 | public Consumer() { 25 | this.name = "name"; 26 | this.age = 12; 27 | this.add = "北京市历史互通"; 28 | this.email = "6666.qq.com"; 29 | } 30 | 31 | /* @Override 32 | public String toString() { 33 | return "Consumer{" + 34 | "name='" + name + '\'' + 35 | ", age=" + age + 36 | ", add='" + add + '\'' + 37 | ", email='" + email + '\'' + 38 | '}'; 39 | }*/ 40 | } 41 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/entity/Pool.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.entity; 2 | 3 | 4 | import lombok.Data; 5 | 6 | /** 7 | * @Title: Pool 8 | * @ProjectName springbootdemo 9 | * @Description: TODO 10 | * @author YangPeng 11 | * @company ccxcredit 12 | * @date 2019/4/12-16:03 13 | */ 14 | @Data 15 | public class Pool { 16 | private String id ; 17 | private String poid; 18 | private String name; 19 | private String creator; 20 | } 21 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/entity/Product.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.entity; 2 | 3 | 4 | import lombok.Data; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | /** 9 | * @author YangPeng 10 | * @Title: Product 11 | * @ProjectName springboot 12 | * @Description: TODO 13 | * @date 2019/3/25-16:23 14 | */ 15 | @Data 16 | public class Product { 17 | 18 | private String name; 19 | private int age; 20 | private String add; 21 | private String email; 22 | 23 | public Product() { 24 | this.name = "name"; 25 | this.age = 12; 26 | this.add = "北京市历史互通"; 27 | this.email = "6666.qq.com"; 28 | } 29 | 30 | /*@Override 31 | public String toString() { 32 | return "Product{" + 33 | "name='" + name + '\'' + 34 | ", age=" + age + 35 | ", add='" + add + '\'' + 36 | ", email='" + email + '\'' + 37 | '}'; 38 | }*/ 39 | } 40 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.entity; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class User { 7 | private String host; 8 | private String username; 9 | } 10 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/redisConfig/JedisClient.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.redisConfig; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: JedisClient 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @date 2019/4/3-18:29 10 | */ 11 | public interface JedisClient { 12 | String set(String key, String value); 13 | 14 | String get(String key); 15 | 16 | Boolean exists(String key); 17 | 18 | Long expire(String key, int seconds); 19 | 20 | Long ttl(String key); 21 | 22 | Long incr(String key); 23 | 24 | Long hset(String key, String field, String value); 25 | 26 | String hget(String key, String field); 27 | 28 | Long hdel(String key, String... field); 29 | 30 | void setx(String key,int seconds,String value); 31 | } 32 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/redisConfig/JedisClientCluster.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.redisConfig; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Component; 6 | import redis.clients.jedis.JedisCluster; 7 | 8 | /** 9 | * @Title: JedisClientCluster 10 | * @ProjectName springbootdemo 11 | * @Description: TODO 12 | * @author YangPeng 13 | * @date 2019/4/3-18:30 14 | */ 15 | @Component 16 | public class JedisClientCluster implements JedisClient { 17 | @Autowired 18 | private JedisCluster jedisCluster; 19 | 20 | @Override 21 | public String set(String key, String value) { 22 | return jedisCluster.set(key, value); 23 | } 24 | 25 | @Override 26 | public String get(String key) { 27 | return jedisCluster.get(key); 28 | } 29 | 30 | @Override 31 | public Boolean exists(String key) { 32 | return jedisCluster.exists(key); 33 | } 34 | 35 | @Override 36 | public Long expire(String key, int seconds) { 37 | return jedisCluster.expire(key, seconds); 38 | } 39 | 40 | @Override 41 | public Long ttl(String key) { 42 | return jedisCluster.ttl(key); 43 | } 44 | 45 | @Override 46 | public Long incr(String key) { 47 | return jedisCluster.incr(key); 48 | } 49 | 50 | @Override 51 | public Long hset(String key, String field, String value) { 52 | return jedisCluster.hset(key, field, value); 53 | } 54 | 55 | @Override 56 | public String hget(String key, String field) { 57 | return jedisCluster.hget(key, field); 58 | } 59 | 60 | @Override 61 | public Long hdel(String key, String... field) { 62 | return jedisCluster.hdel(key, field); 63 | } 64 | 65 | @Override 66 | public void setx(String key, int seconds, String value) { 67 | jedisCluster.setex(key,seconds,value); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/redisConfig/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.redisConfig; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import redis.clients.jedis.HostAndPort; 8 | import redis.clients.jedis.JedisCluster; 9 | 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | /** 14 | * @Title: RedisConfig 15 | * @ProjectName springbootdemo 16 | * @Description: TODO 17 | * @author YangPeng 18 | * @date 2019/4/3-18:17 19 | */ 20 | @Configuration 21 | public class RedisConfig { 22 | 23 | @Autowired 24 | private RedisProperties redisProperties; 25 | 26 | @Bean 27 | public JedisCluster getJedisCluster(){ 28 | //获取redis集群的ip及端口号等相关信息; 29 | String[] serverArray = redisProperties.getNodes().split(","); 30 | Set nodes = new HashSet<>(); 31 | 32 | //遍历add到HostAndPort中; 33 | for (String ipPort : serverArray) { 34 | String[] ipPortPair = ipPort.split(":"); 35 | nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim()))); 36 | } 37 | //构建对象并返回; 38 | return new JedisCluster(nodes, redisProperties.getCommandTimeout()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /springbootdemo-entity/src/main/java/com/example/springbootdemoentity/redisConfig/RedisProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoentity.redisConfig; 2 | 3 | 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.stereotype.Component; 6 | 7 | /** 8 | * @author YangPeng 9 | * @Title: RedisProperties 10 | * @ProjectName springbootdemo 11 | * @Description: 使用ConfigurationProperties注解读取yml文件中的字段值,并使用Component注入到spring容器中; 12 | * @date 2019/4/3-17:52 13 | */ 14 | //依赖注入 15 | @Component 16 | //该注解用于读取配置文件中的属性,其中prefix表示前缀; 17 | @ConfigurationProperties(prefix = "spring.redis.cluster") 18 | public class RedisProperties { 19 | private int expireSeconds; 20 | private String nodes; 21 | private int commandTimeout; 22 | 23 | public int getExpireSeconds() { 24 | return expireSeconds; 25 | } 26 | 27 | public void setExpireSeconds(int expireSeconds) { 28 | this.expireSeconds = expireSeconds; 29 | } 30 | 31 | public String getNodes() { 32 | return nodes; 33 | } 34 | 35 | public void setNodes(String nodes) { 36 | this.nodes = nodes; 37 | } 38 | 39 | public int getCommandTimeout() { 40 | return commandTimeout; 41 | } 42 | 43 | public void setCommandTimeout(int commandTimeout) { 44 | this.commandTimeout = commandTimeout; 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return "RedisProperties{" + 50 | "expireSeconds=" + expireSeconds + 51 | ", nodes='" + nodes + '\'' + 52 | ", commandTimeout=" + commandTimeout + 53 | '}'; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /springbootdemo-eureka/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.3.RELEASE 9 | 10 | 11 | com.example 12 | springbootdemo-eureka 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-eureka 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.cloud 25 | spring-cloud-starter-netflix-eureka-server 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.cloud 33 | spring-cloud-dependencies 34 | Finchley.SR1 35 | pom 36 | import 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /springbootdemo-eureka/src/main/java/com/example/springbootdemoeureka/SpringbootdemoEurekaApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoeureka; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | @SpringBootApplication 8 | @EnableEurekaServer 9 | public class SpringbootdemoEurekaApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringbootdemoEurekaApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-eureka/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 5060 3 | servlet: 4 | context-path: /eureka 5 | spring: 6 | application: 7 | name: eureka-server 8 | eureka: 9 | client: 10 | #是否启用湖区注册服务信息,因为这是一个单节点的EurekaServer,不需要同步其他的EurekaServer节点的数据,所以设置为false; 11 | fetch-registry: false 12 | #表示是否向eureka注册服务,即在自己的eureka中注册自己,默认为true,此处应该设置为false; 13 | register-with-eureka: true 14 | service-url: 15 | defaultZone: http://localhost:5060/eureka/eureka 16 | instance: 17 | hostname: localhost 18 | server: 19 | #设为false,关闭自我保护,即Eureka server在云心光器件会去统计心跳失败比例在15分钟之内是否低于85%,如果低于85%,EurekaServer 20 | #会将这些事例保护起来,让这些事例不会过期,但是在保护器内如果刚哈这个服务提供者非正常下线了,此时服务消费者会拿到一个无效的服务 21 | #实例,此时调用会失败,对于这个问题需要服务消费者端有一些容错机制,如重试、断路器等; 22 | enable-self-preservation: false 23 | #扫描失效服务的间隔时间(单位是毫秒,摩恩是60*1000),即60s 24 | eviction-interval-timer-in-ms: 10000 25 | -------------------------------------------------------------------------------- /springbootdemo-filter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.3.RELEASE 9 | 10 | 11 | com.example 12 | springbootdemo-filter 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-filter 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | org.junit.vintage 34 | junit-vintage-engine 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/java/com/example/springbootdemofilter/SpringbootdemoFilterApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofilter; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.ComponentScan; 7 | 8 | @SpringBootApplication 9 | public class SpringbootdemoFilterApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringbootdemoFilterApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/java/com/example/springbootdemofilter/configure/Configuration.java: -------------------------------------------------------------------------------- 1 | //package com.example.springbootdemofilter.configure; 2 | // 3 | // 4 | //import com.example.springbootdemofilter.filterTest.FirstFilter; 5 | //import com.example.springbootdemofilter.filterTest.SecondFilter; 6 | //import org.springframework.boot.web.servlet.FilterRegistrationBean; 7 | //import org.springframework.context.annotation.Bean; 8 | // 9 | //@org.springframework.context.annotation.Configuration 10 | //public class Configuration { 11 | // @Bean 12 | // public FilterRegistrationBean FirstFilterRegister() { 13 | // FilterRegistrationBean registration = new FilterRegistrationBean(); 14 | // //注入过滤器 15 | // registration.setFilter(new FirstFilter()); 16 | // //拦截规则 17 | // registration.addUrlPatterns("/*"); 18 | // //过滤器名称 19 | // registration.setName("firstFilter"); 20 | // //过滤器顺序 21 | // registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); 22 | // return registration; 23 | // } 24 | // @Bean 25 | // public FilterRegistrationBean SecondFilterRegister() { 26 | // FilterRegistrationBean registration = new FilterRegistrationBean(); 27 | // //注入过滤器 28 | // registration.setFilter(new SecondFilter()); 29 | // //拦截规则 30 | // registration.addUrlPatterns("/*"); 31 | // //过滤器名称 32 | // registration.setName("secondFilter"); 33 | // //过滤器顺序 34 | // registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); 35 | // return registration; 36 | // } 37 | //} 38 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/java/com/example/springbootdemofilter/controller/WebController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofilter.controller; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.ResponseBody; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | public class WebController { 9 | @RequestMapping(value = "/filterTest") 10 | public String filterTest(){ 11 | return "filter test success"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/java/com/example/springbootdemofilter/filterTest/FirstFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofilter.filterTest; 2 | 3 | import org.springframework.core.annotation.Order; 4 | import org.springframework.stereotype.Component; 5 | 6 | import javax.servlet.*; 7 | import javax.servlet.annotation.WebFilter; 8 | import java.io.IOException; 9 | 10 | @Order(1) 11 | @WebFilter(filterName="firstFilter", urlPatterns="/*") 12 | @Component 13 | public class FirstFilter implements Filter { 14 | 15 | @Override 16 | public void init(FilterConfig filterConfig) throws ServletException { 17 | 18 | } 19 | 20 | @Override 21 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 22 | System.out.println("first filter 1"); 23 | filterChain.doFilter(servletRequest, servletResponse); 24 | System.out.println("first filter 2"); 25 | } 26 | 27 | @Override 28 | public void destroy() { 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/java/com/example/springbootdemofilter/filterTest/SecondFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofilter.filterTest; 2 | 3 | import org.springframework.core.annotation.Order; 4 | import org.springframework.stereotype.Component; 5 | 6 | import javax.servlet.*; 7 | import javax.servlet.annotation.WebFilter; 8 | import java.io.IOException; 9 | 10 | @Order(2) 11 | @WebFilter(filterName="secondFilter", urlPatterns="/*") 12 | @Component 13 | public class SecondFilter implements Filter { 14 | @Override 15 | public void init(FilterConfig filterConfig) throws ServletException { 16 | 17 | } 18 | 19 | @Override 20 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 21 | System.out.println("second filter 1"); 22 | System.out.println("before:" + servletResponse); 23 | filterChain.doFilter(servletRequest, servletResponse); 24 | System.out.println("after:" + servletResponse); 25 | System.out.println("second filter 2"); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /springbootdemo-filter/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | servlet: 3 | context-path: /filter -------------------------------------------------------------------------------- /springbootdemo-foundation/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-foundation 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-foundation 15 | java foundation module 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | com.alibaba 34 | tools 35 | RELEASE 36 | test 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/main/java/com/example/springbootdemofoundation/SpringbootdemoFoundationApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootdemoFoundationApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootdemoFoundationApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/SpringbootdemoFoundationApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation; 2 | 3 | import com.example.springbootdemofoundation.entity.AbstractEntity; 4 | import com.example.springbootdemofoundation.entity.InterfaceEntity; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | @RunWith(SpringRunner.class) 11 | @SpringBootTest 12 | public class SpringbootdemoFoundationApplicationTests { 13 | 14 | @Test 15 | public void contextLoads() { 16 | int a = InterfaceEntity.a; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/Test.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation; 2 | 3 | 4 | /** 5 | * @Title: Test 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-11:31 11 | */ 12 | public class Test { 13 | public static void main(String[] args) { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/AbsExexEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: AbsExexEntity 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-14:24 11 | */ 12 | public class AbsExexEntity extends AbsExtendsEntity { 13 | @Override 14 | public void interfaceMethod() { 15 | 16 | } 17 | 18 | @Override 19 | void extendsMethod() { 20 | 21 | } 22 | 23 | @Override 24 | void abstractMethod() { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/AbsExtendsEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: AbsExtendsEntity 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-14:05 11 | */ 12 | public abstract class AbsExtendsEntity extends AbstractEntity implements InterfaceEntity { 13 | abstract void extendsMethod(); 14 | } 15 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/AbstractEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: AbstractEntity 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-11:03 11 | */ 12 | 13 | /** 14 | * 抽象类无法被实例化; 15 | */ 16 | public abstract class AbstractEntity { 17 | abstract void abstractMethod(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/InterfaceEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: InterfaceEntity 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-10:54 11 | */ 12 | public interface InterfaceEntity { 13 | void interfaceMethod(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/InterfaceEntity2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: InterfaceEntity2 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-14:35 11 | */ 12 | public interface InterfaceEntity2 { 13 | String interfaceMethod(); 14 | } 15 | -------------------------------------------------------------------------------- /springbootdemo-foundation/src/test/java/com/example/springbootdemofoundation/entity/interfaceImpEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemofoundation.entity; 2 | 3 | 4 | /** 5 | * @Title: interfaceImpEntity 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/17-14:35 11 | */ 12 | public class interfaceImpEntity implements InterfaceEntity { 13 | 14 | @Override 15 | public void interfaceMethod() { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /springbootdemo-product/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-product 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-product 15 | Demo project for Spring Boot 16 | 17 | 1.8 18 | 19 | 20 | 21 | 22 | 23 | com.example 24 | springbootdemo-entity 25 | 0.0.1-SNAPSHOT 26 | compile 27 | 28 | 29 | org.springframework.cloud 30 | spring-cloud-starter-openfeign 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-freemarker 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-maven-plugin 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /springbootdemo-product/src/main/java/com/example/springbootdemoproduct/SpringbootdemoProductApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoproduct; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 6 | import org.springframework.cloud.openfeign.EnableFeignClients; 7 | 8 | @SpringBootApplication 9 | @EnableFeignClients 10 | @EnableEurekaClient 11 | public class SpringbootdemoProductApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringbootdemoProductApplication.class, args); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /springbootdemo-product/src/main/java/com/example/springbootdemoproduct/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoproduct.controller; 2 | 3 | 4 | import com.example.springbootdemoentity.entity.Product; 5 | import com.example.springbootdemoproduct.exception.MyException; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | 11 | /** 12 | * @author YangPeng 13 | * @Title: ProductController 14 | * @ProjectName springbootdemo 15 | * @Description: TODO 16 | * @date 2019/3/25-19:26 17 | */ 18 | @RestController 19 | public class ProductController { 20 | @RequestMapping(value = "getProduct") 21 | public String getProduct() { 22 | Product product = new Product(); 23 | return product.toString(); 24 | } 25 | 26 | @RequestMapping(value = "/home") 27 | public String home(){ 28 | System.out.println("123111"); 29 | throw new MyException("101","错误"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /springbootdemo-product/src/main/java/com/example/springbootdemoproduct/exception/MyControllerAdvice.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoproduct.exception; 2 | 3 | 4 | import org.springframework.web.bind.annotation.ControllerAdvice; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.servlet.ModelAndView; 7 | 8 | /** 9 | * @Title: MyControllerAdvice 10 | * @ProjectName springbootdemo 11 | * @Description: TODO 12 | * @author YangPeng 13 | * @date 2019/3/28-17:45 14 | */ 15 | @ControllerAdvice 16 | public class MyControllerAdvice { 17 | 18 | @ExceptionHandler(value = MyException.class) 19 | public ModelAndView errorHandler(MyException ex){ 20 | ModelAndView modelAndView = new ModelAndView(); 21 | modelAndView.setViewName("error"); 22 | modelAndView.addObject("code", ex.getCode()); 23 | modelAndView.addObject("msg", ex.getMsg()); 24 | return modelAndView; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /springbootdemo-product/src/main/java/com/example/springbootdemoproduct/exception/MyException.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemoproduct.exception; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: MyException 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @date 2019/3/28-17:36 10 | */ 11 | public class MyException extends RuntimeException { 12 | public MyException(String code, String msg) { 13 | this.code = code; 14 | this.msg = msg; 15 | } 16 | 17 | public String getCode() { 18 | return code; 19 | } 20 | 21 | public void setCode(String code) { 22 | this.code = code; 23 | } 24 | 25 | public String getMsg() { 26 | return msg; 27 | } 28 | 29 | public void setMsg(String msg) { 30 | this.msg = msg; 31 | } 32 | 33 | private String code; 34 | private String msg; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-product/src/main/resources/application.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-product/src/main/resources/application.yml -------------------------------------------------------------------------------- /springbootdemo-product/src/main/resources/templates/error.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 错误页面 6 | 7 | 8 |

${code}

9 |

${msg}

10 | 11 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-rabbitmq 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-rabbitmq 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | com.rabbitmq 24 | amqp-client 25 | 4.8.0 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-maven-plugin 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/RabbitMQDemo02/Readme.md: -------------------------------------------------------------------------------- 1 | RabbitMQ的“Work”模式demo; 2 | 只有一个生产者,有多个消费者,且一个消息只能被一个消费者消费; -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/RabbitMQDemo02/util/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemorabbitmq.RabbitMQDemo02.util; 2 | 3 | 4 | /** 5 | * @Title: ConnectionUtil 6 | * @ProjectName springbootdemo 7 | * @Description: 获取RabbitMQ连接工具类; 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/28-11:27 11 | */ 12 | public class ConnectionUtil { 13 | private static final String QUEUE_NAME = "QUEUE_NAME"; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/SpringbootdemoRabbitmqApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemorabbitmq; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootdemoRabbitmqApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootdemoRabbitmqApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/rabbitMQDemo01/Readme.md: -------------------------------------------------------------------------------- 1 | demo01为RabbitMQ的简单模式,即发送消息、接收消息的模式 -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/rabbitMQDemo01/entity/ConsumerEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemorabbitmq.rabbitMQDemo01.entity; 2 | 3 | 4 | import com.example.springbootdemorabbitmq.rabbitMQDemo01.util.ConnectionUtil; 5 | import com.rabbitmq.client.Channel; 6 | import com.rabbitmq.client.Connection; 7 | import com.rabbitmq.client.QueueingConsumer; 8 | 9 | import java.io.IOException; 10 | 11 | /** 12 | * @author YangPeng 13 | * @Title: ConsumerEntity 14 | * @ProjectName springbootdemo 15 | * @Description: TODO 16 | * @company ccxcredit 17 | * @date 2019/5/28-11:12 18 | */ 19 | public class ConsumerEntity { 20 | private final static String QUEUE_NAME = "QUEUE_A"; 21 | 22 | public static void main(String[] args) throws IOException, InterruptedException { 23 | //获取到连接及MQ通道 24 | Connection connection = ConnectionUtil.getConnection(); 25 | //从连接中创建通道 26 | Channel channel = connection.createChannel(); 27 | //声明队列 28 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 29 | 30 | //定义队列的消费者 31 | QueueingConsumer queueingConsumer = new QueueingConsumer(channel); 32 | //监听队列; 33 | channel.basicConsume(QUEUE_NAME,true,queueingConsumer); 34 | while (true){ 35 | QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery(); 36 | String message = new String(delivery.getBody()); 37 | System.out.println(" [x] Received '" + message + "'"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/rabbitMQDemo01/entity/ProductEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemorabbitmq.rabbitMQDemo01.entity; 2 | 3 | 4 | import com.example.springbootdemorabbitmq.rabbitMQDemo01.util.ConnectionUtil; 5 | import com.rabbitmq.client.Channel; 6 | import com.rabbitmq.client.Connection; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * @Title: SendEntity 12 | * @ProjectName springbootdemo 13 | * @Description: 生产者向消费队列发送消息 14 | * @author YangPeng 15 | * @company ccxcredit 16 | * @date 2019/5/28-10:54 17 | */ 18 | public class ProductEntity { 19 | //定义一个消息队列的名称; 20 | private final static String QUEUE_NAME = "QUEUE_A"; 21 | 22 | public static void main(String[] args) throws IOException { 23 | //获取连接及MQ通道; 24 | Connection connection = ConnectionUtil.getConnection(); 25 | //从连接中创建通道 26 | Channel channel = connection.createChannel(); 27 | //声明(创建)队列 28 | channel.queueDeclare(QUEUE_NAME,false,false,false,null); 29 | //消息内容 30 | String message = "hello world"; 31 | //发布消息 32 | channel.basicPublish("",QUEUE_NAME,null,message.getBytes()); 33 | System.out.println(" [x]Sent'"+message+"'"); 34 | //关闭通道和连接 35 | channel.close(); 36 | connection.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/java/com/example/springbootdemorabbitmq/rabbitMQDemo01/util/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemorabbitmq.rabbitMQDemo01.util; 2 | 3 | import com.rabbitmq.client.Connection; 4 | import com.rabbitmq.client.ConnectionFactory; 5 | 6 | import java.io.IOException; 7 | 8 | /** 9 | * @Title: ConnectionUtil 10 | * @ProjectName springbootdemo 11 | * @Description: 获取RabbitMQ连接工具类 12 | * @author YangPeng 13 | * @company ccxcredit 14 | * @date 2019/5/28-10:43 15 | */ 16 | public class ConnectionUtil { 17 | public static Connection getConnection() throws IOException { 18 | //定义连接工厂 19 | ConnectionFactory factory = new ConnectionFactory(); 20 | //设置服务地址 21 | factory.setHost("localhost"); 22 | //设置端口号 23 | factory.setPort(5672); 24 | //设置账号信息、用户名、密码、vhost信息; 25 | factory.setVirtualHost("/admin_yangpeng"); 26 | factory.setUsername("yangpeng"); 27 | factory.setPassword("1qaz@WSX"); 28 | //获取连接 29 | Connection connection = factory.newConnection(); 30 | return connection; 31 | } 32 | 33 | 34 | /** 35 | * 测试连接RabbitMQ是否成功 36 | * @param args 37 | * @throws IOException 38 | */ 39 | public static void main(String[] args) throws IOException { 40 | Connection con = getConnection(); 41 | System.out.println(con); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /springbootdemo-rabbitmq/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /springbootdemo-test/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-test 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-test 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | com.google.code.gson 28 | gson 29 | 2.2.4 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-test 34 | test 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-maven-plugin 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/DateTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest; 2 | 3 | 4 | import java.text.SimpleDateFormat; 5 | // 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | 9 | public class DateTest { 10 | 11 | private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 12 | 13 | public static void main(String[] args) { 14 | Calendar c = Calendar.getInstance(); 15 | Date now = c.getTime(); 16 | // 当前日期 17 | System.out.println("当前日期:\t" + format(c.getTime())); 18 | 19 | // 下个月的今天 20 | c.setTime(now); 21 | c.add(Calendar.MONTH, 1); 22 | System.out.println("下个月的今天:\t" +format(c.getTime())); 23 | 24 | // 去年的今天 25 | c.setTime(now); 26 | c.add(Calendar.YEAR, -1); 27 | System.out.println("去年的今天:\t" +format(c.getTime())); 28 | 29 | // 上个月的第三天 30 | c.setTime(now); 31 | c.add(Calendar.MONTH, -1); 32 | c.set(Calendar.DATE, 3); 33 | System.out.println("上个月的第三天:\t" +format(c.getTime())); 34 | 35 | } 36 | 37 | private static String format(Date time) { 38 | return sdf.format(time); 39 | } 40 | } -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/DoubleTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest; 2 | 3 | 4 | import org.springframework.util.StopWatch; 5 | 6 | import java.math.BigDecimal; 7 | 8 | /** 9 | * @Title: DoubleTest 10 | * @ProjectName springbootdemo 11 | * @Description: Double类型数据保留四位小数多种方法效率比较 12 | * @author YangPeng 13 | * @company ccxcredit 14 | * @date 2019/7/22-11:21 15 | */ 16 | public class DoubleTest { 17 | 18 | public static void main(String[] args) throws Exception { 19 | method1(); 20 | Thread.sleep(100); 21 | method2(); 22 | Thread.sleep(100); 23 | method3(); 24 | } 25 | 26 | 27 | private static void method1(){ 28 | double value =0.12345566; 29 | StopWatch stopWatch = new StopWatch(); 30 | stopWatch.start(); 31 | for(int i =0;i<100000000;i++){ 32 | value = (double) Math.round(value * 10000) / 10000; 33 | } 34 | stopWatch.stop(); 35 | System.out.println("使用Math.round方法,先转成int,再处以10000,10亿次用时为:"+stopWatch.toString()); 36 | } 37 | 38 | private static void method2(){ 39 | double value =0.12345566; 40 | StopWatch stopWatch = new StopWatch(); 41 | stopWatch.start(); 42 | for(int i =0;i<1000000;i++){ 43 | BigDecimal b = new BigDecimal(value); 44 | value = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); 45 | } 46 | stopWatch.stop(); 47 | System.out.println("使用Bigdecimal进行转换,10亿次用时为:"+stopWatch.toString()); 48 | } 49 | private static void method3(){ 50 | double value =0.12345566; 51 | StopWatch stopWatch = new StopWatch(); 52 | stopWatch.start(); 53 | for(int i =0;i<10000000;i++){ 54 | String stringValue=String.format("%.2f", value); 55 | } 56 | stopWatch.stop(); 57 | System.out.println("使用String进行转换,10亿次用时为:"+stopWatch.toString()); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/JsonFormatTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest; 2 | 3 | 4 | import com.google.gson.Gson; 5 | 6 | import java.util.*; 7 | 8 | /** 9 | * @author YangPeng 10 | * @Title: JsonFormatTest 11 | * @ProjectName springbootdemo 12 | * @Description: TODO 13 | * @company ccxcredit 14 | * @date 2019/7/31-9:38 15 | */ 16 | public class JsonFormatTest { 17 | public static void main(String[] args) { 18 | List> map = new ArrayList<>(); 19 | List> mapList = new ArrayList<>(); 20 | for(int i =0;i<10;i++){ 21 | Map map1 = new HashMap<>(); 22 | Map map2 = new LinkedHashMap<>(); 23 | map1.put("cashingDate","2019-08-09"); 24 | map1.put("trancheA","0"); 25 | map1.put("trancheB","0"); 26 | map1.put("trancheC","0"); 27 | map2.put("cashingDate","2019-08-09"); 28 | map2.put("trancheA","0"); 29 | map2.put("trancheB","0"); 30 | map2.put("trancheC","0"); 31 | map.add(map1); 32 | mapList.add(map2); 33 | } 34 | Gson gson = new Gson(); 35 | System.out.println(gson.toJson(map)); 36 | System.out.println(gson.toJson(mapList)); 37 | //格式如下: 38 | // [{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"},{"cashingDate":"2019-08-09","trancheB":"0","trancheA":"0","trancheC":"0"}] 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/SpringbootdemoTestApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | public class SpringbootdemoTestApplication { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(SpringbootdemoTestApplication.class, args); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/byteCode/Class文件二进制码: -------------------------------------------------------------------------------- 1 | cafe babe 0000 0034 005e 0a00 1900 320a 2 | 000d 0033 0a00 0d00 3409 0035 0036 0700 3 | 370a 0005 0032 0800 380a 0005 0039 0a00 4 | 1800 3a0a 0005 003b 0a00 3c00 3d0a 000d 5 | 003e 0700 3f0a 000d 0040 0800 4108 0042 6 | 0a00 0d00 4308 0044 0900 1800 450a 0015 7 | 003a 0700 4608 0047 0a00 1500 4807 0049 8 | 0700 4a01 0003 7364 6601 001c 4c6a 6176 9 | 612f 7465 7874 2f53 696d 706c 6544 6174 10 | 6546 6f72 6d61 743b 0100 063c 696e 6974 11 | 3e01 0003 2829 5601 0004 436f 6465 0100 12 | 0f4c 696e 654e 756d 6265 7254 6162 6c65 13 | 0100 124c 6f63 616c 5661 7269 6162 6c65 14 | 5461 626c 6501 0004 7468 6973 0100 294c 15 | 636f 6d2f 6578 616d 706c 652f 7370 7269 16 | 6e67 626f 6f74 6465 6d6f 7465 7374 2f44 17 | 6174 6554 6573 743b 0100 046d 6169 6e01 18 | 0016 285b 4c6a 6176 612f 6c61 6e67 2f53 19 | 7472 696e 673b 2956 0100 0461 7267 7301 20 | 0013 5b4c 6a61 7661 2f6c 616e 672f 5374 21 | 7269 6e67 3b01 0001 6301 0014 4c6a 6176 22 | 612f 7574 696c 2f43 616c 656e 6461 723b 23 | 0100 036e 6f77 0100 104c 6a61 7661 2f75 24 | 7469 6c2f 4461 7465 3b01 0010 4d65 7468 25 | 6f64 5061 7261 6d65 7465 7273 0100 0666 26 | 6f72 6d61 7401 0024 284c 6a61 7661 2f75 27 | 7469 6c2f 4461 7465 3b29 4c6a 6176 612f 28 | 6c61 6e67 2f53 7472 696e 673b 0100 0474 29 | 696d 6501 0008 3c63 6c69 6e69 743e 0100 30 | 0a53 6f75 7263 6546 696c 6501 000d 4461 31 | 7465 5465 7374 2e6a 6176 610c 001c 001d 32 | 0c00 4b00 4c0c 004d 004e 0700 4f0c 0050 33 | 0051 0100 176a 6176 612f 6c61 6e67 2f53 34 | 7472 696e 6742 7569 6c64 6572 0100 10e5 35 | bd93 e589 8de6 97a5 e69c 9fef bc9a 090c 36 | 0052 0053 0c00 2c00 2d0c 0054 0055 0700 37 | 560c 0057 0058 0c00 5900 5a01 0012 6a61 38 | 7661 2f75 7469 6c2f 4361 6c65 6e64 6172 39 | 0c00 5b00 5c01 0014 e4b8 8be4 b8aa e69c 40 | 88e7 9a84 e4bb 8ae5 a4a9 3a09 0100 11e5 41 | 8ebb e5b9 b4e7 9a84 e4bb 8ae5 a4a9 3a09 42 | 0c00 5d00 5c01 0017 e4b8 8ae4 b8aa e69c 43 | 88e7 9a84 e7ac ace4 b889 e5a4 a93a 090c 44 | 001a 001b 0100 1a6a 6176 612f 7465 7874 45 | 2f53 696d 706c 6544 6174 6546 6f72 6d61 46 | 7401 0013 7979 7979 2d4d 4d2d 6464 2048 47 | 483a 6d6d 3a73 730c 001c 0058 0100 2763 48 | 6f6d 2f65 7861 6d70 6c65 2f73 7072 696e 49 | 6762 6f6f 7464 656d 6f74 6573 742f 4461 50 | 7465 5465 7374 0100 106a 6176 612f 6c61 51 | 6e67 2f4f 626a 6563 7401 000b 6765 7449 52 | 6e73 7461 6e63 6501 0016 2829 4c6a 6176 53 | 612f 7574 696c 2f43 616c 656e 6461 723b 54 | 0100 0767 6574 5469 6d65 0100 1228 294c 55 | 6a61 7661 2f75 7469 6c2f 4461 7465 3b01 56 | 0010 6a61 7661 2f6c 616e 672f 5379 7374 57 | 656d 0100 036f 7574 0100 154c 6a61 7661 58 | 2f69 6f2f 5072 696e 7453 7472 6561 6d3b 59 | 0100 0661 7070 656e 6401 002d 284c 6a61 60 | 7661 2f6c 616e 672f 5374 7269 6e67 3b29 61 | 4c6a 6176 612f 6c61 6e67 2f53 7472 696e 62 | 6742 7569 6c64 6572 3b01 0008 746f 5374 63 | 7269 6e67 0100 1428 294c 6a61 7661 2f6c 64 | 616e 672f 5374 7269 6e67 3b01 0013 6a61 65 | 7661 2f69 6f2f 5072 696e 7453 7472 6561 66 | 6d01 0007 7072 696e 746c 6e01 0015 284c 67 | 6a61 7661 2f6c 616e 672f 5374 7269 6e67 68 | 3b29 5601 0007 7365 7454 696d 6501 0013 69 | 284c 6a61 7661 2f75 7469 6c2f 4461 7465 70 | 3b29 5601 0003 6164 6401 0005 2849 4929 71 | 5601 0003 7365 7400 2100 1800 1900 0000 72 | 0100 0a00 1a00 1b00 0000 0400 0100 1c00 73 | 1d00 0100 1e00 0000 2f00 0100 0100 0000 74 | 052a b700 01b1 0000 0002 001f 0000 0006 75 | 0001 0000 0009 0020 0000 000c 0001 0000 76 | 0005 0021 0022 0000 0009 0023 0024 0002 77 | 001e 0000 011f 0003 0003 0000 00ad b800 78 | 024c 2bb6 0003 4db2 0004 bb00 0559 b700 79 | 0612 07b6 0008 2bb6 0003 b800 09b6 0008 80 | b600 0ab6 000b 2b2c b600 0c2b 0504 b600 81 | 0eb2 0004 bb00 0559 b700 0612 0fb6 0008 82 | 2bb6 0003 b800 09b6 0008 b600 0ab6 000b 83 | 2b2c b600 0c2b 0402 b600 0eb2 0004 bb00 84 | 0559 b700 0612 10b6 0008 2bb6 0003 b800 85 | 09b6 0008 b600 0ab6 000b 2b2c b600 0c2b 86 | 0502 b600 0e2b 0806 b600 11b2 0004 bb00 87 | 0559 b700 0612 12b6 0008 2bb6 0003 b800 88 | 09b6 0008 b600 0ab6 000b b100 0000 0200 89 | 1f00 0000 3a00 0e00 0000 0e00 0400 0f00 90 | 0900 1100 2800 1400 2d00 1500 3300 1600 91 | 5200 1900 5700 1a00 5d00 1b00 7c00 1e00 92 | 8100 1f00 8700 2000 8d00 2100 ac00 2300 93 | 2000 0000 2000 0300 0000 ad00 2500 2600 94 | 0000 0400 a900 2700 2800 0100 0900 a400 95 | 2900 2a00 0200 2b00 0000 0501 0025 0000 96 | 000a 002c 002d 0002 001e 0000 0032 0002 97 | 0001 0000 0008 b200 132a b600 14b0 0000 98 | 0002 001f 0000 0006 0001 0000 0026 0020 99 | 0000 000c 0001 0000 0008 002e 002a 0000 100 | 002b 0000 0005 0100 2e00 0000 0800 2f00 101 | 1d00 0100 1e00 0000 2500 0300 0000 0000 102 | 0dbb 0015 5912 16b7 0017 b300 13b1 0000 103 | 0001 001f 0000 0006 0001 0000 000b 0001 104 | 0030 0000 0002 0031 -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/byteCode/class文件结构: -------------------------------------------------------------------------------- 1 | 第一部分:前四个字节 魔术: 2 | CA FE BA BE 3 | 第二部分:次版本号; 4 | 00 00(0) 5 | 第三部分:主版本号 6 | 00 34(3*16+4=52)——》对应版本号为jdk1.8;51对应的版本号为jdk1.7; 7 | 第四部分:常量池的个数,占两个字节; 8 | 00 19(16*1+9-1=24) 为什么-1?因为第0号常量被我们的JVM给占用了,表示的是什么都不引用; 9 | 10 | 常量池的分类:字面量类型,符号引用类型;每一种类型都有自己的结构;每一种结构的第一个字节:tag位(标记位); 11 | //java/lang/Object."":()V 没有参数,返回值为null; 12 | 常量池的第一个常量: 13 | 0A 00 04 00 15: methodref_info class_index 00 04(4) #4 00 15(21) #21(nameAndType_index); 14 | 第二个常量: 15 | 09 00 03 00 16: field_info 00 03 class_index #3 00 16(22)#22 16 | 第三个常量: 17 | 07 00 17 :class_info 00 17(23)#23 18 | 第四个常量: 19 | 07 00 18 :class_info 00 18(24)#24的位置; 20 | 第五个常量:01——》utf-8 len:00 08(8个字节),这8个字节表示的是字段描述名称,比如String name,这八个字节表示的是name 21 | 01 00 08 75 73 65 72 4E 61 6D 65; 22 | 第六个常量:class_info 00 12(18个字节)——》 java/lang/String; 23 | 01 00 12 4C 6A 61 76 61 2F 6C 61 6E 67 2F 53 74 69 6E 67 3B: 24 | 第七个常量:01 ——》utf-8 len: 00 06(6个字节)——》 表示的构造方法; 25 | 01 00 06 3C 69 6E 69 74 3E; 26 | 第八个常量:01——》utf-8 len:03(3个字节) ——》 ()V:构造方法的描述符,无参数,无返回值; 27 | 01 00 03 28 29 56; 28 | 第九个常量:01 ——》utf-8 len:00 04(4个字节)——》Code:属性表;在每个方法中都有一个Code属性表;包含的是JVM指令 29 | 01 00 04 42 6F 64 65; 30 | 第十个常量:01 ——》utf-8 len:00 0F(15个字节) ——》 LineNumbserTab(行号表):当抛出异常的时候,会定位到具体是某一行抛出异常,通过行号表来记录异常的行号; 31 | 行号表用来保存JVM指令与源码行号之间的映射关系; 32 | 01 00 0F 4C 69 6E 65 4E 75 6D 62 65 72 54 61 62 6C 65 33 | 第十一个常量:01——》utf-8 len:00 12(18个字节)——》LocalVariableTable(局部变量表):在编译的时候,局部变量表会把this当做第一个参数传递到局部变量表中,其他参数为第二个变量,参数多的时候,以此类推; 34 | 01 00 12 4c 69 6e 65 4e 75 6d 62 65 72 54 61 62 6c 65 01 00 35 | 在编译的时候,this对象会被当做参数传递到局部变量表中,因此在某个方法的时候,可以随便使用this关键字,来对当前对象进行操作; 36 | 第十二个参数:01 04(4个字节) ——》 this; 37 | 01 00 04 74 68 69 73 38 | 第十三个参数:utf8 len: 00 33(51个字节): 39 | 01 00 33 。。。。。。。。 40 | 41 | 42 | access_flag:访问标记符号(2个字节)0X0021:ACC_PUBLIC && ACC_SUPER ; 43 | thisClassName:索引值(2个字节); 44 | superClassName:索引值(2个字节); 45 | Interfaces_count:实现接口的个数(2个字节) 00 00——》Java类中最大实现接口的个数是65535(ffff)个(16^4-1个); 46 | fields_count:字段的个数; 47 | fileds_info[] :字段数组,8个字节: 48 | 前2个字节为字段的访问修饰符; 49 | 3、4个字节为name_index(字段名称索引); 50 | 5、6个字节为descriptor_index(字段描述索引 51 | 7、8字节位attribute_count(属性表个数)); 52 | method_info[] :方法数组 53 | access_flag:表示我们的方法访问权限为ACC_PUBLIC; 54 | name_index表示方法名称的索引指向常量池的第七个位置,表示init,在编译期间生成的默认的构造函数; 55 | descriptor_index:biaoshi方法描述索引指向的常量池 #8 表示()V 五参数,无返回值; 56 | attribute_count:表示方法的属性个数; 57 | attribute_infs.... 58 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/classLoader/MainClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.classLoader; 2 | 3 | import org.aspectj.util.LangUtil; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | public class MainClass { 9 | public static void main(String[] args) { 10 | // PersionClass persionClass = new PersionClass(); 11 | // Class clazz = PersionClass.class; 12 | // persionClass.getClass(); 13 | 14 | bootClassLoaderLoadingPath(); 15 | extClassLoaderLoadingPath(); 16 | appClassLoaderLoadingPath(); 17 | // getProcess(); 18 | 19 | } 20 | //Bootstrap类加载器加载的jar包 21 | public static void bootClassLoaderLoadingPath(){ 22 | String bootStrapLoadingPath = System.getProperty("sun.boot.class.path"); 23 | List list = Arrays.asList(bootStrapLoadingPath.split(";")); 24 | System.out.println("启动类的类加载器加载jar包路径如下"); 25 | //启动类的类加载器中会有一个“C:\Program Files\Java\jdk1.8.0_211\jre\classes”路径, 26 | //这个路径表示你自定义的class文件放到上述路径中就可以被启动类加载器加载; 27 | list.forEach(s ->System.out.println(s)); 28 | } 29 | //扩展类加载器加载的jar包 30 | public static void extClassLoaderLoadingPath(){ 31 | System.out.println("-----------------"); 32 | System.out.println("扩展类类加载器加载jar包路径如下"); 33 | String bootStrapLoadingPath = System.getProperty("java.ext.dirs"); 34 | List list = Arrays.asList(bootStrapLoadingPath.split(";")); 35 | list.forEach(s ->System.out.println(s)); 36 | } 37 | //应用类加载器加载的jar包 38 | public static void appClassLoaderLoadingPath(){ 39 | System.out.println("-----------------"); 40 | System.out.println("应用类类加载器加载jar包路径如下:"); 41 | String bootStrapLoadingPath = System.getProperty("java.class.path"); 42 | List list = Arrays.asList(bootStrapLoadingPath.split(";")); 43 | list.forEach(s ->System.out.println(s)); 44 | } 45 | 46 | 47 | //代码验证双亲委派模型加载过程 48 | public static void getProcess(){ 49 | System.out.println(MainClass.class.getClassLoader()); 50 | System.out.println(MainClass.class.getClassLoader().getParent()); 51 | System.out.println(MainClass.class.getClassLoader().getParent().getParent()); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/classLoader/PersionClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.classLoader; 2 | 3 | public class PersionClass { 4 | private String name ; 5 | private String add; 6 | } 7 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/classLoader/自定义类加载力器: -------------------------------------------------------------------------------- 1 | JVM知识点划分: 2 | 一、class文件结构 3 | 二、classloader 4 | 三、JVM运行时候数据区; 5 | 四、垃圾回收器和垃圾回收算法; 6 | 五、jit; 7 | 8 | 9 | 二、类加载 10 | 2.1、在Java代码中,类型的加载、链接、初始化过程都是在程序运行期间完成的; 11 | 2.1.1、类型的加载————这里的类型是指的什么? 12 | 答:类型就是指的我们Java源代码通过编译后的class文件; 13 | 2.1.2、类型的来源有哪些? 14 | 答:本地磁盘、网络下载.class文件、war、jar下加载.class文件、从专门的数据库中读取class文件(少见) 15 | 将Java源文件动态编译成class文件:典型的代表是动态代理——通过运行期生成class文件;jsp会被转 16 | 换成servlet,而我们的servlet是一个Java文件,会被编译成class文件; 17 | 2.1.3、通过类加载器来进行加载,加载到加载到方法区(元空间); 18 | 2.1.4、类加载器都有哪些? 19 | 1)、启动类加载器:通过C语言实现; 20 | 2)、扩展类加载器:通过Java语言实现; 21 | 3)、系统(APP类加载器)类加载器:Java语言实现的; 22 | 4)、用户级别的:自定义的类加载器(继承ClasssLoader); 23 | 2.1.5、类加载器的加载机制:双亲委派模型——自底向上检查,自顶向下加载; 24 | Launcher源码中可以看到:ExcClassLoader会作为父类被传递给appClassLoader; 25 | 2.2、在什么时候会触发类的初始化(执行类的静态代码块)? 26 | 1)、get static:调用类的静态方法; 27 | 2)、invokeStatic: 28 | 3)、main方法; 29 | 4)、new 指令; 30 | 5)、class.forName()反射; 31 | 6)、子类的初始化一定会触发我们的父类的初始化 32 | 初始化一定会有类加载过程;类加载过程不一定有初始化; 33 | 2.3、如何编写自定义类加载器? 34 | 1)、写一个loadClassData():把.class文件变成byte数组; 35 | 2)、重写我们的findClass(){ 36 | loaderClassDate(); 37 | defineClass(); 38 | } 39 | 官网demo如下: 40 | * class NetworkClassLoader extends ClassLoader { 41 | * String host; 42 | * int port; 43 | * //红鞋 44 | * public Class findClass(String name) { 45 | * byte[] b = loadClassData(name); 46 | * return defineClass(name, b, 0, b.length); 47 | * } 48 | * 49 | * private byte[] loadClassData(String name) { 50 | * // load the class data from the connection 51 | *  . . . 52 | * } 53 | * } 54 | 55 | 2.4、不同的类加载器加载相同的类,则两个类加载器加载的类无法进行相互转换; 56 | 原因:不同的类加载器有不同的命名空间; 57 | 类加载器的命名空间:是具有类加载器本身以及所有父加载器所加载出来的binary name(full class name) 组成; 58 | 1)、在同一个二明明空间里,不允许出现2个完全一样的binary name。 59 | 2)、在不同的命名空间中,可以出现2个相同的binary name。但是二者对应的class对象是相互不能感知到的,也就是说class对象的类型是不一样的; 60 | 3)、子加载器的命名空间站中的binary name对应的类中可以访问父加载器命名空间中binary name 对应的类,反之不行; 61 | 62 | 2.5、双亲委派模型的好处; 63 | 1)、如果我们的Object类被自定义的classloader加载,name内存中会出现多个object对象,且这个对象是无法相互转换的,这是一个非常危险的事情; 64 | 65 | 2.6、如何打破双亲委派模型? 66 | SPI: -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/controller/WebController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | public class WebController { 9 | 10 | @RequestMapping("filterTest") 11 | public String filterTest(){ 12 | return "fiterTest success"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/enumTest/EnumDemo01.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.enumTest; 2 | 3 | 4 | /** 5 | * @Title: EnumDemo01 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/22-10:45 11 | */ 12 | public enum EnumDemo01 { 13 | RETURN_TYPE1("name1","1"), 14 | RETURN_TYPE2("name2","2"), 15 | RETURN_TYPE3("name3","3"); 16 | 17 | private String message; 18 | private String code; 19 | 20 | EnumDemo01(String message, String code) { 21 | this.message = message; 22 | this.code = code; 23 | } 24 | 25 | public String getCode() { 26 | return code; 27 | } 28 | 29 | public String getMessage() { 30 | return message; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/enumTest/EnumDemo02.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.enumTest; 2 | 3 | 4 | /** 5 | * @Title: EnumDemo02 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/22-11:00 11 | */ 12 | public enum EnumDemo02 { 13 | 14 | NAME,AGE,ADDR,PHONE; 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaNonReturnMutipleParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: LambdaNonReturnMutipleParameter 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:31 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaNonReturnMutipleParameter { 14 | void test(int a ,int b); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaNonReturnNonParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: Interface 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:28 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaNonReturnNonParameter { 14 | void test(); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaNonReturnSingleParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: LambdaNonReturnSingleParameter 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:30 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaNonReturnSingleParameter { 14 | void test(int a); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaSingleRetrunSingleParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: LambdaSingleRetrunSingleParameter 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:32 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaSingleRetrunSingleParameter { 14 | int test(int a ); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaSingleReturnMutiplyParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: LambdaSingleReturnMutiplyParameter 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:33 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaSingleReturnMutiplyParameter { 14 | int test(int a,int b); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/interfaces/LambdaSingleReturnNoneParameter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.interfaces; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: LambdaSingleReturnNoneParameter 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:32 11 | */ 12 | @FunctionalInterface 13 | public interface LambdaSingleReturnNoneParameter { 14 | int test(); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/lambdaPackage/Program.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.lambdaPackage; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: Program 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/24-15:13 11 | */ 12 | public class Program { 13 | public static void main(String[] args) { 14 | Comparator comparator = new MyComparator(); 15 | Comparator comparator1 =new Comparator() { 16 | @Override 17 | public int compare(int a, int b) { 18 | return a-b; 19 | } 20 | }; 21 | Comparator comparator2 = (a,b)->a-b; 22 | } 23 | 24 | static class MyComparator implements Comparator { 25 | 26 | @Override 27 | public int compare(int a, int b) { 28 | return a - b; 29 | } 30 | } 31 | 32 | @FunctionalInterface 33 | public interface Comparator { 34 | int compare(int a, int b); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/lambdaPackage/ProgramDemo02.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.lambdaPackage; 2 | 3 | 4 | /** 5 | * @Title: ProgramDemo02 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/9/16-11:53 11 | */ 12 | public class ProgramDemo02 { 13 | } 14 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/clibPackage/MainClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.clibPackage; 2 | 3 | public class MainClass { 4 | public static void main(String[] args) { 5 | Singer singer = new Singer(); 6 | Singer proxySinger = (Singer) new ProxyFactory(singer).getProxyInstance(); 7 | proxySinger.sing(); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/clibPackage/ProxyFactory.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.clibPackage; 2 | 3 | 4 | import org.springframework.cglib.proxy.Enhancer; 5 | import org.springframework.cglib.proxy.MethodInterceptor; 6 | import org.springframework.cglib.proxy.MethodProxy; 7 | 8 | import java.lang.reflect.Method; 9 | 10 | public class ProxyFactory implements MethodInterceptor { 11 | private Object target; 12 | public ProxyFactory(Object target){ 13 | this.target = target; 14 | } 15 | public Object getProxyInstance(){ 16 | //1.工具类 17 | Enhancer en = new Enhancer(); 18 | //2.设置父类 19 | en.setSuperclass(target.getClass()); 20 | //3.设置回调函数 21 | en.setCallback(this); 22 | //4.创建子类(代理对象) 23 | return en.create(); 24 | } 25 | 26 | 27 | @Override 28 | public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { 29 | //此处在真实对象方法执行前编写自己的业务逻辑 30 | System.out.println("CGLIB动态代理————向观众问好"); 31 | Object returnValue = method.invoke(target,objects);//真实对象对应方法的调用; 32 | //此处在真实对象方法执行前编写自己的业务逻辑 33 | System.out.println("CGLIB动态代理————谢谢大家"); 34 | return returnValue; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/clibPackage/Singer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.clibPackage; 2 | 3 | public class Singer { 4 | public void sing(){ 5 | System.out.println("sing a song"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/jdkPackage/ISinger.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.jdkPackage; 2 | 3 | public interface ISinger { 4 | void sing(); 5 | } 6 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/jdkPackage/MainClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.jdkPackage; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | public class MainClass { 8 | public static void main(String[] args) { 9 | //1、创建一个真实角色 10 | Singer target = new Singer(); 11 | //2、调用Proxy.newProxyInstance方法,并构造一个InvocationHandler对象, 12 | //3、在对象内部重写invoke方法,同时调用method.invoke(target,args); 13 | //4、并在该方法的上下添加自己的代码逻辑 14 | //其中:target.getClass().getClassLoader():获取类加载器,用来生成代理对象; 15 | // target.getClass().getInterfaces()获取接口元信息; 16 | ISinger iSinger = (ISinger) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { 17 | @Override 18 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 19 | System.out.println("动态代理---向观众问好");//在真实对象的方法被调用“前”编写自己的业务逻辑 20 | Object returnValue = method.invoke(target,args);//此处通过反射调用真实对象对应的方法; 21 | System.out.println("动态代理---向观众问好");//在真实对象的方法被调用“后”编写自己的业务逻辑 22 | return returnValue; 23 | } 24 | }); 25 | iSinger.sing(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/jdkPackage/Singer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.jdkPackage; 2 | 3 | public class Singer implements ISinger{ 4 | 5 | @Override 6 | public void sing() { 7 | System.out.println("sing a song"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/$Proxy1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/$Proxy1.class -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/$Proxy1.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | import java.lang.reflect.Method; 3 | public class $Proxy1 implements com.example.springbootdemotest.proxy.principle.Moveable{ 4 | public $Proxy1(InvocationHandler h){ 5 | this.h = h; 6 | } 7 | com.example.springbootdemotest.proxy.principle.InvocationHandler h; 8 | @Override 9 | public void move(){ 10 | try{ 11 | Method md = com.example.springbootdemotest.proxy.principle.Moveable.class.getMethod("move"); 12 | h.invoke(this,md); 13 | }catch(Exception e){e.printStackTrace();} 14 | }} -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/InvocationHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | //定义一个方法调用接口 6 | public interface InvocationHandler { 7 | void invoke(Object o, Method m); 8 | } 9 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/Moveable.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | 3 | //定义一个接口; 4 | public interface Moveable { 5 | void move(); 6 | } 7 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/Proxy.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | 3 | import org.apache.tomcat.websocket.WsRemoteEndpointImplClient; 4 | 5 | import javax.tools.JavaCompiler; 6 | import javax.tools.StandardJavaFileManager; 7 | import javax.tools.ToolProvider; 8 | import java.io.File; 9 | import java.io.FileWriter; 10 | import java.lang.reflect.Constructor; 11 | import java.lang.reflect.Method; 12 | import java.net.URL; 13 | import java.net.URLClassLoader; 14 | 15 | //代理对象, 16 | public class Proxy { 17 | public static Object newProxyInstance(Class infce, InvocationHandler h) throws Exception { 18 | //1、定义方法字符串,用于保存方法信息; 19 | String methodStr = ""; 20 | String rt = "\r\n"; 21 | //2、接口方法获取; 22 | Method[] methods = infce.getMethods(); 23 | for (Method m : methods) { 24 | //生成方法信息; 25 | methodStr += "@Override" + rt + 26 | " public void "+ m.getName()+"(){"+rt+ 27 | " try{" + rt + 28 | " Method md = " + infce.getName() + ".class.getMethod(\"" + m.getName() + "\");" + rt + //找到具体方法 29 | " h.invoke(this,md);" + rt + 30 | " }catch(Exception e){e.printStackTrace();}" + rt + 31 | "}"; 32 | } 33 | //3、生成实现类的对象信息 34 | String src ="package com.example.springbootdemotest.proxy.principle;"+ rt + 35 | "import java.lang.reflect.Method;" +rt + 36 | "public class $Proxy1 implements "+ infce.getName() +"{" +rt + 37 | " public $Proxy1(InvocationHandler h){" +rt + 38 | " this.h = h;" +rt + 39 | " }" +rt + 40 | " com.example.springbootdemotest.proxy.principle.InvocationHandler h;" +rt + 41 | methodStr+ 42 | "}"; 43 | 44 | //4、动态生成$Proxy.java文件; 45 | //D:\software\gitRespository\springbootdemo\src\main\java\com\example\springbootdemotest\proxy\principle\$Proxy1.java 46 | String fileName = System.getProperty("user.dir")+"/springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/$Proxy1.java"; 47 | File f = new File(fileName); 48 | FileWriter fw = new FileWriter(f); 49 | fw.write(src); 50 | fw.flush(); 51 | fw.close(); 52 | 53 | //5、执行动态编译过程; 54 | JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 55 | StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null,null,null); 56 | Iterable units = fileMgr.getJavaFileObjects(fileName); 57 | JavaCompiler.CompilationTask t = compiler.getTask(null,fileMgr,null,null,null,units); 58 | t.call(); 59 | fileMgr.close(); 60 | 61 | //6、加载生成的$Proxy.class到内存中; 62 | //D:\software\gitRespository\springbootdemo\springbootdemo-test\src\main\java\com\example\springbootdemotest\proxy\clibPackage\MainClass.java 63 | // URL[] urls = new URL[]{new URL("file:"+System.getProperty("user.dir")+"/src/main/java")}; 64 | URL[] urls = new URL[]{new URL("file:"+"D:/software/gitRespository/springbootdemo/springbootdemo-test/src/main/java")}; 65 | 66 | URLClassLoader ul = new URLClassLoader(urls); 67 | Class c = ul.loadClass("com.example.springbootdemotest.proxy.principle.$Proxy1"); 68 | System.out.println(c); 69 | Constructor ctr = c.getConstructor(InvocationHandler.class); 70 | Object m = ctr.newInstance(h); 71 | //m.move(); 72 | return m; 73 | } 74 | 75 | public static void main(String[] args) throws Exception{ 76 | Tank tank = new Tank(); 77 | InvocationHandler h = new TimeHandler(tank); 78 | Moveable m = (Moveable) Proxy.newProxyInstance(Moveable.class,h); 79 | m.move(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/Tank.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | 3 | //实现接口的目标类 4 | public class Tank implements Moveable 5 | { 6 | @Override 7 | public void move() { 8 | System.out.println("Tank Move..."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/TimeHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.principle; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | public class TimeHandler implements InvocationHandler{ 6 | 7 | private Object target; 8 | public TimeHandler(Object target){ 9 | this.target = target; 10 | } 11 | @Override 12 | public void invoke(Object o, Method m) { 13 | long start = System.currentTimeMillis(); 14 | System.out.println("StartTime:"+start); 15 | System.out.println(o.getClass().getName()); 16 | try { 17 | m.invoke(target); 18 | }catch (Exception e){ 19 | e.printStackTrace(); 20 | } 21 | long end = System.currentTimeMillis(); 22 | System.out.println("EndTime:"+end); 23 | System.out.println("time:"+(end-start)); 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/principle/底层动态生成代理类和编译过程: -------------------------------------------------------------------------------- 1 | jdk动态代理(底层动态生成代理类和编译过程) 2 | 相关API: 3 | 1、Java 编译API: 4 | JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 5 | 2、Invocationhandler(接口): 6 | 该接口是proxy代理实例的 调用处理程序实现的一个接口,每个proxy代理实例都有一个关联的调用处理程序;在代理实例调用方法时, 7 | 方法调用被编码分配到调用处理程序的invoke方法。 8 | 3、Proxy类: 9 | 该类就是用来创建一个代理对象的类,它提供了很多方法,但是我们最常用的是newProxyInstance方法;该方法有三个参数,具体如下: 10 | 1)、ClassLoader loader:一个ClassLoader对象,定义了由哪个classloader对象生成的代理类进行加载; 11 | 2)、 Class[] interfaces:一个interfaces对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样的一个接口对象数组, 12 | 那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法; 13 | 3)、InvocationHandler h:一个Invocationhandler对象,表示的是当动态代理对象调用方法的时候会关联到哪一个Invocationhandler对象上, 14 | 并最终由其调用; 15 | 4、代理过程: 16 | 1、定义一个接口:Moveable,接口中有方法:move(); 17 | 2、实现接口的目标类(它要被代理); 18 | 3、定义一个处理器TimeHandler,重载构造方法,重写invoke函数,添加自己的处理逻辑; 19 | 4、代理逻辑实现过程编写: 20 | 1)、获取接口方法; 21 | 2)、获取需要动态生成的代理对象的目录; 22 | 3)、生成对应的代理文件$Proxy.java文件; 23 | 4、执行动态编译过程,生成$Proxy.class文件; 24 | 5)、加载生成的$Proxy.calss到内存中(执行对象的声明周期); 25 | 6)、返回生成对象的引用; 26 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/staticPacakge/ISinger.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.staticPacakge; 2 | 3 | public interface ISinger { 4 | void sing(); 5 | } 6 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/staticPacakge/MainClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.staticPacakge; 2 | 3 | import com.example.springbootdemotest.proxy.staticPacakge.ISinger; 4 | import com.example.springbootdemotest.proxy.staticPacakge.Singer; 5 | import com.example.springbootdemotest.proxy.staticPacakge.SingerProxy; 6 | 7 | public class MainClass { 8 | public static void main(String[] args) { 9 | //创建一个真实角色 10 | Singer singer = new Singer(); 11 | //创建一个代理角色,构造方法中需要真实角色; 12 | ISinger singerProxy = new SingerProxy(singer); 13 | //代理角色执行方法(代理角色内部调用真实角色对应的方法) 14 | singerProxy.sing(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/staticPacakge/Singer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.staticPacakge; 2 | 3 | public class Singer implements ISinger{ 4 | @Override 5 | public void sing() { 6 | System.out.println("sing a song"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/proxy/staticPacakge/SingerProxy.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.proxy.staticPacakge; 2 | 3 | public class SingerProxy implements ISinger { 4 | private ISinger iSinger ; 5 | public SingerProxy(ISinger iSinger){ 6 | this.iSinger = iSinger; 7 | } 8 | 9 | @Override 10 | public void sing() { 11 | System.out.println("向观众问好"); 12 | iSinger.sing(); 13 | System.out.println("谢谢大家"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/qas/QasTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.qas; 2 | 3 | 4 | import com.example.springbootdemotest.interfaces.LambdaSingleReturnMutiplyParameter; 5 | 6 | import java.util.concurrent.locks.AbstractQueuedSynchronizer; 7 | import java.util.concurrent.locks.ReentrantLock; 8 | 9 | /** 10 | * @Title: QasTest 11 | * @ProjectName springbootdemo 12 | * @Description: TODO 13 | * @author YangPeng 14 | * @company ccxcredit 15 | * @date 2019/6/5-16:58 16 | */ 17 | public class QasTest { 18 | // AbstractQueuedSynchronizer 19 | // ReentrantLock 20 | public static void main(String[] args) { 21 | LambdaSingleReturnMutiplyParameter lambda1 = (a,b)->{ 22 | return a+b; 23 | }; 24 | System.out.println(lambda1.test(1,2)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/reflect/MainClass.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.reflect; 2 | 3 | import org.springframework.http.converter.json.GsonBuilderUtils; 4 | 5 | import java.io.FileDescriptor; 6 | import java.lang.reflect.*; 7 | 8 | public class MainClass { 9 | public static void main(String[] args) { 10 | getPrivateConstructor(); 11 | getObject(); 12 | getPrivateFiled(); 13 | getPrivateMethod(); 14 | } 15 | 16 | //通过反射方式生成私有的构造方法; 17 | public static void getPrivateConstructor() { 18 | try { 19 | Class userClass = null; 20 | userClass = Class.forName("com.example.springbootdemotest.reflect.User"); 21 | Constructor constructor = userClass.getDeclaredConstructor(String.class); 22 | constructor.setAccessible(true); 23 | User user = (User) constructor.newInstance("yangpeng"); 24 | System.out.println("反射生成私有构造方法----------对象地址为:" + user.hashCode()); 25 | } catch (Exception e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | 30 | //通过反射生成对象: 31 | public static void getObject() { 32 | try { 33 | Class classObject = Class.forName("com.example.springbootdemotest.reflect.User"); 34 | User user = (User) classObject.newInstance(); 35 | user.setAdd("beijing"); 36 | user.setName("yangpeng"); 37 | System.out.print("反射生成对象--------对象信息为:"); 38 | user.getMsg(); 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | //反射私有属性 44 | public static void getPrivateFiled() { 45 | 46 | try { 47 | Class classObject = Class.forName("com.example.springbootdemotest.reflect.User"); 48 | Object classUser = classObject.newInstance(); 49 | Field field = classObject.getDeclaredField("value"); 50 | field.setAccessible(true); 51 | String value = (String) field.get(classUser); 52 | System.out.println("获取私有属性成功:value:" + value); 53 | } catch (Exception e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | //反射私有方法 59 | public static void getPrivateMethod() { 60 | try { 61 | Class classObject = Class.forName("com.example.springbootdemotest.reflect.User"); 62 | Object classUser = classObject.newInstance(); 63 | Method method = classObject.getDeclaredMethod("privateMethod",int.class); 64 | method.setAccessible(true); 65 | method.invoke(classUser, 0); 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/reflect/User.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.reflect; 2 | 3 | public class User { 4 | private String name; 5 | private String add; 6 | private String value = "123456"; 7 | 8 | public User(String name, String add) { 9 | this.name = name; 10 | this.add = add; 11 | } 12 | 13 | private User(String name) { 14 | this.name = name; 15 | } 16 | public User(){ 17 | 18 | } 19 | private void privateMethod(int i ) { 20 | System.out.println("这是一个私有方法:"+i); 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public String getAdd() { 28 | return add; 29 | } 30 | 31 | public void setAdd(String add) { 32 | this.add = add; 33 | } 34 | 35 | public void getMsg() { 36 | System.out.println(this.name + this.add); 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/reflect/反射.txt: -------------------------------------------------------------------------------- 1 | 该包反射package,用来编写反射相关代码及原理; 2 | 一、什么是反射? 3 | Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性; 4 | 这种动态获取信息以及动态调用对象方法的功能程为Java语言的反射机制; 5 | 二、Java反射的相关类; 6 | 与Java反射相关的类如下: 7 | Class类:代表类的实体,在运行的Java应用程序中表示类和接口; 8 | Field类:代表类的成员变量(成员变量也成为类的属性) 9 | Method类:代表类的方法; 10 | Constructor类:代表类的构造方法; 11 | 具体通过反射方式获取类的相关信息代码如下: 12 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/streamTest/StreamTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.streamTest; 2 | 3 | 4 | import java.util.*; 5 | import java.util.stream.Stream; 6 | 7 | /** 8 | * @author YangPeng 9 | * @Title: StreamTest 10 | * @ProjectName springbootdemo 11 | * @Description: StreamTestDemo 12 | * @company ccxcredit 13 | * @date 2019/6/27-16:47 14 | */ 15 | public class StreamTest { 16 | 17 | public static void main(String[] args) { 18 | List list = new ArrayList<>(); 19 | Map map = new HashMap<>(); 20 | map.put("12",12.0); 21 | // map. 22 | list.add("1"); 23 | list.add("2"); 24 | list.add("3"); 25 | list.add("4"); 26 | list.add("5"); 27 | Stream> stream = Stream.of(list); 28 | Stream> streamMap = Stream.of(map); 29 | stream.forEach(x->{ 30 | System.out.println(x); 31 | }); 32 | streamMap.forEach(a ->{ 33 | System.out.println(a); 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/syntax/Syntax1.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.syntax; 2 | 3 | 4 | import com.example.springbootdemotest.interfaces.*; 5 | 6 | /** 7 | * @author YangPeng 8 | * @Title: Syntax1 9 | * @ProjectName springbootdemo 10 | * @Description: lambda 表达式的基础语法; 11 | * @company ccxcredit 12 | * @date 2019/5/24-15:34 13 | */ 14 | public class Syntax1 { 15 | public static void main(String[] args) { 16 | //1、lambda表达式的基础语法 17 | //lambda是一个匿名函数 18 | //返回值类型(pass)、方法名(pass)、参数列表(重点)、方法体(重点); 19 | // ():用来表示参数列表; 20 | //{}:用来描述方法体 21 | // ->:使用lambda运算符(读作:goes to) 22 | //1、无参无返回: 23 | LambdaNonReturnNonParameter lambda1 = () -> { 24 | System.out.println("无参数无返回值的lambda表达式"); 25 | }; 26 | lambda1.test(); 27 | //2、有参数无返回值的 28 | LambdaNonReturnSingleParameter lambda2 = (int a) -> { 29 | System.out.println("有参数,无返回值的lambda表达式:" + a); 30 | }; 31 | lambda2.test(3); 32 | //3、多参数无返回值的lambda表达式 33 | LambdaNonReturnMutipleParameter lambda3 = (int a, int b) -> { 34 | System.out.println("多参数无返回值的lambda表达式:" + a + b); 35 | }; 36 | lambda3.test(3, 5); 37 | //4、无参数有返回值的lambda表达式 38 | LambdaSingleReturnNoneParameter lambda4 = () -> { 39 | System.out.println("无参数有返回值的lambda表达式:100"); 40 | return 100; 41 | }; 42 | lambda4.test(); 43 | //5、单一参数单一返回值的lambda表达式: 44 | LambdaSingleRetrunSingleParameter lambda5 = (int a) -> { 45 | System.out.println("单一参数单一返回值的lambda表达式:" + (100 + a)); 46 | return a + 100; 47 | }; 48 | lambda5.test(100); 49 | //6、多参数单一返回值的lambda表达式: 50 | LambdaSingleReturnMutiplyParameter lambda6 = (int a, int b) -> { 51 | System.out.println("多参数单一返回值的lambda表达式:" + (a + b)); 52 | return a + b; 53 | }; 54 | lambda6.test(100, 200); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/java/com/example/springbootdemotest/syntax/Syntax2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotest.syntax; 2 | 3 | 4 | import com.example.springbootdemotest.interfaces.LambdaNonReturnMutipleParameter; 5 | import com.example.springbootdemotest.interfaces.LambdaNonReturnSingleParameter; 6 | import com.example.springbootdemotest.interfaces.LambdaSingleReturnMutiplyParameter; 7 | import com.example.springbootdemotest.interfaces.LambdaSingleReturnNoneParameter; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Collections; 11 | import java.util.List; 12 | 13 | /** 14 | * @author YangPeng 15 | * @Title: Syntax2 16 | * @ProjectName springbootdemo 17 | * @Description: TODO 18 | * @company ccxcredit 19 | * @date 2019/5/24-15:57 20 | */ 21 | public class Syntax2 { 22 | public static void main(String[] args) { 23 | //1、lambda可以精简参数的类型(因为接口中已经定义了参数的类型) 24 | LambdaNonReturnMutipleParameter lambda1 = (a, b) -> { 25 | System.out.println(a + b); 26 | }; 27 | 28 | //2、lambda可以精简小括号; 29 | LambdaNonReturnSingleParameter lambda2 = x -> { 30 | System.out.println("hello world"); 31 | }; 32 | //3、关于方法、大括号的精简; 33 | //如果方法体中只有一句代码时,大括号是可以省略的; 34 | LambdaNonReturnSingleParameter lambda3 = x -> System.out.println("hello world"); 35 | 36 | //4、对方法和大括号精简的补充 37 | //如果方法体中唯一的一条语句是返回语句,则在省略大括号的同时,也必须省略return; 38 | LambdaSingleReturnNoneParameter lambda4 = () -> 10; 39 | 40 | LambdaSingleReturnMutiplyParameter lambda5 = (a,b)->a+b; 41 | 42 | 43 | //lambda表达式的方法引用:可以快速的将一个lambda表达式的实现直线给一个已经实现的方法; 44 | //语法:方法的隶属这::方法名 45 | //注意:1、参数数量和类型一定要和接口中定义的方法一致;2、返回值类型也必须同接口中定义的返回值类型一致; 46 | 47 | List list = new ArrayList(); 48 | Collections.addAll(list,"1","2","3","4","5","6"); 49 | System.out.println(list); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /springbootdemo-test/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/MainClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/MainClass.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/ProxyFactory.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/ProxyFactory.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/Singer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/clibPackage/Singer.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/ISinger.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/ISinger.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/MainClass$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/MainClass$1.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/MainClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/MainClass.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/Singer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/jdkPackage/Singer.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/ISinger.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/ISinger.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/MainClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/MainClass.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/Singer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/Singer.class -------------------------------------------------------------------------------- /springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/SingerProxy.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yanpgeng/springbootdemo/eb5fb7ab97d435630dd79e52194cab265eaf1078/springbootdemo-test/target/classes/com/example/springbootdemotest/proxy/staticPacakge/SingerProxy.class -------------------------------------------------------------------------------- /springbootdemo-thread/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-thread 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-thread 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | com.example 34 | springbootdemo-entity 35 | 0.0.1-SNAPSHOT 36 | compile 37 | 38 | 42 | 43 | org.apache.tomcat.embed 44 | tomcat-embed-jasper 45 | 46 | 47 | redis.clients 48 | jedis 49 | 50 | 51 | 52 | 53 | 54 | 55 | com.alibaba 56 | druid 57 | 1.1.0 58 | 59 | 60 | 61 | mysql 62 | mysql-connector-java 63 | runtime 64 | 65 | 66 | 67 | org.mybatis.spring.boot 68 | mybatis-spring-boot-starter 69 | 1.3.1 70 | 71 | 72 | 73 | com.github.pagehelper 74 | pagehelper-spring-boot-starter 75 | 1.2.3 76 | 77 | 78 | 79 | 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-maven-plugin 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/BlockQueueTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread; 2 | 3 | import com.example.springbootdemothread.entity.Consumer; 4 | import com.example.springbootdemothread.entity.Producer; 5 | 6 | import java.util.concurrent.BlockingQueue; 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.LinkedBlockingQueue; 10 | 11 | public class BlockQueueTest { 12 | public static void main(String[] args) throws InterruptedException { 13 | // 声明一个容量为10的缓存队列 14 | BlockingQueue queue = new LinkedBlockingQueue(10); 15 | 16 | Producer producer1 = new Producer(queue); 17 | Producer producer2 = new Producer(queue); 18 | Producer producer3 = new Producer(queue); 19 | Consumer consumer = new Consumer(queue); 20 | 21 | // 借助Executors 22 | ExecutorService service = Executors.newCachedThreadPool(); 23 | // 启动线程 24 | service.execute(producer1); 25 | service.execute(producer2); 26 | service.execute(producer3); 27 | service.execute(consumer); 28 | 29 | // 执行10s 30 | Thread.sleep(10 * 1000); 31 | producer1.stop(); 32 | producer2.stop(); 33 | producer3.stop(); 34 | 35 | Thread.sleep(2000); 36 | // 退出Executor 37 | service.shutdown(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/ConcurrentContainer/ContainerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.ConcurrentContainer; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Iterator; 6 | import java.util.Vector; 7 | 8 | /** 9 | * @author YangPeng 10 | * @Title: ContainerTest 11 | * @ProjectName springbootdemo 12 | * @Description: TODO 13 | * @company ccxcredit 14 | * @date 2019/6/11-14:43 15 | */ 16 | public class ContainerTest { 17 | static Vector stringVector = new Vector<>(); 18 | 19 | public static void main(String[] args) { 20 | stringVector.add("111"); 21 | stringVector.add("222"); 22 | stringVector.add("333"); 23 | stringVector.add("444"); 24 | Thread thread1 = new Thread(() -> { 25 | stringVector.forEach((x) -> { 26 | try { 27 | Thread.sleep(100); 28 | } catch (InterruptedException e) { 29 | e.printStackTrace(); 30 | } 31 | //使用vector时,当遍历vector容器的同时,又其他线程向该容器中添加或者删除对象时,该遍历进程会抛出异常(ConcurrentModificationException) 32 | stringVector.remove(x); 33 | System.out.println("值为:" + x+";当前vector中还有元素个数:"+stringVector.size()); 34 | }); 35 | }); 36 | Thread thread2 = new Thread(() -> { 37 | try { 38 | Thread.sleep(100); 39 | } catch (InterruptedException e) { 40 | e.printStackTrace(); 41 | } 42 | System.out.println("添加的值为:555"); 43 | stringVector.addElement("555"); 44 | }); 45 | thread1.start(); 46 | thread2.start(); 47 | 48 | 49 | // ArrayList list = new ArrayList(); 50 | // list.add(2); 51 | // Iterator iterator = list.iterator(); 52 | // while (iterator.hasNext()) { 53 | // Integer integer = iterator.next(); 54 | // if (integer == 2) 55 | // list.remove(integer); 56 | // } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/controller/HttpReqController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.controller; 2 | 3 | import com.example.springbootdemothread.utils.HttpUtils; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.LinkedBlockingDeque; 9 | import java.util.concurrent.ThreadPoolExecutor; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | @RestController 13 | public class HttpReqController { 14 | ExecutorService executorService = new ThreadPoolExecutor(10, 15 | 10, 0, TimeUnit.SECONDS, 16 | new LinkedBlockingDeque<>(10)); 17 | @RequestMapping(value = "test") 18 | public void test() { 19 | int num =4; 20 | for (int i = 0; i < num; i++) { 21 | executorService.submit(new ReqEntity(i)); 22 | } 23 | } 24 | 25 | class ReqEntity implements Runnable{ 26 | private int i ; 27 | 28 | public ReqEntity(int i) { 29 | this.i = i; 30 | } 31 | 32 | @Override 33 | public void run() { 34 | HttpUtils.doGet("http://localhost:7003/thread/threadTestDemo?i="+i); 35 | //System.out.println("开启第"+i+"个线程"); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | double a = 50.0; 41 | if(a>=100){ 42 | System.out.println(a); 43 | }else{ 44 | System.out.println("j; a "); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/controller/ThreadPoolController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.controller; 2 | 3 | import com.example.springbootdemoentity.entity.User; 4 | import com.example.springbootdemothread.dao.UserMapper; 5 | import com.example.springbootdemothread.entity.ThreadEntity2; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.FileInputStream; 12 | import java.io.FileNotFoundException; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.util.concurrent.*; 16 | 17 | 18 | /** 19 | * 证评需求: 20 | * 定义一个接口,该接口可并发访问,并发访问数量不高,1s在50以内;且通过该接口计算现金流,并将现金流结果到处到excel中, 21 | * 并共浏览器进行下载; 22 | * 实现方案: 23 | * 1、使用线程池进行控制并发数量:将超过并发数量的线程保存到blockqueue中,超过部分直接报错(线程池的rejectException); 24 | * 2、使用CountDownLatch做“串行”处理,确定线程池中的当前请求是否执行结束,如果执行结束,则调用文件导出方法进行下载; 25 | * 3、使用runnable进行算法的计算和文件的保存操作; 26 | * 1)、定义Runnable对象,参数有:ID、countDownLatch、业务参数、dao层对象(用于查询数据库)、 27 | * ConcurrentHashMap(用于保存计算过程中的异常、正确结果等信息); 28 | * 2)、重写run方法,在该方法中执行的操作有: 29 | * I、使用dao层对象,通过ID获取入参想项; 30 | * II、对入参项进行校验,校验通过,则通过模型计算现金流,如果发生异常,则保存到ConcurrentHashMap对象中,并保存相关异常信息,打印到log中; 31 | * III、当算法计算结束,将计算结果通过代码写入到excel中并保存到服务器某一路径下; 32 | * IV、使用countDownLatch.await()代码进行“同步串行”操作,并根据ConcurrentHashMap对象中的数据判断当前模型是否正常执行结束,如果是, 33 | * 则调用下载方法,让浏览器可以下载计算结果; 34 | * 3)、通过构造函数创建对象,并使用线程池中的线程执行该任务; 35 | * 36 | * 37 | * 线程池相关变量: 38 | * 1、线程池核心线程大小:CPU个数; 39 | * 2、线程池最大线程大小:CPU个数; 40 | * 3、等待队列大小:2倍的CPU个数; 41 | */ 42 | @RestController 43 | public class ThreadPoolController { 44 | //定义一个map,用来保存计算结果 45 | static ExecutorService executorService = new ThreadPoolExecutor(2, 5, 46 | 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2)); 47 | @Autowired 48 | private UserMapper userMapper; 49 | 50 | @RequestMapping(value = "/threadTestDemo") 51 | public String threadTestDemo(HttpServletResponse response, int i) { 52 | ConcurrentHashMap con = new ConcurrentHashMap<>(); 53 | CountDownLatch countDownLatch = new CountDownLatch(1); 54 | try { 55 | executorService.submit(new ThreadEntity2(i, userMapper, con, countDownLatch)); 56 | countDownLatch.await(); 57 | System.out.println(con.toString()); 58 | 59 | } catch (InterruptedException e) { 60 | e.printStackTrace(); 61 | } 62 | try { 63 | downloadLocal(response, i + ""); 64 | } catch (FileNotFoundException e) { 65 | e.printStackTrace(); 66 | } 67 | return "计算成功!"; 68 | } 69 | 70 | public void downloadLocal(HttpServletResponse response, String i) throws FileNotFoundException { 71 | // 下载本地文件 72 | String fileName = i + ".txt"; // 文件的默认保存名 73 | // 读到流中 74 | InputStream inStream = new FileInputStream("E:/file/file/" + i + ".txt");// 文件的存放路径 75 | // 设置输出的格式 76 | response.reset(); 77 | response.setContentType("bin"); 78 | response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); 79 | // 循环取出流中的数据 80 | byte[] b = new byte[1024]; 81 | int len; 82 | try { 83 | while ((len = inStream.read(b)) > 0) { 84 | response.getOutputStream().write(b, 0, len); 85 | } 86 | inStream.close(); 87 | } catch (IOException e) { 88 | e.printStackTrace(); 89 | } 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.controller; 2 | 3 | import com.example.springbootdemoentity.entity.User; 4 | import com.example.springbootdemothread.entity.ThreadEntity2; 5 | import com.example.springbootdemothread.service.UserService; 6 | import com.github.pagehelper.PageHelper; 7 | import com.github.pagehelper.PageInfo; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.concurrent.*; 15 | import java.util.concurrent.atomic.AtomicInteger; 16 | import java.util.function.Consumer; 17 | 18 | @RestController 19 | public class UserController { 20 | @Autowired 21 | private UserService userService; 22 | 23 | @RequestMapping(value = "/getUser") 24 | public String getUser() { 25 | System.out.println("调用getUser方法"); 26 | User user = userService.getUser(); 27 | System.out.println(user.toString()); 28 | return user.toString(); 29 | } 30 | 31 | @RequestMapping(value = "/getPageUser") 32 | public PageInfo getPageUser(int page, int pageSize) { 33 | PageHelper.startPage(page, pageSize); 34 | System.out.println("调用getUser方法"); 35 | List userList = userService.getPageUser(); 36 | System.out.println(userList.toString()); 37 | PageInfo pageInfo = new PageInfo(userList); 38 | return pageInfo; 39 | //return user.toString(); 40 | } 41 | 42 | //获取服务器CPU个数; 43 | static final int nThreads = Runtime.getRuntime().availableProcessors(); 44 | 45 | //第三个参数:当线程数量大于核心线程池数量,且blockqueue已经满的时候,需要创建新的线程达到线程最大值,那么当新的 46 | //线程执行队列中的任务结束之后,新的线程的等待时间; 47 | //核心线程池数量为2,当 当前线程数量大约2时,将线程保存到线程队列中,且线程队列中最多能保存10个线程; 48 | //当线程队列也满了的时候,需要启动新的线程,且新的线程+原线程的数量不能大于5; 49 | static ExecutorService executorService = new ThreadPoolExecutor(2, 2, 50 | 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4)); 51 | AtomicInteger integer = new AtomicInteger(0); 52 | 53 | @RequestMapping(value = "/threadTest") 54 | public String threadTest(int i ) { 55 | try { 56 | Thread.currentThread().setName("第"+integer+"个controller线程"); 57 | CountDownLatch countDownLatch = new CountDownLatch(1); 58 | ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>(); 59 | // for (int i = 0; i < 100; i++) { 60 | // System.out.println(userService.hashCode()); 61 | // executorService.submit(new ThreadEntity(i)); 62 | executorService.submit(new ThreadEntity2(i,userService, concurrentHashMap, countDownLatch)); 63 | // } 64 | String a = ""; 65 | String b = ""; 66 | a.equals(b); 67 | countDownLatch.await(100, TimeUnit.SECONDS); 68 | } catch (InterruptedException e) { 69 | e.printStackTrace(); 70 | } 71 | return ""; 72 | } 73 | } 74 | 75 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/dao/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.dao; 2 | 3 | 4 | import com.example.springbootdemoentity.entity.User; 5 | import org.apache.ibatis.annotations.Mapper; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.util.List; 9 | 10 | @Mapper 11 | @Component 12 | public interface UserMapper { 13 | User getUser(); 14 | List getPageUser(); 15 | } 16 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/entity/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.entity; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.BlockingQueue; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class Consumer implements Runnable { 8 | //定义blockQueue对象; 9 | private BlockingQueue queue; 10 | private static final int DEFAULT_RANGE_FOR_SLEEP = 1000; 11 | 12 | public Consumer(BlockingQueue queue) { 13 | this.queue = queue; 14 | } 15 | 16 | public void run() { 17 | System.out.println("启动消费者线程!"); 18 | Random r = new Random(); 19 | boolean isRunning = true; 20 | try { 21 | while (isRunning) { 22 | System.out.println("正从队列获取数据..."); 23 | String data = queue.poll(2, TimeUnit.SECONDS); 24 | if (null != data) { 25 | System.out.println("拿到数据:" + data); 26 | System.out.println("正在消费数据:" + data); 27 | Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP)); 28 | } else { 29 | // 超过2s还没数据,认为所有生产线程都已经退出,自动退出消费线程。 30 | isRunning = false; 31 | } 32 | } 33 | } catch (InterruptedException e) { 34 | e.printStackTrace(); 35 | Thread.currentThread().interrupt(); 36 | } finally { 37 | System.out.println("退出消费者线程!"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/entity/Producer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.entity; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.BlockingQueue; 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | public class Producer implements Runnable{ 9 | 10 | private volatile boolean isRunning = true; 11 | private BlockingQueue queue; 12 | private static AtomicInteger count = new AtomicInteger(); 13 | private static final int DEFAULT_RANGE_FOR_SLEEP = 1000; 14 | 15 | public Producer(BlockingQueue queue) { 16 | this.queue = queue; 17 | } 18 | 19 | public void run() { 20 | String data = null; 21 | Random r = new Random(); 22 | 23 | System.out.println("启动生产者线程!"); 24 | try { 25 | while (isRunning) { 26 | System.out.println("正在生产数据..."); 27 | Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP)); 28 | 29 | data = "data:" + count.incrementAndGet(); 30 | System.out.println("将数据:" + data + "放入队列..."); 31 | if (!queue.offer(data, 2, TimeUnit.SECONDS)) { 32 | System.out.println("放入数据失败:" + data); 33 | } 34 | } 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | Thread.currentThread().interrupt(); 38 | } finally { 39 | System.out.println("退出生产者线程!"); 40 | } 41 | } 42 | 43 | public void stop() { 44 | isRunning = false; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/entity/ThreadEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.entity; 2 | 3 | 4 | import com.example.springbootdemothread.utils.WriteUtils; 5 | 6 | import java.io.IOException; 7 | 8 | public class ThreadEntity implements Runnable{ 9 | private int count ; 10 | 11 | //构造方法 12 | public ThreadEntity(int count) { 13 | this.count = count; 14 | } 15 | 16 | @Override 17 | public void run() { 18 | try { 19 | WriteUtils.writeFiles(count); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/entity/ThreadEntity2.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.entity; 2 | 3 | import com.example.springbootdemoentity.entity.User; 4 | import com.example.springbootdemothread.dao.UserMapper; 5 | import com.example.springbootdemothread.service.UserService; 6 | import com.example.springbootdemothread.utils.WriteUtils; 7 | 8 | import java.util.concurrent.ConcurrentHashMap; 9 | import java.util.concurrent.CountDownLatch; 10 | 11 | public class ThreadEntity2 implements Runnable{ 12 | private UserService userService; 13 | private UserMapper userMapper; 14 | private ConcurrentHashMap concurrentHashMap; 15 | private int count ; 16 | private CountDownLatch countDownLatch; 17 | 18 | // //构造方法 19 | public ThreadEntity2(int count, UserService userService, 20 | ConcurrentHashMap concurrentHashMap,CountDownLatch countDownLatch) { 21 | this.count = count; 22 | this.userService = userService; 23 | this.concurrentHashMap = concurrentHashMap; 24 | this.countDownLatch = countDownLatch; 25 | } 26 | public ThreadEntity2(int count, UserMapper userMapper, 27 | ConcurrentHashMap concurrentHashMap,CountDownLatch countDownLatch) { 28 | this.count = count; 29 | this.userMapper = userMapper; 30 | this.concurrentHashMap = concurrentHashMap; 31 | this.countDownLatch = countDownLatch; 32 | } 33 | //构造方法 34 | // public ThreadEntity2(int count,ConcurrentHashMap concurrentHashMap, 35 | // CountDownLatch countDownLatch) { 36 | // this.count = count; 37 | // this.countDownLatch = countDownLatch; 38 | // this.concurrentHashMap = concurrentHashMap; 39 | // } 40 | 41 | @Override 42 | public void run() { 43 | try { 44 | //Thread.currentThread().setName("第"+count+"个计算子线程"); 45 | Thread.sleep(count*3000); 46 | System.out.println("当前线程名称为:"+Thread.currentThread().getName()+";睡眠时间:"+count*3); 47 | System.out.println(userMapper.hashCode()); 48 | User user = userMapper.getUser(); 49 | concurrentHashMap.put(count+"",user); 50 | WriteUtils.writeFiles(count); 51 | // System.out.println(Thread.currentThread().getName()+"即将结束并调用countDown方法"); 52 | countDownLatch.countDown(); 53 | // System.out.println(user.hashCode()); 54 | //System.out.println(concurrentHashMap.size()); 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/entity/ThreadTestEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.entity; 2 | 3 | public class ThreadTestEntity implements Runnable{ 4 | 5 | @Override 6 | public void run() { 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/execption/ExecptionController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.execption; 2 | 3 | 4 | import org.springframework.web.bind.annotation.ControllerAdvice; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * @Title: ExecptionController 13 | * @ProjectName springbootdemo 14 | * @Description: TODO 15 | * @author YangPeng 16 | * @date 2019/3/27-17:30 17 | */ 18 | 19 | /** 20 | * @ControllerAdvice(basePackages = "com.example") 注解不添加basePackages 表示加了@Controller和@RestController都能控制 21 | */ 22 | @ControllerAdvice 23 | public class ExecptionController { 24 | 25 | @ResponseBody 26 | @ExceptionHandler(value = java.util.concurrent.RejectedExecutionException.class) 27 | public Map excptionhandler(Exception ex) { 28 | HashMap map = new HashMap<>(); 29 | 30 | map.put("errorCode", "500"); 31 | map.put("errorMsg", "当前并发访问量太大,请您稍后访问"); 32 | map.put("errorInfo", ex.getMessage()); 33 | 34 | return map; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/execption/RejectedExecutionHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.execption; 2 | 3 | 4 | import java.util.concurrent.ThreadPoolExecutor; 5 | 6 | /** 7 | * @Title: RejectedExecutionHandler 8 | * @ProjectName springbootdemo 9 | * @Description: TODO 10 | * @author YangPeng 11 | * @company ccxcredit 12 | * @date 2019/7/29-10:28 13 | */ 14 | public class RejectedExecutionHandler implements java.util.concurrent.RejectedExecutionHandler { 15 | @Override 16 | public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { 17 | // executor.setRejectedExecutionHandler(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/producerAndConsumer02/ProducerAndConsumer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.producerAndConsumer02; 2 | 3 | import java.util.LinkedList; 4 | import java.util.concurrent.TimeUnit; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import static rx.schedulers.Schedulers.start; 8 | 9 | /** 10 | * 面试题: 11 | * 写一个固定容量同步容器,拥有put和get方法,以即getCount方法, 12 | * 能够支持2个生产者线程以及10个消费者线程的阻塞调用; 13 | * 使用wait和nofity/notifyAll来实现; 14 | */ 15 | public class ProducerAndConsumer { 16 | final private LinkedList linkedList = new LinkedList(); 17 | //容器中做多10个元素; 18 | final private int MAX = 10; 19 | //容器中元素的个数; 20 | private AtomicInteger count = new AtomicInteger(0); 21 | 22 | 23 | synchronized void put(T t) { 24 | try { 25 | while (linkedList.size() == MAX) { 26 | System.out.println("当前容器个数为:"+size()); 27 | System.out.println("生产者线程:"+Thread.currentThread().getName()+"即将释放锁,并处于wait状态!"); 28 | this.wait(); 29 | } 30 | linkedList.add(t); 31 | count.getAndIncrement(); 32 | System.out.println("生产者:"+Thread.currentThread().getName()+"往容器添加一个,当前容器中的个数为:"+size()); 33 | System.out.println("生产者通知消费者进程,容器中已经有东西了,可以进行消费了。。"); 34 | this.notifyAll(); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } 38 | 39 | } 40 | 41 | synchronized T get() { 42 | T t = null; 43 | try { 44 | while (linkedList.size() == 0) { 45 | System.out.println("当前容器个数为:"+size()); 46 | System.out.println("消费者线程:"+Thread.currentThread().getName()+"即将释放锁,并处于wait状态!"); 47 | this.wait(); 48 | } 49 | t = linkedList.removeFirst(); 50 | count.getAndDecrement(); 51 | System.out.println("消费者线程:"+Thread.currentThread().getName()+"从容器中获取一个,当前容器中的个数为:"+size()); 52 | System.out.println("消费者通知生产者,已经被消费了一个,可以进行生产了。"); 53 | this.notifyAll(); 54 | } catch (InterruptedException e) { 55 | e.printStackTrace(); 56 | } 57 | return t; 58 | } 59 | 60 | Integer size() { 61 | return count.intValue(); 62 | } 63 | 64 | public static void main(String[] args) { 65 | ProducerAndConsumer producerAndConsumer = new ProducerAndConsumer<>(); 66 | System.out.println(producerAndConsumer.size()); 67 | for (int i = 0; i < 10; i++) { 68 | new Thread(() -> { 69 | for (int j = 0; j < 5; j++) 70 | System.out.println(producerAndConsumer.get()); 71 | }, "c" + i).start(); 72 | } 73 | try { 74 | TimeUnit.SECONDS.sleep(2); 75 | } catch (InterruptedException e) { 76 | e.printStackTrace(); 77 | } 78 | for (int i = 0; i < 2; i++) { 79 | new Thread(() -> { 80 | for (int j = 0; j < 25; j++) 81 | producerAndConsumer.put(Thread.currentThread().getName() + " " + j); 82 | }, "p" + i).start(); 83 | } 84 | } 85 | } 86 | 87 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo01/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo01; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: Consumer 7 | * @ProjectName springbootdemo 8 | * @Description: 消费者线程类; 9 | * @company ccxcredit 10 | * @date 2019/5/20-15:49 11 | */ 12 | public class Consumer implements Runnable { 13 | private String name; 14 | private Storage s = null; 15 | 16 | public Consumer(String name, Storage s) { 17 | this.name = name; 18 | this.s = s; 19 | } 20 | 21 | @Override 22 | public void run() { 23 | try { 24 | while (true){ 25 | Product product = s.pop(); 26 | System.out.println(name + "已消费(" + product.toString() + ").容器中现由产品个数为:"+s.size()); 27 | Thread.sleep(3000); 28 | } 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo01/Producer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo01; 2 | 3 | 4 | import java.util.Random; 5 | 6 | /** 7 | * @author YangPeng 8 | * @Title: Producer 9 | * @ProjectName springbootdemo 10 | * @Description: 生产者线程类; 11 | * @company ccxcredit 12 | * @date 2019/5/20-16:13 13 | */ 14 | public class Producer implements Runnable { 15 | /** 16 | * 定义生产者的姓名,生产的产品的存放路径; 17 | */ 18 | private String name; 19 | private Storage s = null; 20 | 21 | /** 22 | * 构造方法; 23 | */ 24 | 25 | public Producer(String name, Storage s) { 26 | this.name = name; 27 | this.s = s; 28 | } 29 | 30 | @Override 31 | public void run() { 32 | try { 33 | //线程一直往容器中生产产品; 34 | while (true) { 35 | Product product = new Product(new Random().nextInt(1000)); 36 | s.push(product); 37 | System.out.println(name + "已生产(" + product.toString() + ").容器中现有产品个数为:"+s.size()); 38 | Thread.sleep(3000); 39 | } 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo01/ProducerAndConsumserTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo01; 2 | 3 | 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | 8 | /** 9 | * @Title: ProducerAndConsumserTest 10 | * @ProjectName springbootdemo 11 | * @Description: TODO 12 | * @author YangPeng 13 | * @company ccxcredit 14 | * @date 2019/5/20-16:24 15 | */ 16 | public class ProducerAndConsumserTest { 17 | public static void main(String[] args) { 18 | ExecutorService executorService = Executors.newFixedThreadPool(8); 19 | Storage storage = new Storage(); 20 | Consumer consumer1 = new Consumer("消费者1",storage); 21 | // Consumer consumer2 = new Consumer("消费者2",storage); 22 | // Consumer consumer3 = new Consumer("消费者3",storage); 23 | 24 | Producer producer1 = new Producer("生产者1",storage); 25 | Producer producer2 = new Producer("生产者2",storage); 26 | Producer producer3 = new Producer("生产者3",storage); 27 | Producer producer4 = new Producer("生产者4",storage); 28 | Producer producer5 = new Producer("生产者5",storage); 29 | executorService.submit(consumer1); 30 | // executorService.submit(consumer2); 31 | // executorService.submit(consumer3); 32 | 33 | executorService.submit(producer1); 34 | executorService.submit(producer2); 35 | executorService.submit(producer3); 36 | executorService.submit(producer4); 37 | executorService.submit(producer5); 38 | 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo01/Product.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo01; 2 | 3 | 4 | /** 5 | * @Title: Product 6 | * @ProjectName springbootdemo 7 | * @Description: TODO 8 | * @author YangPeng 9 | * @company ccxcredit 10 | * @date 2019/5/20-15:50 11 | */ 12 | public class Product { 13 | private int id; 14 | public Product(int id ){ 15 | this.id = id; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "产品:" + this.id; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo01/Storage.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo01; 2 | 3 | 4 | 5 | import java.util.concurrent.ArrayBlockingQueue; 6 | import java.util.concurrent.BlockingQueue; 7 | import java.util.concurrent.LinkedBlockingQueue; 8 | 9 | /** 10 | * @Title: Storage 11 | * @ProjectName springbootdemo 12 | * @Description: 生产者消费者线程容器类 13 | * @author YangPeng 14 | * @company ccxcredit 15 | * @date 2019/5/20-15:49 16 | */ 17 | public class Storage { 18 | /** 19 | * 定义一个容器,该容器使用BlockingQueue,该容器为线程安全的消息队列; 20 | * 且使用linkedBlockingQueue,该容器默认大小为Integer.MAX;所以在初始化的时候不需要指定大小; 21 | * ArrayBlockingQueue,在初始化的时候,不许传入一个容量大小的值(capacity:容量); 22 | */ 23 | // BlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(); 24 | BlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(10); 25 | 26 | /** 27 | * 生产者生产产品 28 | */ 29 | public void push(Product p) throws InterruptedException { 30 | arrayBlockingQueue.put(p); 31 | } 32 | public Product pop() throws InterruptedException { 33 | //使用队列的take()方法,即如果该队列为空,则会处于阻塞状态; 34 | //如果使用poll()方法,即如果该队列为空,则返回null,就无法达到阻塞效果,生产者消费者模型无效; 35 | Product product = arrayBlockingQueue.take(); 36 | return product; 37 | } 38 | public int size(){ 39 | return arrayBlockingQueue.size(); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo02/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo02; 2 | 3 | 4 | import java.util.concurrent.ArrayBlockingQueue; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | /** 8 | * @author YangPeng 9 | * @Title: Consumer 10 | * @ProjectName springbootdemo 11 | * @Description: TODO 12 | * @company ccxcredit 13 | * @date 2019/5/20-17:38 14 | */ 15 | public class Consumer implements Runnable { 16 | //定义参数; 17 | private ArrayBlockingQueue productArrayBlockingQueue; 18 | private AtomicInteger count; 19 | public Consumer(ArrayBlockingQueue productArrayBlockingQueue,AtomicInteger count) { 20 | this.productArrayBlockingQueue = productArrayBlockingQueue; 21 | this.count = count; 22 | } 23 | 24 | 25 | //消费者消费产品 26 | @Override 27 | public void run() { 28 | try { 29 | //判断容器中是否还有产品,如果没有,则该线程进行wait(); 30 | while (count.intValue() == 0) { 31 | this.wait(); 32 | } 33 | //如果容器中还有产品,则进行消费; 34 | Product product = productArrayBlockingQueue.poll(); 35 | //容器中产品个数减一 36 | count.decrementAndGet(); 37 | System.out.println(Thread.currentThread().getName() + "消费的产品为:" + product.toString() + ",当前容器中还有产品个数为;" + count.decrementAndGet()); 38 | //睡觉5s 39 | Thread.sleep(5000); 40 | //唤醒其他线程; 41 | notifyAll(); 42 | } catch (InterruptedException e) { 43 | e.printStackTrace(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo02/Produce.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo02; 2 | 3 | 4 | import java.util.concurrent.ArrayBlockingQueue; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | /** 8 | * @author YangPeng 9 | * @Title: Produce 10 | * @ProjectName springbootdemo 11 | * @Description: TODO 12 | * @company ccxcredit 13 | * @date 2019/5/20-17:35 14 | */ 15 | public class Produce implements Runnable { 16 | /** 17 | * 定义一个生产者线程对象;; 18 | */ 19 | /** 20 | * 生产者线程对象中定义一个容器,将生产者生产的内容保存到容器中; 21 | */ 22 | private ArrayBlockingQueue productArrayBlockingQueue; 23 | private AtomicInteger count; 24 | 25 | public Produce(ArrayBlockingQueue productArrayBlockingQueue, AtomicInteger count) { 26 | this.productArrayBlockingQueue = productArrayBlockingQueue; 27 | this.count = count; 28 | } 29 | 30 | @Override 31 | public void run() { 32 | try { 33 | //一直判断容器中的size是否等于10,如果等于10则处于wait()状态,否则进行其他操作; 34 | while (count.intValue() == 10) { 35 | this.wait(); 36 | } 37 | Product product = new Product(Thread.currentThread().getName(), "12"); 38 | productArrayBlockingQueue.add(product); 39 | count.incrementAndGet(); 40 | System.out.println(Thread.currentThread().getName() + "生产的产品为:" + product.toString() + ",当前容器中还有产品个数为;" + count.intValue()); 41 | //睡觉5s 42 | Thread.sleep(5000); 43 | //唤醒其他线程; 44 | notifyAll(); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo02/Product.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo02; 2 | 3 | 4 | /** 5 | * @author YangPeng 6 | * @Title: Product 7 | * @ProjectName springbootdemo 8 | * @Description: TODO 9 | * @company ccxcredit 10 | * @date 2019/5/20-17:33 11 | */ 12 | public class Product { 13 | /** 14 | * 定义一个产品,产品有产品名称、产品地址信息; 15 | */ 16 | private String name; 17 | private String add; 18 | 19 | public Product(String name, String add) { 20 | this.name = name; 21 | this.add = add; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return "name='" + name + '\'' + ", add='" + add + '\''; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/productAndConsumer/productAndConsumerDemo02/ProductAndConsumerDemo02.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.productAndConsumer.productAndConsumerDemo02; 2 | 3 | 4 | import java.util.concurrent.ArrayBlockingQueue; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | 10 | /** 11 | * @author YangPeng 12 | * @Title: ProductAndConsumerDemo02 13 | * @ProjectName springbootdemo 14 | * @Description: 生产者消费者模型; 15 | * @company ccxcredit 16 | * @date 2019/5/20-17:06 17 | */ 18 | public class ProductAndConsumerDemo02 { 19 | /** 20 | * 定义一个容器,容器中有 21 | */ 22 | 23 | //AtomicInteger count = new AtomicInteger(0); 24 | 25 | 26 | 27 | public static void main(String[] args) { 28 | ArrayBlockingQueue productArrayBlockingQueue = new ArrayBlockingQueue<>(10); 29 | AtomicInteger count = new AtomicInteger(0); 30 | ExecutorService executorService = Executors.newFixedThreadPool(8); 31 | for(int i = 0;i<25;i++){ 32 | Produce produce = new Produce(productArrayBlockingQueue,count); 33 | executorService.submit(produce); 34 | } 35 | for (int i =0;i<20;i++){ 36 | Consumer consumer = new Consumer(productArrayBlockingQueue,count); 37 | executorService.submit(consumer); 38 | } 39 | 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.service; 2 | 3 | import com.example.springbootdemoentity.entity.User; 4 | import com.example.springbootdemothread.dao.UserMapper; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.io.Serializable; 11 | import java.util.List; 12 | 13 | @Service 14 | public class UserService implements Serializable { 15 | @Autowired 16 | private UserMapper userMapper; 17 | 18 | public User getUser(){ 19 | return userMapper.getUser(); 20 | } 21 | public List getPageUser(){ 22 | return userMapper.getPageUser(); 23 | } 24 | 25 | @Override 26 | protected Object clone() throws CloneNotSupportedException { 27 | return super.clone(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/java/com/example/springbootdemothread/utils/WriteUtils.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemothread.utils; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.File; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | 8 | public class WriteUtils { 9 | public static void writeFiles(int i) throws IOException { 10 | String path ="E:\\file\\file\\"+i+".txt"; 11 | File file =new File(path); 12 | 13 | //if file doesnt exists, then create it 14 | if(!file.exists()){ 15 | file.createNewFile(); 16 | } 17 | String data = i +" This content will append to the end of the file"+"----------"; 18 | /*FileWriter fileWritter = new FileWriter(file.getName(),true); 19 | fileWritter.write(data); 20 | fileWritter.close();*/ 21 | FileWriter fw = new FileWriter(file.getAbsoluteFile()); 22 | BufferedWriter bw = new BufferedWriter(fw); 23 | bw.write(data); 24 | bw.close(); 25 | } 26 | 27 | public static void main(String[] args) { 28 | try { 29 | writeFiles(1); 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 7003 3 | servlet: 4 | context-path: /thread 5 | eureka: 6 | client: 7 | service-url: 8 | defaultZone: http://localhost:5060/eureka/eureka 9 | #eureka: 10 | # client: 11 | # service-url: 12 | # defaultZone: http://localhost:7070/eureka/eureka 13 | spring: 14 | application: 15 | name: product-server 16 | datasource: 17 | url: jdbc:mysql://localhost:3306/mysql?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 18 | username: root 19 | password: 5Wy43g&mvI+u 20 | #type: com.alibaba.druid.pool.DruidDataSource 21 | main: 22 | allow-bean-definition-overriding: true 23 | mybatis: 24 | mapper-locations: classpath:mapper/*.xml 25 | pagehelper: 26 | helper-dialect: mysql 27 | reasonable: true 28 | support-methods-arguments: true 29 | params: count=countsql 30 | returnPageInfo: check 31 | 32 | -------------------------------------------------------------------------------- /springbootdemo-thread/src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 12 | 18 | -------------------------------------------------------------------------------- /springbootdemo-token/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | springbootdemo 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | com.example 12 | springbootdemo-token 13 | 0.0.1-SNAPSHOT 14 | springbootdemo-token 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-test 30 | test 31 | 32 | 33 | 34 | com.auth0 35 | java-jwt 36 | 3.2.0 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-data-redis 41 | 42 | 43 | org.springframework.session 44 | spring-session-data-redis 45 | 46 | 47 | org.springframework.data 48 | spring-data-redis 49 | 50 | 51 | redis.clients 52 | jedis 53 | 54 | 55 | ccx.credit.data 56 | data-util 57 | 1.0 58 | 59 | 60 | cn.hutool 61 | hutool-all 62 | 4.1.12 63 | 64 | 65 | javax.mail 66 | mail 67 | 1.4.7 68 | 69 | 70 | eu.bitwalker 71 | UserAgentUtils 72 | 1.20 73 | 74 | 75 | org.apache.httpcomponents 76 | httpclient 77 | 4.5.13 78 | 79 | 80 | org.apache.httpcomponents 81 | httpmime 82 | 4.5.3 83 | 84 | 85 | com.alibaba 86 | fastjson 87 | 1.2.31 88 | 89 | 90 | 91 | 92 | 93 | 94 | org.springframework.boot 95 | spring-boot-maven-plugin 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/SpringbootdemoTokenApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.servlet.ServletComponentScan; 6 | import org.springframework.cloud.netflix.eureka.EnableEurekaClient; 7 | 8 | @SpringBootApplication 9 | @EnableEurekaClient 10 | @ServletComponentScan() 11 | public class SpringbootdemoTokenApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringbootdemoTokenApplication.class, args); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/consts/HttpConst.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.consts; 2 | 3 | 4 | /** 5 | * 客户端请求,返回编码 6 | * @author zhaozhengyang 7 | */ 8 | public class HttpConst { 9 | 10 | /** 11 | * 服务器成功返回用户请求的数据 12 | */ 13 | public final static Integer OK = 200; 14 | 15 | /** 16 | * 用户新建或修改数据成功 17 | */ 18 | public final static Integer CREATED = 201; 19 | /** 20 | * 受认可的资源 21 | */ 22 | public final static Integer ACCEPTED = 202; 23 | /** 24 | * 客户端创建/修改失败 25 | */ 26 | public final static Integer CREATEFTD = 203; 27 | /** 28 | * 用户删除数据成功 29 | */ 30 | public final static Integer NOCONTENT = 204; 31 | /** 32 | * 客户端删除失败 33 | */ 34 | public final static Integer DELETEFTD = 205; 35 | /** 36 | * 用户发出的请求有错误,服务器没有进行操作 37 | */ 38 | public final static Integer BADREQUEST = 400; 39 | /** 40 | * 用户没有授权(令牌、用户名、密码错误) 41 | */ 42 | public final static Integer UNAUTHORIZED = 401; 43 | 44 | /** 45 | * 错误的密码或凭证 46 | */ 47 | public final static Integer PWD = 402; 48 | /** 49 | * 用户得到授权,但是无权限操作 50 | */ 51 | public final static Integer FORBIDDEN = 403; 52 | /** 53 | * 用户发出的请求针对的是不存在的记录,服务器没有进行操作 54 | */ 55 | public final static Integer NOTFOUND = 404; 56 | /** 57 | * 客户端被拒绝的请求 58 | */ 59 | public final static Integer NOTALLOWED = 405; 60 | /** 61 | * 服务器发生错误 62 | */ 63 | public final static Integer SERVERERROE = 500; 64 | /** 65 | * 服务器当前不能处理请求 66 | */ 67 | public final static Integer SERVERUNAVAILABLE = 503; 68 | 69 | } 70 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/consts/SysConst.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.consts; 2 | 3 | /** 4 | * @author zhaozhengyang 5 | * @date 2018/05/18 10:06 6 | */ 7 | public enum SysConst { 8 | /** 9 | * 系统设定 10 | */ 11 | DEV(8096, "development"), 12 | PRO(8080, "product"), 13 | APP(1, "APP"), 14 | WEB(2, "WEB"), 15 | PAD(3, "PAD"), 16 | 17 | /** 18 | * 客户端请求,返回编码 19 | */ 20 | OK(HttpConst.OK, "服务器成功返回用户请求的数据"), 21 | ERROR(HttpConst.SERVERERROE, "操作数据失败"), 22 | 23 | PWD(HttpConst.PWD, "错误的密码或登录帐号,请检查"), 24 | PWDSIMPLE(HttpConst.PWD, "密码太简单,请重新设置"), 25 | PHONEUNFOND(HttpConst.PWD, "手机号未录入,请完善个人信息"), 26 | SHIROUSERNOTFOUND(HttpConst.PWD, "用户不存在,请联系管理员"), 27 | DEPTNOTFOUND(HttpConst.PWD, "操作部门无效,请联系管理员"), 28 | CREATED(HttpConst.CREATED, "用户新建数据成功"), 29 | UPDATED(HttpConst.CREATED, "用户修改数据成功"), 30 | ACCEPTED(HttpConst.ACCEPTED, "受认可的资源"), 31 | CREATEFTD(HttpConst.CREATEFTD, "客户端创建数据失败"), 32 | UPDATEFTD(HttpConst.CREATEFTD, "客户端修改数据失败"), 33 | NOCONTENT(HttpConst.NOCONTENT, "用户删除数据成功"), 34 | DELETED(HttpConst.OK, "客户端删除数据成功"), 35 | DELETEFTD(HttpConst.DELETEFTD, "客户端删除数据失败"), 36 | BADREQUEST(HttpConst.BADREQUEST, "用户发出的请求有错误"), 37 | UNAUTHORIZED(HttpConst.UNAUTHORIZED, "客户端没有授权的请求"), 38 | FORBIDDEN(HttpConst.FORBIDDEN, "客户端被禁止的请求"), 39 | NOTFOUND(HttpConst.NOTFOUND, "未知的资源响应"), 40 | NOTALLOWED(HttpConst.NOTALLOWED, "客户端被拒绝的请求"), 41 | SERVERERROE(HttpConst.SERVERERROE, "服务器发送未知的错误"), 42 | SERVERUNAVAILABLE(HttpConst.SERVERUNAVAILABLE, "服务器当前不能处理请求"), 43 | 44 | /** 45 | * 异常处理编码 46 | */ 47 | IPEXCEPTION(HttpConst.NOTALLOWED, "IP访问异常"), 48 | TOKENEXCEPTION(HttpConst.NOTALLOWED, "Token认证异常"), 49 | XSSSQLEXCEPTION(HttpConst.NOTALLOWED, "XSS-SQL验证异常"), 50 | PERMISSIONEXCEPTION(HttpConst.NOTALLOWED, "权限验证异常"), 51 | 52 | NULLPOINTEREXCEPTION(20101, "空指针引用异常"), 53 | CLASSCASTEXCEPTION(20102, "类型强制转换异常"), 54 | ILLEGALARGUMENTEXCEPTION(20103, "传递非法参数异常"), 55 | ARITHMETICEXCEPTION(20104, "算术运算异常"), 56 | ARRAYSTOREEXCEPTION(20105, "向数组中存放与声明类型不兼容对象异常"), 57 | INDEXOUTOFBOUNDSEXCEPTION(20106, "下标越界异常"), 58 | NEGATIVEARRAYSIZEEXCEPTION(20107, "创建一个大小为负数的数组错误异常"), 59 | NUMBERFORMATEXCEPTION(20108, "数字格式异常"), 60 | SECURITYEXCEPTION(20109, "安全异常"), 61 | UNSUPPORTEDOPERATIONEXCEPTION(20110, "不支持的操作异常"), 62 | SQLEXCEPTION(20111, "SQL执行异常"), 63 | IOEXCEPTION(20112, "IO流(输入输出)异常"), 64 | NOSUCHMETHODEXCEPTION(20113, "方法未找到异常"), 65 | DATETIMEEXCEPTION(20114, "日期时间解析异常"), 66 | RSPONSECOMMONERROR(20115, "少见异常的异常"), 67 | 68 | 69 | /** 70 | * TOKEN设定 71 | */ 72 | TOKENSECRET(1, "X#$%(201805011201)(#*!()!CCX<273148:55DELL>?N<{SX"), 73 | TOKENALG(2, "HS256"), 74 | TOKENTYP(3, "JWT"), 75 | TOKENEXPTIME(4, "4"), 76 | TOKENPREFIX(5,"jwt_cache:") 77 | ; 78 | 79 | /** 80 | * 返回编码 81 | */ 82 | Integer code; 83 | 84 | /** 85 | * 消息描述 86 | */ 87 | String message; 88 | 89 | SysConst(Integer code, String message) { 90 | this.code = code; 91 | this.message = message; 92 | } 93 | 94 | public Integer getCode() { 95 | return code; 96 | } 97 | 98 | public void setCode(Integer code) { 99 | this.code = code; 100 | } 101 | 102 | public String getMessage() { 103 | return message; 104 | } 105 | 106 | 107 | public String getValue() { 108 | return message; 109 | } 110 | 111 | public void setMessage(String message) { 112 | this.message = message; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/exceptions/BaseException.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.exceptions; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | 5 | 6 | /** 7 | * 异常基类 8 | * @author zhaozhengyang 9 | */ 10 | public class BaseException extends RuntimeException { 11 | 12 | public static final ObjectMapper JsonUtils = new ObjectMapper(); 13 | 14 | public BaseException() { 15 | } 16 | 17 | public BaseException(String message) { 18 | super(message); 19 | } 20 | 21 | public BaseException(String message, Throwable cause) { 22 | super(message, cause); 23 | } 24 | 25 | public BaseException(Throwable cause) { 26 | super(cause); 27 | } 28 | 29 | public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 30 | super(message, cause, enableSuppression, writableStackTrace); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/exceptions/TokenException.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.exceptions; 2 | 3 | 4 | import com.example.springbootdemotoken.consts.SysConst; 5 | 6 | public class TokenException extends BaseException { 7 | 8 | /** 9 | * 异常码 10 | */ 11 | private int code; 12 | /** 13 | * 异常信息 14 | */ 15 | private String message; 16 | 17 | public TokenException(int code, String message) { 18 | this.code = code; 19 | this.message = message; 20 | } 21 | 22 | public TokenException(SysConst cnt) { 23 | this.code = cnt.getCode(); 24 | this.message = cnt.getMessage(); 25 | } 26 | 27 | public int getCode() { 28 | return code; 29 | } 30 | 31 | @Override 32 | public String getMessage() { 33 | return message; 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/extend/BodyReaderHttpRequestWrapper.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.extend; 2 | 3 | import com.example.springbootdemotoken.utils.HttpUtils; 4 | 5 | import javax.servlet.ReadListener; 6 | import javax.servlet.ServletInputStream; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletRequestWrapper; 9 | import java.io.*; 10 | import java.nio.charset.Charset; 11 | import java.util.Enumeration; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | public class BodyReaderHttpRequestWrapper extends HttpServletRequestWrapper { 16 | 17 | private final byte[] body; 18 | private Map header = new HashMap<>(16); 19 | 20 | public BodyReaderHttpRequestWrapper(HttpServletRequest request) throws IOException { 21 | super(request); 22 | Enumeration e = request.getHeaderNames(); 23 | while (e.hasMoreElements()) { 24 | String name = (String) e.nextElement(); 25 | header.put(name, request.getHeader(name)); 26 | } 27 | body = HttpUtils.getBodyString(request).getBytes(Charset.forName("UTF-8")); 28 | } 29 | 30 | @Override 31 | public BufferedReader getReader() throws IOException { 32 | return new BufferedReader(new InputStreamReader(getInputStream())); 33 | } 34 | 35 | @Override 36 | public ServletInputStream getInputStream() throws IOException { 37 | 38 | final ByteArrayInputStream bais = new ByteArrayInputStream(body); 39 | 40 | return new ServletInputStream() { 41 | public boolean isFinished() { 42 | return false; 43 | } 44 | 45 | public boolean isReady() { 46 | return false; 47 | } 48 | 49 | public void setReadListener(ReadListener listener) { 50 | 51 | } 52 | 53 | @Override 54 | public int read() throws IOException { 55 | return bais.read(); 56 | } 57 | 58 | }; 59 | } 60 | 61 | @Override 62 | public String getHeader(String name) { 63 | return super.getHeader(name); 64 | } 65 | 66 | @Override 67 | public Enumeration getHeaderNames() { 68 | return super.getHeaderNames(); 69 | } 70 | 71 | @Override 72 | public Enumeration getHeaders(String name) { 73 | return super.getHeaders(name); 74 | } 75 | 76 | /** 77 | *
获取HttpRequest的body数据:
78 | * 79 | * @return java.lang.String 80 | * @throws 81 | * @author iwinkfc 82 | * @create 2018/1/15 0015 - 21:52 83 | */ 84 | public String getBody() { 85 | try { 86 | return new String(this.body, "UTF-8"); 87 | } catch (UnsupportedEncodingException e) { 88 | e.printStackTrace(); 89 | } 90 | return null; 91 | } 92 | 93 | /** 94 | *
获取HttpRequest的header数据:
95 | * 96 | * @return java.util.Map 97 | * @throws 98 | * @author iwinkfc 99 | * @create 2018/1/15 0015 - 21:51 100 | */ 101 | public Map getHeader() { 102 | return this.header; 103 | } 104 | } -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/extend/BodyReaderHttpResponseWrapper.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.extend; 2 | 3 | import javax.servlet.ServletOutputStream; 4 | import javax.servlet.WriteListener; 5 | import javax.servlet.http.HttpServletResponse; 6 | import javax.servlet.http.HttpServletResponseWrapper; 7 | import java.io.ByteArrayOutputStream; 8 | import java.io.IOException; 9 | import java.io.PrintWriter; 10 | 11 | public class BodyReaderHttpResponseWrapper extends HttpServletResponseWrapper { 12 | 13 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 14 | PrintWriter printWriter = new PrintWriter(byteArrayOutputStream); 15 | 16 | public BodyReaderHttpResponseWrapper(HttpServletResponse response) throws IOException { 17 | super(response); 18 | } 19 | 20 | /** 21 | * 覆盖getWriter()方法,将字符流缓冲到本地 22 | */ 23 | @Override 24 | public PrintWriter getWriter() throws IOException { 25 | return printWriter; 26 | } 27 | 28 | /** 29 | * 覆盖getOutputStream()方法,将字节流缓冲到本地 30 | */ 31 | @Override 32 | public ServletOutputStream getOutputStream() throws IOException { 33 | return new ServletOutputStream() { 34 | public boolean isReady() { 35 | return false; 36 | } 37 | 38 | public void setWriteListener(WriteListener listener) { 39 | 40 | } 41 | 42 | @Override 43 | public void write(int b) throws IOException { 44 | byteArrayOutputStream.write(b); 45 | } 46 | }; 47 | } 48 | 49 | /** 50 | * 把缓冲区内容写入输出流后关闭 51 | * 52 | * @author xxj 53 | */ 54 | public void flush() { 55 | try { 56 | printWriter.flush(); 57 | printWriter.close(); 58 | byteArrayOutputStream.flush(); 59 | byteArrayOutputStream.close(); 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | } 63 | } 64 | 65 | /** 66 | * 获取字节流 67 | * 68 | * @return 69 | */ 70 | public ByteArrayOutputStream getByteArrayOutputStream() { 71 | return byteArrayOutputStream; 72 | } 73 | 74 | /** 75 | * 将换出区内容转为文本输出 76 | * 77 | * @return 78 | */ 79 | public String getTextContent() { 80 | flush(); 81 | return byteArrayOutputStream.toString(); 82 | } 83 | } -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/filter/BaseFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.filter; 2 | 3 | import com.example.springbootdemotoken.consts.SysConst; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import javax.servlet.*; 7 | import java.io.IOException; 8 | import java.io.PrintWriter; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | public interface BaseFilter extends Filter { 13 | 14 | ObjectMapper JSON = new ObjectMapper(); 15 | 16 | @Override 17 | void init(FilterConfig filterConfig) throws ServletException; 18 | 19 | @Override 20 | void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException; 21 | 22 | @Override 23 | void destroy(); 24 | 25 | default void pushResponseError(ServletResponse response, SysConst cnt) { 26 | response.setContentType("text/json; charset=UTF-8"); 27 | Map resMap = new HashMap<>(); 28 | resMap.put("code", cnt.getCode()); 29 | resMap.put("data", cnt.getValue()); 30 | resMap.put("message", cnt.getMessage()); 31 | try { 32 | PrintWriter out = response.getWriter(); 33 | out.println(JSON.writeValueAsString(resMap)); 34 | out.flush(); 35 | out.close(); 36 | } catch (IOException e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/filter/TokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.filter; 2 | 3 | 4 | import com.example.springbootdemotoken.consts.SysConst; 5 | import com.example.springbootdemotoken.extend.BodyReaderHttpRequestWrapper; 6 | import com.example.springbootdemotoken.tokens.JsonWebToken; 7 | import com.example.springbootdemotoken.utils.FileUtils; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import javax.servlet.*; 12 | import javax.servlet.annotation.WebFilter; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | /** 21 | * @Title: TokenFilter 22 | * @ProjectName springbootdemo 23 | * @Description: TODO 24 | * @author YangPeng 25 | * @company ccxcredit 26 | * @date 2019/9/27-11:18 27 | */ 28 | @WebFilter 29 | public class TokenFilter implements BaseFilter{ 30 | 31 | private static Logger logger = LoggerFactory.getLogger(TokenFilter.class); 32 | 33 | private static List WHITEURLS = new ArrayList<>(); 34 | @Override 35 | public void init(FilterConfig config) throws ServletException { 36 | // 读取文件 37 | try { 38 | 39 | if (!SysConst.DEV.getValue().equals(config.getInitParameter("level"))) { 40 | InputStream stream = getClass().getClassLoader().getResourceAsStream("static/tokenWhite.txt") ; 41 | WHITEURLS = FileUtils.readWhiteFile(stream); 42 | } else { 43 | logger.debug(config.getInitParameter("level")); 44 | } 45 | } catch (Exception e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | 50 | @Override 51 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 52 | 53 | HttpServletRequest request = (HttpServletRequest) servletRequest; 54 | HttpServletResponse response = (HttpServletResponse) servletResponse; 55 | 56 | response.setCharacterEncoding("UTF-8"); 57 | response.setContentType("text/json;charset=UTF-8"); 58 | 59 | String tmp = request.getRequestURI(); 60 | String token = null; 61 | request = new BodyReaderHttpRequestWrapper(request); 62 | if (!FileUtils.isWhiteBeg(request.getRequestURI(), WHITEURLS)) { 63 | token = request.getHeader("token"); 64 | if (null == JsonWebToken.verifyToken(token)) { 65 | pushResponseError(response, SysConst.TOKENEXCEPTION); 66 | return; 67 | } else { 68 | 69 | /* 70 | try { 71 | response.setHeader("token", JsonWebToken.updateToken(token)); 72 | } finally { 73 | }*/ 74 | } 75 | } 76 | 77 | response.setHeader("token", token); 78 | filterChain.doFilter(request, response); 79 | } 80 | 81 | @Override 82 | public void destroy() { 83 | 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/redis/JedisClusterConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.redis; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 5 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import redis.clients.jedis.HostAndPort; 9 | import redis.clients.jedis.JedisCluster; 10 | 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | @Configuration 15 | @ConditionalOnClass({JedisCluster.class}) 16 | @EnableConfigurationProperties(RedisProperties.class) 17 | public class JedisClusterConfig { 18 | @Autowired 19 | private RedisProperties redisProperties; 20 | 21 | 22 | @Bean 23 | public JedisCluster getJdeisCluster(){ 24 | String[] serverArray = redisProperties.getNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题) 25 | Set nodes = new HashSet<>(); 26 | 27 | for (String ipPort : serverArray) { 28 | String[] ipPortPair = ipPort.split(":"); 29 | nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim()))); 30 | } 31 | //return new JedisCluster(nodes,redisProperties.getCommandTimeout(), 6); 32 | return new JedisCluster(nodes,redisProperties.getCommandTimeout()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/redis/RedisProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.redis; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | @ConfigurationProperties(prefix = "spring.redis.cluster") 8 | public class RedisProperties { 9 | private int expireSeconds; 10 | private int commandTimeout; 11 | private String nodes; 12 | 13 | public int getExpireSeconds() { 14 | return expireSeconds; 15 | } 16 | 17 | public void setExpireSeconds(int expireSeconds) { 18 | this.expireSeconds = expireSeconds; 19 | } 20 | 21 | public int getCommandTimeout() { 22 | return commandTimeout; 23 | } 24 | 25 | public void setCommandTimeout(int commandTimeout) { 26 | this.commandTimeout = commandTimeout; 27 | } 28 | 29 | public String getNodes() { 30 | return nodes; 31 | } 32 | 33 | public void setNodes(String nodes) { 34 | this.nodes = nodes; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.utils; 2 | 3 | import eu.bitwalker.useragentutils.UserAgent; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import javax.mail.internet.MimeUtility; 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.io.*; 10 | import java.net.URLEncoder; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | *
处理上传下载中的文件中文编码
16 | * 17 | * @author 许言杰(qoodit.kfc) 18 | * @version v1.0 19 | * @create 2018/1/6 - 23:51 20 | * @email xuyanjie@qiaodit.com 21 | */ 22 | public class FileUtils extends cn.hutool.core.io.FileUtil { 23 | 24 | private static Logger logger = LoggerFactory.getLogger(FileUtils.class); 25 | 26 | /** 27 | * 设置下载文件中文件的名称 28 | * 29 | * @param filename 30 | * @param request 31 | * @return 通用浏览器文件码名 32 | */ 33 | public static String encodeFileName(String filename, HttpServletRequest request) { 34 | 35 | String encodedFileName; 36 | 37 | String browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser().getGroup().getName(); 38 | logger.error("logger:{ encodeFileName browser ===> [" + browser + "]}"); 39 | try { 40 | switch (browser) { 41 | case "Chrome": 42 | case "Internet Explorer": 43 | case "Safari": 44 | encodedFileName = URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"); 45 | break; 46 | case "Firefox": 47 | case "Opera": 48 | default: 49 | encodedFileName = MimeUtility.encodeWord(filename); 50 | break; 51 | } 52 | return encodedFileName; 53 | } catch (UnsupportedEncodingException e) { 54 | return filename; 55 | } 56 | } 57 | /** 58 | * 判断是否是白名单 59 | */ 60 | public static boolean isWhiteBeg(String requestUrl, List whiteList) { 61 | 62 | if (requestUrl.length() == 1 && "/".equals(requestUrl) 63 | || whiteList.size() <= 0) { 64 | return true; 65 | } else { 66 | for (String urlTemp : whiteList) { 67 | if (requestUrl.indexOf(urlTemp) > -1) { 68 | return true; 69 | } 70 | } 71 | } 72 | 73 | return false; 74 | } 75 | 76 | /** 77 | * 读取白名单配置文件 78 | */ 79 | public static List readWhiteFile(InputStream stream) { 80 | 81 | List list = new ArrayList<>(); 82 | String line; 83 | try (BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) { 84 | while ((line = br.readLine()) != null) { 85 | if ("".equals(line) || line.contains("#")) { 86 | } else { 87 | list.add(line); 88 | } 89 | } 90 | } catch (Exception e) { 91 | e.getLocalizedMessage(); 92 | } 93 | 94 | return list; 95 | } 96 | 97 | public static String GenerateFile(String imgSource, String savePath, String saveName, HttpServletRequest request) throws IOException { 98 | return null; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/utils/RedisCacheUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.utils; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Component; 5 | import redis.clients.jedis.JedisCluster; 6 | 7 | import javax.annotation.PostConstruct; 8 | import java.io.IOException; 9 | 10 | @Component 11 | public class RedisCacheUtil { 12 | @Autowired 13 | private JedisCluster jed; 14 | 15 | private static JedisCluster jedisCluster; 16 | 17 | public static JedisCluster getInstance(){ 18 | return jedisCluster; 19 | } 20 | 21 | @PostConstruct 22 | public void init(){ 23 | this.jedisCluster = jed; 24 | } 25 | public static boolean exists(String prefix,String key){ 26 | if(jedisCluster.exists(prefix+key)){ 27 | return true; 28 | }else{ 29 | return false; 30 | } 31 | } 32 | public static boolean exists(String key){ 33 | if(jedisCluster.exists(key)){ 34 | return true; 35 | }else{ 36 | return false; 37 | } 38 | } 39 | /** 40 | * 取出 缓存 数据 41 | * @param key 42 | * @return 43 | */ 44 | public static String get(String prefix,String key) { 45 | String value = jedisCluster.get(prefix+key); 46 | return value; 47 | } 48 | public static String get(String key) { 49 | String value = jedisCluster.get(key); 50 | return value; 51 | } 52 | /** 53 | * 存入缓存数据 54 | * @param key 55 | * @param value 56 | */ 57 | public static void set(String prefix,String key,String value) { 58 | jedisCluster.set(prefix+key, value); 59 | } 60 | public static void set(String key,String value) { 61 | jedisCluster.set(key, value); 62 | } 63 | 64 | /** 65 | * 删除 key 存贮 66 | * @param key 67 | * @return 68 | */ 69 | public static Long del(String prefix,String key) { 70 | Long value = jedisCluster.del(prefix+key); 71 | return value; 72 | } 73 | public static Long del(String key) { 74 | Long value = jedisCluster.del(key); 75 | return value; 76 | } 77 | 78 | /** 79 | * 关闭redis连接 80 | */ 81 | private static void closeJedis(JedisCluster jedisCluster) { 82 | if (jedisCluster != null) { 83 | try { 84 | jedisCluster.close(); 85 | } catch (IOException e) { 86 | e.printStackTrace(); 87 | } 88 | } 89 | } 90 | /** 91 | * 设置 过期时间 单位秒 92 | * @param key 93 | * @param value 94 | * @param seconds 95 | * @return 96 | */ 97 | public static void setTimeSecond(String key,String value,int seconds ) { 98 | jedisCluster.setex(key, seconds, value); 99 | } 100 | /** 101 | * 设置 过期时间 单位毫秒 102 | * @param key 103 | * @param value 104 | * @param milliseconds 105 | * @return 106 | */ 107 | public static void setTimeMilliseconds(String key,String value,long milliseconds ) { 108 | jedisCluster.psetex(key, milliseconds, value); 109 | } 110 | /** 111 | * 设置 过期时间 以天为单位 112 | * @param key 113 | * @param value 114 | * @param day 115 | * @return 116 | **/ 117 | public static void setTimeDay(String key,String value,int day ) { 118 | jedisCluster.psetex(key, day*24*60*60, value); 119 | } 120 | /** 121 | * 设置 过期时间 以小时为单位 122 | * @param key 123 | * @param value 124 | * @param Hour 125 | * @return 126 | **/ 127 | public static void setTimeHour(String key,String value,int Hour ) { 128 | jedisCluster.psetex(key, Hour*60*60, value); 129 | } 130 | /** 131 | * 设置 过期时间 以分钟为单位 132 | * @param key 133 | * @param value 134 | * @param minute 135 | * @return 136 | **/ 137 | public static void setTimeMinute(String key,String value,int minute ) { 138 | jedisCluster.psetex(key, minute*60, value); 139 | String string = jedisCluster.get(key); 140 | System.out.println(string); 141 | 142 | } 143 | 144 | /** 145 | * 自增:计数 146 | * @param key 已保存的key值 147 | */ 148 | public static void incr(String key){ 149 | jedisCluster.incr(key); 150 | 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/utils/StrUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.utils; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | /** 11 | * 12 | * @description 字符串工具类 13 | * @author zxr 14 | * @date 2017 下午1:13:46 15 | */ 16 | public class StrUtil extends StringUtils { 17 | 18 | /** 19 | *

处理从Map中取出的Null值,默认返回空字符串

20 | *
 21 | 	 * Map: {name=sinba,age=11}
 22 | 	 * StrUtil.fixNull( map.get("noSuchKey") )  =  ""
 23 | 	 * StrUtil.fixNull( map.get("name") )       =  "sinba"
 24 | 	 * StrUtil.fixNull( map.get("age") )        =  "11"
 25 | 	 * @param o
 26 | 	 * @return
 27 | 	 * 
28 | */ 29 | public static String fixNull(Object o) { 30 | return o == null ? "" : o.toString().trim(); 31 | } 32 | 33 | /** 34 | * 处理空值 35 | * @param o 36 | * @param defaulStr 37 | * @return 38 | */ 39 | public static String fixNull(Object o, String defaulStr) { 40 | return o == null ? defaulStr : o.toString().trim(); 41 | } 42 | 43 | /** 44 | * 处理BigDecimal Null值 45 | * @param value 46 | * @return 47 | */ 48 | public static BigDecimal fixBigDecimal(BigDecimal value) { 49 | if (value == null) { 50 | return BigDecimal.ZERO; 51 | } 52 | return value; 53 | } 54 | 55 | /** 56 | * 去掉字符串前面的空格 57 | * @param original 58 | * @return 59 | */ 60 | public static String beforeTrim(String original) { 61 | if (original == null || original.trim().length() == 0) { 62 | return original; 63 | } 64 | int len = original.length(); 65 | int st = 0; 66 | int off = 0; /* avoid getfield opcode */ 67 | char[] originalValue = original.toCharArray(); 68 | char[] val = Arrays.copyOfRange(originalValue, off, off + len); 69 | ; /* avoid getfield opcode */ 70 | 71 | while ((st < len) && (val[off + st] <= ' ')) { 72 | st++; 73 | } 74 | return ((st > 0) || (st < len)) ? original.substring(st, len) : ""; 75 | } 76 | 77 | /** 78 | * 去掉字符串后面的空格 79 | * @param original 80 | * @return 81 | */ 82 | public static String afterTrim(String original) { 83 | if (original == null || original.trim().length() == 0) { 84 | return original; 85 | } 86 | int len = original.length(); 87 | int st = 0; 88 | int off = 0; /* avoid getfield opcode */ 89 | char[] originalValue = original.toCharArray(); 90 | char[] val = Arrays.copyOfRange(originalValue, off, off + len); /* avoid getfield opcode */ 91 | 92 | while ((st < len) && (val[off + len - 1] <= ' ')) { 93 | len--; 94 | } 95 | return ((st > 0) || (st < len)) ? original.substring(st, len) : ""; 96 | } 97 | 98 | /** 99 | * 字符串转list 100 | * @param str 101 | * @param splitBy 102 | * @return 103 | */ 104 | public static List splitToList(String str, String splitBy) { 105 | if (StringUtils.isBlank(str)) { 106 | return null; 107 | } 108 | String[] arrays = str.split(splitBy); 109 | List list = new ArrayList(); 110 | for (int i = 0; i < arrays.length; i++) { 111 | list.add(arrays[i].trim()); 112 | } 113 | return list; 114 | } 115 | 116 | /** 117 | * 118 | * @param str 119 | * @param splitBy 120 | * @return 121 | */ 122 | public static List splitToLongList(String str, String splitBy) { 123 | if (StringUtils.isBlank(str)) { 124 | return null; 125 | } 126 | String[] arrays = str.split(splitBy); 127 | List list = new ArrayList(); 128 | for (int i = 0; i < arrays.length; i++) { 129 | list.add(Long.parseLong(arrays[i].trim())); 130 | } 131 | return list; 132 | } 133 | 134 | /** 135 | * 将数据库表字段转化为实体类属性 136 | * e.g. user_info --> userInfo 137 | * @param columnName 138 | * @return 139 | */ 140 | public static String toCamelStyle(String columnName) { 141 | StringBuffer sb = new StringBuffer(); 142 | boolean match = false; 143 | for (int i = 0; i < columnName.length(); i++) { 144 | char ch = columnName.charAt(i); 145 | if (match && ch >= 97 && ch <= 122) { 146 | ch -= 32; 147 | } 148 | if (ch != '_') { 149 | match = false; 150 | sb.append(ch); 151 | } else { 152 | match = true; 153 | } 154 | } 155 | return sb.toString(); 156 | } 157 | 158 | /** 159 | * 将驼峰命名法转化为下划线的形式 160 | * e.g. UserInfo --> user_info loginId --> login_id 161 | * @param name 162 | * @return 163 | */ 164 | public static String addUnderscores(String name) { 165 | StringBuffer buf = new StringBuffer(name.replace('.', '_')); 166 | for (int i = 1; i < buf.length() - 1; i++) { 167 | if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i)) && Character.isLowerCase(buf.charAt(i + 1))) { 168 | buf.insert(i++, '_'); 169 | } 170 | } 171 | return buf.toString().toLowerCase(); 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/java/com/example/springbootdemotoken/webController/WebController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken.webController; 2 | 3 | 4 | import com.example.springbootdemotoken.tokens.JsonWebToken; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * @Title: WebController 13 | * @ProjectName springbootdemo 14 | * @Description: TODO 15 | * @author YangPeng 16 | * @company ccxcredit 17 | * @date 2019/9/26-17:17 18 | */ 19 | @RestController 20 | public class WebController { 21 | 22 | @RequestMapping(value = "/getStr") 23 | public String getStr(String str){ 24 | Map map = new HashMap<>(); 25 | map.put("name","yangpeng"); 26 | map.put("userId","123221"); 27 | String token = JsonWebToken.createToken(map); 28 | return token+"----"; 29 | } 30 | 31 | @RequestMapping(value = "/crossToken") 32 | public String crossToken(){ 33 | return "token验证成功"; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 7006 3 | servlet: 4 | context-path: /token 5 | eureka: 6 | client: 7 | service-url: 8 | defaultZone: http://localhost:5060/eureka/eureka 9 | spring: 10 | redis: 11 | cluster: 12 | expire-seconds: 120 13 | command-timeout: 5000 14 | nodes: namenode22:6379,datanode23:6379,datanode24:6379,datanode25:6379,datanode26:6379,datanode27:6379 15 | -------------------------------------------------------------------------------- /springbootdemo-token/src/main/resources/static/tokenWhite.txt: -------------------------------------------------------------------------------- 1 | /web 2 | /getStr -------------------------------------------------------------------------------- /springbootdemo-token/src/test/java/com/example/springbootdemotoken/SpringbootdemoTokenApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootdemotoken; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootdemoTokenApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------