├── .gitignore
├── Cache-SpringBoot
├── README.MD
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── skypyb
│ │ ├── CacheDemoApplication.java
│ │ ├── entity
│ │ └── User.java
│ │ └── service
│ │ └── UserService.java
│ └── test
│ └── java
│ └── CacheTest.java
├── Event-Springboot
├── README.md
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── skypyb
│ │ ├── EventApplication.java
│ │ ├── config
│ │ └── MyAsyncConfigurer.java
│ │ ├── entity
│ │ └── User.java
│ │ ├── event
│ │ └── UserRegisterEvent.java
│ │ ├── listener
│ │ └── InitializationListener.java
│ │ └── service
│ │ ├── MailService.java
│ │ └── UserService.java
│ └── test
│ └── java
│ └── com
│ └── skypyb
│ └── EventTest.java
├── LICENSE
├── README.md
├── RabbitMQ-SpringBoot
├── README.md
├── RabbitMQ-Consumer
│ ├── build.gradle
│ ├── gradlew
│ ├── gradlew.bat
│ ├── out
│ │ └── production
│ │ │ └── resources
│ │ │ └── application.yml
│ ├── settings.gradle
│ └── src
│ │ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── skypyb
│ │ │ │ └── rabbitmq
│ │ │ │ ├── Application.java
│ │ │ │ ├── config
│ │ │ │ ├── RabbitBindConfig.java
│ │ │ │ └── RabbitMQCoreConfig.java
│ │ │ │ ├── controller
│ │ │ │ ├── DeadReceiver.java
│ │ │ │ ├── DelayReceiver.java
│ │ │ │ └── User1Receiver.java
│ │ │ │ └── entity
│ │ │ │ └── User1.java
│ │ └── resources
│ │ │ └── application.yml
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── skypyb
│ │ └── test
│ │ └── RabbitmqTest.java
└── RabbitMQ-Producer
│ ├── build.gradle
│ ├── gradlew
│ ├── gradlew.bat
│ ├── out
│ └── production
│ │ └── resources
│ │ └── application.yml
│ ├── settings.gradle
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── rabbitmq
│ │ │ ├── Application.java
│ │ │ ├── entity
│ │ │ └── User1.java
│ │ │ └── producer
│ │ │ └── User1Sender.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── com
│ └── skypyb
│ └── test
│ └── RabbitmqTest.java
├── WebSocket
├── README.md
└── websocket
│ ├── build.gradle
│ ├── gradlew
│ ├── gradlew.bat
│ ├── out
│ └── production
│ │ └── resources
│ │ ├── application.yml
│ │ └── view
│ │ └── index.html
│ ├── settings.gradle
│ └── src
│ └── main
│ ├── java
│ └── com
│ │ └── skypyb
│ │ ├── WebSocketApplication.java
│ │ ├── scheduled
│ │ ├── SchedulerConfig.java
│ │ └── WebSocketSendMessageScheduled.java
│ │ ├── springboot_websocket
│ │ ├── MyWebSocketHandler.java
│ │ └── WebSocketConfigTwo.java
│ │ └── websocket
│ │ ├── WebSocketConfigOne.java
│ │ └── WebSocketServerOne.java
│ └── resources
│ ├── application.yml
│ └── view
│ └── index.html
├── distributed-lock
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ ├── DemoApplication.java
│ │ │ ├── config
│ │ │ └── RedisConfig.java
│ │ │ ├── lock
│ │ │ ├── DistributedLock.java
│ │ │ └── RedisLock.java
│ │ │ └── semaphore
│ │ │ ├── DistributedSemaphore.java
│ │ │ ├── RedisSemaphore.java
│ │ │ └── SemaphoreInfo.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── com
│ └── skypyb
│ ├── DistributedLockTest.java
│ └── DistributedSemaphoreTest.java
├── dubbo-springboot
├── README.md
├── docker-compose.zookeeper.yml
├── dubbo-user-service-api
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── com
│ │ └── skypyb
│ │ └── dubbo
│ │ └── service
│ │ └── user
│ │ └── api
│ │ └── UserService.java
├── dubbo-user-service-consumer
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── skypyb
│ │ │ │ └── dubbo
│ │ │ │ └── user
│ │ │ │ └── service
│ │ │ │ └── consumer
│ │ │ │ ├── DubboUserServiceConsumerApplication.java
│ │ │ │ ├── config
│ │ │ │ └── HystrixConfig.java
│ │ │ │ └── controller
│ │ │ │ └── UserController.java
│ │ └── resources
│ │ │ └── application.yml
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── skypyb
│ │ └── dubbo
│ │ └── user
│ │ └── service
│ │ └── consumer
│ │ └── DubboUserServiceConsumerApplicationTests.java
└── dubbo-user-service-provider
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── dubbo
│ │ │ └── user
│ │ │ └── service
│ │ │ └── provider
│ │ │ ├── DubboUserServiceProviderApplication.java
│ │ │ └── api
│ │ │ └── impl
│ │ │ └── UserServiceImpl.java
│ └── resources
│ │ └── application.yml
│ └── test
│ └── java
│ └── com
│ └── skypyb
│ └── dubbo
│ └── user
│ └── service
│ └── provider
│ └── DubboUserServiceProviderApplicationTests.java
├── sc-demo-alibaba
├── README.md
├── sc-demo-alibaba-consumer
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── provider
│ │ │ ├── NacosConsumerApplication.java
│ │ │ ├── config
│ │ │ └── RestConfiguration.java
│ │ │ ├── controller
│ │ │ └── NacosConsumerController.java
│ │ │ ├── fallback
│ │ │ └── HelloServiceFallback.java
│ │ │ └── feign
│ │ │ └── NacosHelloFeign.java
│ │ └── resources
│ │ └── application.yml
├── sc-demo-alibaba-dependencies
│ └── pom.xml
├── sc-demo-alibaba-gateway
│ ├── pom.xml
│ └── src
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── gateway
│ │ │ ├── GatewayApplication.java
│ │ │ ├── config
│ │ │ ├── GatewayRateLimiterConfig.java
│ │ │ └── RedisConfig.java
│ │ │ └── filter
│ │ │ └── all
│ │ │ └── AuthFilter.java
│ │ └── resources
│ │ └── application.yml
└── sc-demo-alibaba-provider
│ ├── pom.xml
│ └── src
│ └── main
│ ├── java
│ └── com
│ │ └── skypyb
│ │ └── provider
│ │ ├── NacosProviderApplication.java
│ │ └── controller
│ │ └── NacosProviderController.java
│ └── resources
│ └── application.yml
├── sc-demo-microservice
├── build.gradle
├── gradlew
├── gradlew.bat
├── sc-demo-microservice-eureka
│ ├── build.gradle
│ ├── out
│ │ └── production
│ │ │ └── resources
│ │ │ └── application.yml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── sc
│ │ │ ├── EurekaServerApplication.java
│ │ │ └── config
│ │ │ └── WebSecurityConfig.java
│ │ └── resources
│ │ └── application.yml
├── sc-demo-microservice-movie
│ ├── build.gradle
│ ├── out
│ │ └── production
│ │ │ └── resources
│ │ │ └── application.yml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── sc
│ │ │ ├── MovieApplication.java
│ │ │ ├── config
│ │ │ ├── FeignConfiguration.java
│ │ │ └── RestConfig.java
│ │ │ ├── controller
│ │ │ └── MovieController.java
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ ├── feign
│ │ │ └── UserFeignClient.java
│ │ │ └── hystrix
│ │ │ └── UserFeignFallback.java
│ │ └── resources
│ │ └── application.yml
├── sc-demo-microservice-user
│ ├── build.gradle
│ ├── out
│ │ └── production
│ │ │ └── resources
│ │ │ ├── application.yml
│ │ │ └── schema.sql
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── sc
│ │ │ ├── UserApplication.java
│ │ │ ├── controller
│ │ │ └── UserController.java
│ │ │ ├── dao
│ │ │ └── UserDao.java
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ └── service
│ │ │ └── UserService.java
│ │ └── resources
│ │ ├── application.yml
│ │ └── schema.sql
├── sc-demo-microservice-zuul
│ ├── build.gradle
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── sc
│ │ │ ├── ZuulApplication.java
│ │ │ ├── config
│ │ │ ├── RestConfig.java
│ │ │ └── ZuulFilterConfig.java
│ │ │ ├── controller
│ │ │ ├── AggregationController.java
│ │ │ └── LocalController.java
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ └── hystrix
│ │ │ └── UserMicroserviceFallBack.java
│ │ └── resources
│ │ └── application.yml
└── settings.gradle
├── shardingsphere-springboot
└── sharding-jdbc
│ ├── build.gradle
│ ├── settings.gradle
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── skypyb
│ │ │ └── demo
│ │ │ └── sharding
│ │ │ ├── ShardingJDBCApplication.java
│ │ │ └── order
│ │ │ ├── dao
│ │ │ └── OrderMapper.java
│ │ │ ├── entity
│ │ │ └── OrderDO.java
│ │ │ └── service
│ │ │ ├── OrderService.java
│ │ │ └── impl
│ │ │ └── OrderServiceImpl.java
│ └── resources
│ │ ├── application.yml
│ │ ├── init
│ │ └── schema.sql
│ │ └── mybatis
│ │ └── mapper
│ │ └── OrderMapper.xml
│ └── test
│ └── java
│ └── com
│ └── skypyb
│ └── test
│ └── shardingjdbc
│ └── ShardingSphereTest.java
├── spring-security-demo
├── README.md
├── pom.xml
├── spring-security-demo-dependencies
│ └── pom.xml
└── spring-security-demo-server
│ ├── pom.xml
│ └── src
│ └── main
│ ├── java
│ └── com
│ │ └── skypyb
│ │ ├── SecurityServerApplication.java
│ │ ├── security
│ │ ├── config
│ │ │ ├── SecurityConfiguration.java
│ │ │ └── SecurityProperties.java
│ │ ├── controller
│ │ │ └── advice
│ │ │ │ └── AuthenticationExceptionAdvice.java
│ │ ├── exception
│ │ │ ├── RequestValidationException.java
│ │ │ └── SecurityAuthException.java
│ │ ├── filter
│ │ │ ├── AuthenticationFailEntryPoint.java
│ │ │ ├── access
│ │ │ │ ├── JwtAccessDecisionManager.java
│ │ │ │ ├── JwtAuthenticationTokenFilter.java
│ │ │ │ ├── JwtFilterSecurityInterceptor.java
│ │ │ │ └── JwtInvocationSecurityMetadataSourceService.java
│ │ │ └── authentication
│ │ │ │ ├── CreateAuthenticationTokenFilter.java
│ │ │ │ └── OptionsRequestFilter.java
│ │ ├── model
│ │ │ ├── dto
│ │ │ │ └── AuthenticationUser.java
│ │ │ ├── request
│ │ │ │ └── AuthenticationRequest.java
│ │ │ └── response
│ │ │ │ ├── AuthenticationFailResponse.java
│ │ │ │ ├── AuthenticationResponse.java
│ │ │ │ ├── BasicResponse.java
│ │ │ │ └── ValidationFailResponse.java
│ │ ├── service
│ │ │ └── AuthenticationUserService.java
│ │ └── util
│ │ │ └── JwtTokenUtil.java
│ │ ├── test
│ │ └── controller
│ │ │ └── MethodProtectedRestController.java
│ │ └── user
│ │ ├── config
│ │ └── UserConfiguration.java
│ │ ├── dao
│ │ └── UserDao.java
│ │ ├── model
│ │ ├── dto
│ │ │ ├── MinimumPermissionDTO.java
│ │ │ ├── MinimumRoleDTO.java
│ │ │ ├── MinimumUserDTO.java
│ │ │ └── RolePermissionPO.java
│ │ └── po
│ │ │ ├── PermissionPO.java
│ │ │ ├── RolePO.java
│ │ │ └── UserPO.java
│ │ └── service
│ │ └── UserService.java
│ └── resources
│ ├── application.yml
│ ├── init_sql
│ └── tables
│ └── mybatis
│ └── mapper
│ └── UserMapper.xml
└── ssm-backstage
├── README.MD
├── pom.xml
└── src
└── main
├── java
└── com
│ └── skypyb
│ ├── config
│ └── SecurityInterceptor.java
│ ├── controller
│ ├── AuthorityController.java
│ ├── FeatureController.java
│ ├── UserController.java
│ └── ViewController.java
│ ├── dao
│ ├── AuthorityDao.java
│ ├── FeatureDao.java
│ └── UserDao.java
│ ├── entity
│ ├── Authority.java
│ ├── AuthorityToFeature.java
│ ├── Feature.java
│ └── User.java
│ ├── model
│ └── LaydataResponse.java
│ └── service
│ ├── AuthorityService.java
│ ├── FeatureService.java
│ └── UserService.java
├── resources
├── applicationContext.xml
├── log4j.properties
├── mybatis.xml
├── mysql.properties
├── springmvc.xml
└── sql
│ └── schema.sql
└── webapp
├── WEB-INF
├── templates
│ ├── authorityManager.html
│ ├── index.html
│ ├── layout.html
│ ├── login.html
│ └── userManager.html
└── web.xml
├── css
├── authorityManager.css
└── login.css
├── js
├── authorityManager.js
├── layout.js
└── userManager.js
└── layui
├── css
├── layui.css
├── layui.mobile.css
└── modules
│ ├── code.css
│ ├── laydate
│ └── default
│ │ └── laydate.css
│ └── layer
│ └── default
│ ├── icon-ext.png
│ ├── icon.png
│ ├── layer.css
│ ├── loading-0.gif
│ ├── loading-1.gif
│ └── loading-2.gif
├── font
├── iconfont.eot
├── iconfont.svg
├── iconfont.ttf
└── iconfont.woff
├── images
└── face
│ ├── 0.gif
│ ├── 1.gif
│ ├── 10.gif
│ ├── 11.gif
│ ├── 12.gif
│ ├── 13.gif
│ ├── 14.gif
│ ├── 15.gif
│ ├── 16.gif
│ ├── 17.gif
│ ├── 18.gif
│ ├── 19.gif
│ ├── 2.gif
│ ├── 20.gif
│ ├── 21.gif
│ ├── 22.gif
│ ├── 23.gif
│ ├── 24.gif
│ ├── 25.gif
│ ├── 26.gif
│ ├── 27.gif
│ ├── 28.gif
│ ├── 29.gif
│ ├── 3.gif
│ ├── 30.gif
│ ├── 31.gif
│ ├── 32.gif
│ ├── 33.gif
│ ├── 34.gif
│ ├── 35.gif
│ ├── 36.gif
│ ├── 37.gif
│ ├── 38.gif
│ ├── 39.gif
│ ├── 4.gif
│ ├── 40.gif
│ ├── 41.gif
│ ├── 42.gif
│ ├── 43.gif
│ ├── 44.gif
│ ├── 45.gif
│ ├── 46.gif
│ ├── 47.gif
│ ├── 48.gif
│ ├── 49.gif
│ ├── 5.gif
│ ├── 50.gif
│ ├── 51.gif
│ ├── 52.gif
│ ├── 53.gif
│ ├── 54.gif
│ ├── 55.gif
│ ├── 56.gif
│ ├── 57.gif
│ ├── 58.gif
│ ├── 59.gif
│ ├── 6.gif
│ ├── 60.gif
│ ├── 61.gif
│ ├── 62.gif
│ ├── 63.gif
│ ├── 64.gif
│ ├── 65.gif
│ ├── 66.gif
│ ├── 67.gif
│ ├── 68.gif
│ ├── 69.gif
│ ├── 7.gif
│ ├── 70.gif
│ ├── 71.gif
│ ├── 8.gif
│ └── 9.gif
├── lay
└── modules
│ ├── carousel.js
│ ├── code.js
│ ├── colorpicker.js
│ ├── element.js
│ ├── flow.js
│ ├── form.js
│ ├── jquery.js
│ ├── laydate.js
│ ├── layedit.js
│ ├── layer.js
│ ├── laypage.js
│ ├── laytpl.js
│ ├── mobile.js
│ ├── rate.js
│ ├── slider.js
│ ├── table.js
│ ├── tree.js
│ ├── upload.js
│ └── util.js
├── layui.all.js
└── layui.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 | *.iml
22 | *.lst
23 |
24 | #java files
25 |
26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
27 | hs_err_pid*
28 |
29 | #dirs
30 | .idea/
31 | .mvn/
32 | out/
33 | build/
34 | gradle/
35 | .gradle/
36 | target/out/
37 | target/
38 |
39 | #files
40 | HELP.md
41 | mvnw
42 | mvnw.cmd
43 | gradlew
44 | gradlew.bat
--------------------------------------------------------------------------------
/Cache-SpringBoot/README.MD:
--------------------------------------------------------------------------------
1 | SpringBoot的缓存操作
2 | ---
3 |
4 | * IDEA中选择[Project Structure]的Project子菜单, 进行如下操作导入:
5 | `绿色加号 -> Import Module -> 选择build.gradle -> OK -> ... `
6 |
7 |
8 |
9 | 关于缓存,这里只涉及到SpringBoot自带的缓存实现,即默认的 SimpleCacheConfiguration 创建的 ConcurrentMapCacheManager ,不涉及Redis缓存。
10 | @CacheConfig
11 | @CacheEvict
12 | @CachePut
13 | @Cacheable
14 | 以上注解都有用到,test 文件夹下有测试类举例说明,除注解配置之外,测试类中也有个简易的代码操作缓存演示。
15 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.4.RELEASE'
4 | }
5 | repositories {
6 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
7 | mavenCentral()
8 | }
9 | dependencies {
10 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
11 | }
12 | }
13 |
14 | apply plugin: 'java'
15 | apply plugin: 'idea'
16 | apply plugin: 'org.springframework.boot'
17 |
18 | jar {
19 | baseName = 'Cache-SpringBoot'
20 | version = '0.0.1-SNAPSHOT'
21 | }
22 |
23 | sourceCompatibility = 1.8
24 | targetCompatibility = 1.8
25 |
26 | allprojects {
27 | repositories {
28 | mavenLocal()
29 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
30 | mavenCentral()
31 | }
32 | }
33 |
34 | dependencies {
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.0.4.RELEASE'
37 | testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE')
38 | }
39 |
40 | tasks.withType(JavaCompile) {
41 | options.encoding = "UTF-8"
42 | }
43 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Cache-SpringBoot'
2 |
3 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/src/main/java/com/skypyb/CacheDemoApplication.java:
--------------------------------------------------------------------------------
1 | package com.skypyb;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.cache.annotation.EnableCaching;
6 |
7 | @EnableCaching//开启基于注解的缓存
8 | @SpringBootApplication
9 | public class CacheDemoApplication {
10 | public static void main(String[] args) {
11 | SpringApplication.run(CacheDemoApplication.class, args);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/src/main/java/com/skypyb/entity/User.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | public class User implements Serializable {
6 |
7 | private Integer id;
8 | private String name;
9 | private String gender;
10 |
11 | public User() {
12 | }
13 |
14 | public User(Integer id, String name, String gender) {
15 | this.id = id;
16 | this.name = name;
17 | this.gender = gender;
18 | }
19 |
20 | public Integer getId() {
21 | return id;
22 | }
23 |
24 | public void setId(Integer id) {
25 | this.id = id;
26 | }
27 |
28 | public String getName() {
29 | return name;
30 | }
31 |
32 | public void setName(String name) {
33 | this.name = name;
34 | }
35 |
36 | public String getGender() {
37 | return gender;
38 | }
39 |
40 | public void setGender(String gender) {
41 | this.gender = gender;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | final StringBuffer sb = new StringBuffer("User{");
47 | sb.append("id=").append(id);
48 | sb.append(", name='").append(name).append('\'');
49 | sb.append(", gender='").append(gender).append('\'');
50 | sb.append('}');
51 | return sb.toString();
52 | }
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/src/main/java/com/skypyb/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.service;
2 |
3 | import com.skypyb.entity.User;
4 | import org.springframework.cache.annotation.CacheConfig;
5 | import org.springframework.cache.annotation.CacheEvict;
6 | import org.springframework.cache.annotation.CachePut;
7 | import org.springframework.cache.annotation.Cacheable;
8 | import org.springframework.stereotype.Service;
9 |
10 |
11 | /**
12 | * CRUD 都是直接返回的假数据,不连数据库查了
13 | */
14 | @Service
15 | @CacheConfig(cacheNames = "user")
16 | public class UserService {
17 | private User user = new User(1, "tom", "man");
18 |
19 | /**
20 | * @Cacheable 表示需要缓存
21 | * key 属性是指定如何生成key(可用SpEL表达式)。也可以手动实现 keyGenerator
22 | * 在查询时,若是在Cache中(我这里是指定的名为"user的"Cache)有对应的key的话则不会执行方法
23 | * -
24 | * cacheManager 属性可以指定使用的CacheManager,CacheManager可以自己实现
25 | * 若是什么都没有导入则默认使用 SimpleCacheConfiguration 创建的 ConcurrentMapCacheManager
26 | * 要是导入了拥有自己实现的CacheManager的第三方依赖,比如 spring-boot-starter-data-redis,就会覆盖掉默认的实现
27 | * -
28 | * condition 属性,满足条件就缓存(可用SpEL表达式写条件),默认始终缓存
29 | * unless 属性,满足条件就不缓存,默认始终缓存
30 | */
31 | @Cacheable(key = "#root.targetClass.name+#id")
32 | public User getUserById(Integer id) {
33 |
34 | System.out.println("执行了 getUserById 该方法..");
35 | return user;
36 | }
37 |
38 |
39 | @Cacheable(key = "#root.targetClass.name + #name")
40 | public User getUserByName(String name) {
41 |
42 | System.out.println("执行了 getUserByName 该方法..");
43 | return user;
44 | }
45 |
46 | /**
47 | * @CachePut 表示随你怎么搞,反正方法是要执行的。如果对应的Key有缓存,就给你更新了
48 | */
49 | @CachePut(key = "#root.targetClass.name+#result.id")
50 | public User updateUser(User user) {
51 | System.out.println("执行了 updateUser 该方法..");
52 | this.user = user;
53 |
54 | return user;
55 | }
56 |
57 | /**
58 | * @CacheEvict 表示会清除key对应的缓存, 方法也是无论如何都会执行的
59 | */
60 | @CacheEvict(key = "#root.targetClass.name+#id")
61 | public void deleteUserById(Integer id) {
62 | System.out.println("执行了 deleteUserById 该方法..");
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/Cache-SpringBoot/src/test/java/CacheTest.java:
--------------------------------------------------------------------------------
1 | import com.skypyb.CacheDemoApplication;
2 | import com.skypyb.entity.User;
3 | import com.skypyb.service.UserService;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import javax.annotation.Resource;
12 |
13 | @SpringBootTest(classes = CacheDemoApplication.class)
14 | @RunWith(SpringRunner.class)
15 | public class CacheTest {
16 |
17 | @Autowired
18 | private UserService userService;
19 |
20 | @Resource
21 | private ConcurrentMapCacheManager cacheManager;
22 |
23 |
24 | @Test
25 | public void test1() {
26 |
27 | //第一次查
28 | User user = userService.getUserById(1);
29 | userService.getUserByName("tom");
30 | System.out.println("------");
31 |
32 | //第二次查
33 | userService.getUserById(1);
34 | userService.getUserByName("tom");
35 | System.out.println("------");
36 |
37 | userService.updateUser(user);
38 | System.out.println("------");
39 |
40 | userService.deleteUserById(1);
41 | System.out.println("------");
42 |
43 | //第三次查
44 | userService.getUserById(1);
45 | userService.getUserByName("tom");
46 | System.out.println("------");
47 |
48 | test2();
49 | }
50 |
51 | /**
52 | * 代码方式操作缓存
53 | */
54 | public void test2() {
55 | Object user = cacheManager.getCache("user").get("com.skypyb.service.UserService1").get();
56 | System.out.println(user);
57 | }
58 |
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Event-Springboot/README.md:
--------------------------------------------------------------------------------
1 | SpringBoot实现异步事件驱动(发布、监听)编程
2 | ---
3 |
4 | * IDEA中选择[Project Structure]的Project子菜单, 进行如下操作导入:
5 | `绿色加号 -> Import Module -> 选择build.gradle -> OK -> ... `
6 | * test 文件夹下有测试类,直接启动即可
7 | * 有序监听没写,没什么用,严格要求有序处理业务为啥不一个个调用方法。
8 | `有序监听实现 SmartApplicationListener 就行了。`
9 |
--------------------------------------------------------------------------------
/Event-Springboot/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.4.RELEASE'
4 | }
5 | repositories {
6 | mavenLocal()
7 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
8 | mavenCentral()
9 | }
10 | dependencies {
11 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
12 | }
13 | }
14 |
15 | apply plugin: 'java'
16 | apply plugin: 'idea'
17 | apply plugin: 'org.springframework.boot'
18 |
19 | jar {
20 | baseName = 'Event'
21 | version = '0.0.1-SNAPSHOT'
22 | }
23 |
24 | sourceCompatibility = 1.8
25 | targetCompatibility = 1.8
26 |
27 | allprojects {
28 | repositories {
29 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
30 | mavenCentral()
31 | }
32 | }
33 |
34 | dependencies {
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter
37 | compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.0.4.RELEASE'
38 | testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE')
39 | }
40 |
41 | tasks.withType(JavaCompile) {
42 | options.encoding = "UTF-8"
43 | }
44 |
--------------------------------------------------------------------------------
/Event-Springboot/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Event-Springboot'
2 |
3 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/EventApplication.java:
--------------------------------------------------------------------------------
1 | package com.skypyb;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class EventApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(EventApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/config/MyAsyncConfigurer.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.config;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
6 | import org.springframework.context.annotation.Configuration;
7 | import org.springframework.scheduling.annotation.AsyncConfigurer;
8 | import org.springframework.scheduling.annotation.EnableAsync;
9 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
10 |
11 | import java.lang.reflect.Method;
12 | import java.util.concurrent.Executor;
13 |
14 | @Configuration
15 | @EnableAsync
16 | public class MyAsyncConfigurer implements AsyncConfigurer {
17 | private static Logger logger = LoggerFactory.getLogger(MyAsyncConfigurer.class);
18 |
19 | /**
20 | * 自定义异步线程池,若不重写会使用默认的线程池。
21 | * @return
22 | */
23 | @Override
24 | public Executor getAsyncExecutor() {
25 | //使用Spring内置线程池任务对象
26 | ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
27 | taskExecutor.setCorePoolSize(10);
28 | taskExecutor.setMaxPoolSize(20);
29 | taskExecutor.setQueueCapacity(25);
30 | taskExecutor.initialize();
31 | return taskExecutor;
32 | }
33 |
34 | @Override
35 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
36 | return new MyAsyncExceptionHandler();
37 | }
38 |
39 |
40 | class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
41 |
42 | @Override
43 | public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
44 | logger.info("Exception message - " + throwable.getMessage());
45 | logger.info("Method name - " + method.getName());
46 | for (Object param : objects) {
47 | logger.info("Parameter value - " + param);
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/entity/User.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | public class User implements Serializable {
6 |
7 | private Long id;
8 |
9 | private String userName;
10 |
11 | private String password;
12 |
13 | public User() {
14 | }
15 |
16 | public User(Long id, String userName, String password) {
17 | this.id = id;
18 | this.userName = userName;
19 | this.password = password;
20 | }
21 |
22 | public Long getId() {
23 | return id;
24 | }
25 |
26 | public void setId(Long id) {
27 | this.id = id;
28 | }
29 |
30 | public String getUserName() {
31 | return userName;
32 | }
33 |
34 | public void setUserName(String userName) {
35 | this.userName = userName;
36 | }
37 |
38 | public String getPassword() {
39 | return password;
40 | }
41 |
42 | public void setPassword(String password) {
43 | this.password = password;
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | final StringBuffer sb = new StringBuffer("User{");
49 | sb.append("id=").append(id);
50 | sb.append(", userName='").append(userName).append('\'');
51 | sb.append('}');
52 | return sb.toString();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/event/UserRegisterEvent.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.event;
2 |
3 | import com.skypyb.entity.User;
4 | import org.springframework.context.ApplicationEvent;
5 |
6 | /**
7 | * 用户注册事件
8 | */
9 | public class UserRegisterEvent extends ApplicationEvent {
10 |
11 | private User user;
12 |
13 | /**
14 | * 重写构造函数
15 | * @param source
16 | * @param user
17 | */
18 | public UserRegisterEvent(Object source, User user) {
19 | super(source);
20 | this.user = user;
21 | }
22 |
23 |
24 | public User getUser() {
25 | return user;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/listener/InitializationListener.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.listener;
2 |
3 | import com.skypyb.entity.User;
4 | import com.skypyb.event.UserRegisterEvent;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.context.ApplicationListener;
8 | import org.springframework.scheduling.annotation.Async;
9 | import org.springframework.stereotype.Component;
10 |
11 | /**
12 | * 用户注册完了,要初始化一些数据嘛
13 | * 这是监听用户注册的初始化方法
14 | */
15 | @Component
16 | public class InitializationListener implements ApplicationListener {
17 |
18 | private static Logger logger = LoggerFactory.getLogger(InitializationListener.class);
19 |
20 | @Override
21 | @Async
22 | public void onApplicationEvent(UserRegisterEvent event) {
23 | User user = event.getUser();
24 | //init(user)
25 | logger.info("User initialization completed.");
26 | }
27 |
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/service/MailService.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.service;
2 |
3 | import com.skypyb.event.UserRegisterEvent;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 | import org.springframework.context.event.EventListener;
7 | import org.springframework.scheduling.annotation.Async;
8 | import org.springframework.stereotype.Service;
9 |
10 | /**
11 | * 假设这是个发邮件的服务
12 | */
13 | @Service
14 | public class MailService {
15 | private static Logger logger = LoggerFactory.getLogger(MailService.class);
16 |
17 | /*
18 | public void send(Mail mail) {
19 | ...
20 | }*/
21 |
22 |
23 | /**
24 | * 监听用户注册,发送注册成功邮件。
25 | *
26 | * @param event
27 | */
28 | @EventListener
29 | @Async
30 | public void userRegister(UserRegisterEvent event) {
31 | //send(xxx);
32 |
33 | logger.info("Send a registration success email to the user! user name : {}",
34 | event.getUser().getUserName());
35 | }
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/Event-Springboot/src/main/java/com/skypyb/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.service;
2 |
3 |
4 | import com.skypyb.entity.User;
5 | import com.skypyb.event.UserRegisterEvent;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.context.ApplicationContext;
10 | import org.springframework.stereotype.Service;
11 |
12 | @Service
13 | public class UserService {
14 | private static Logger logger = LoggerFactory.getLogger(UserService.class);
15 |
16 | @Autowired
17 | private ApplicationContext context;
18 |
19 |
20 | public void register(User user) {
21 | //repository.save(user)
22 | logger.info("User register success! user :{}",user);
23 |
24 | context.publishEvent(new UserRegisterEvent(this, user));
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/Event-Springboot/src/test/java/com/skypyb/EventTest.java:
--------------------------------------------------------------------------------
1 | package com.skypyb;
2 |
3 | import com.skypyb.entity.User;
4 | import com.skypyb.service.UserService;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import java.util.UUID;
12 |
13 | @SpringBootTest
14 | @RunWith(SpringRunner.class)
15 | public class EventTest {
16 |
17 | @Autowired
18 | private UserService userService;
19 |
20 | @Test
21 | public void test1() {
22 | User u = new User() {{
23 | setId(1L);
24 | setUserName("skypyb");
25 | setPassword(UUID.randomUUID().toString());
26 | }};
27 |
28 | userService.register(u);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 skypyb
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 使用各类主流框架、以及中间件整合之类的代码演示,注释详细
2 | ---
3 | [](https://mit-license.org/)
4 |
5 |
6 |
7 |
8 | ### Demo 演示列表
9 | - [sc-demo-alibaba](https://github.com/skypyb/code_demo/tree/master/sc-demo-alibaba):Spring Cloud Alibaba全家桶的示例,服务治理、熔断、通信、网关、限流、鉴权等
10 | - [spring-security-demo](https://github.com/skypyb/code_demo/tree/master/spring-security-demo):(内附sql脚本) 标准的RBAC权限设计,基于动态查询数据库的权限判定 ( *以接口为粒度,即 Request URL+Request Method* )基于JWT的认证授权流程,使用SpringBoot+SpringSecurity+MyBatis+jjwt
11 | - [dubbo-springboot](https://github.com/skypyb/code_demo/tree/master/dubbo-springboot):SpringBoot整合Dubbo的演示,服务治理使用Zookeeper
12 | - [sc-demo-microservice](https://github.com/skypyb/code_demo/tree/master/sc-demo-microservice):SpringCloudNetfilx全家桶,包含Zuul,Eureka,Ribbon,Hystrix,Feign等组件的使用
13 | - [ssm-backstage](https://github.com/skypyb/code_demo/tree/master/ssm-backstage):Spring+SpringMVC+Mybatis注解式开发的简易后台项目,Mybatis实现一对一/一对多映射,前台使用Thymeleaf+Layui
14 | - [WebSocket](https://github.com/skypyb/code_demo/tree/master/WebSocket):SpringBoot开发的WebSocket应用,包含传统tomcat开发方式和使用`spring-boot-starter-websocket`的开发方式
15 | - [Cache-SpringBoot](https://github.com/skypyb/code_demo/tree/master/Cache-SpringBoot):SpringBoot自带的缓存实现,@CacheConfig @CacheEvict @CachePut @Cacheable 等注解使用
16 | - [RabbitMQ-SpringBoot](https://github.com/skypyb/code_demo/tree/master/RabbitMQ-SpringBoot):SpringBoot 集成 RabbitMQ; 消息发送/接收、死信队列
17 | - [Event-Springboot](https://github.com/skypyb/code_demo/tree/master/Event-Springboot):SpringBoot实现异步事件驱动(发布、监听)编程,AsyncConfigurer异步配置演示,ApplicationEvent、ApplicationListener、@EventListener等相关接口/注解使用示例
18 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/README.md:
--------------------------------------------------------------------------------
1 | SpringBoot 集成 RabbitMQ; 消息发送/接收、死信队列
2 | ---
3 |
4 | * IDEA中选择[Project Structure]的Project子菜单, 进行如下操作导入:
5 | `绿色加号 -> Import Module -> 选择build.gradle -> OK -> ... `
6 |
7 | * 两个项目的 test 文件夹下均有演示测试类
8 | * 测试前先启动Consumer服务器,两个服务的yml配置文件都要改为可以连上的RabbitMQ
9 |
10 |
11 |
12 |
13 | ### 完成的功能
14 | * 生产者消费者基础功能,消息收发
15 | * 注解形式/配置类形式 创建Queue、ExChange、Binding
16 | * 配置监听器工厂,指定消息限流次数、并发线程数
17 | * 死信队列相关配置,使用死信队列实现延时消息的收/发
18 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.4.RELEASE'
4 | }
5 | repositories {
6 | mavenLocal()
7 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
8 | mavenCentral()
9 | }
10 | dependencies {
11 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
12 | }
13 | }
14 |
15 | apply plugin: 'java'
16 | apply plugin: 'idea'
17 | apply plugin: 'org.springframework.boot'
18 |
19 | jar {
20 | baseName = 'RabbitMQ-Consumer'
21 | version = '0.0.1-SNAPSHOT'
22 | }
23 |
24 | sourceCompatibility = 1.8
25 | targetCompatibility = 1.8
26 |
27 | allprojects {
28 | repositories {
29 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
30 | mavenCentral()
31 | }
32 | }
33 |
34 | dependencies {
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | // compile('org.springframework.boot:spring-boot-starter-data-redis:2.0.4.RELEASE')
37 | compile('org.springframework.boot:spring-boot-starter-amqp:2.0.4.RELEASE')
38 | // compile("com.google.code.gson:gson:2.8.0")
39 | compile('org.springframework.boot:spring-boot-starter-web:2.0.4.RELEASE')
40 | // compile('org.springframework.boot:spring-boot-starter-thymeleaf')
41 | // compile group: 'org.freemarker', name: 'freemarker', version: '2.3.23'
42 | // compile('org.springframework.boot:spring-boot-starter-data-jpa')
43 | // compile group: 'org.mybatis', name: 'mybatis', version: '3.4.6'
44 | compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
45 | // compile "org.springframework.boot:spring-boot-devtools:2.0.4.RELEASE"
46 | testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE')
47 | }
48 |
49 | tasks.withType(JavaCompile) {
50 | options.encoding = "UTF-8"
51 | }
52 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/out/production/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8081
3 | servlet:
4 | context-path: /
5 | spring:
6 | http:
7 | encoding:
8 | charset: UTF-8
9 | jackson:
10 | #前端页面传Date值时格式化
11 | date-format: yyyy-MM-dd HH:mm:ss
12 | time-zone: GMT+8
13 | #rabbitmq基本配置
14 | rabbitmq:
15 | addresses: 192.168.194.132:5672
16 | username: admin
17 | password: 614
18 | virtual-host: /
19 | connection-timeout: 15s
20 | #rabbitmq消费端配置
21 | listener:
22 | simple:
23 | #并发数
24 | concurrency: 5
25 | #最大并发数
26 | max-concurrency: 10
27 | #签收模式:手工签收、自动签收
28 | acknowledge-mode: manual
29 | #限流,在此消费端同一时间只有一条消息消费
30 | prefetch: 1
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'RabbitMQ-Consumer'
2 |
3 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/Application.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Application.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/config/RabbitMQCoreConfig.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.config;
2 |
3 | import org.springframework.amqp.core.AcknowledgeMode;
4 | import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
5 | import org.springframework.amqp.rabbit.connection.ConnectionFactory;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 |
10 | @Configuration
11 | public class RabbitMQCoreConfig {
12 |
13 | @Autowired
14 | private ConnectionFactory connectionFactory;
15 |
16 |
17 | @Bean(name = "prefetchCount5Container")
18 | public SimpleRabbitListenerContainerFactory prefetchCount5Container() {
19 | SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
20 | //并发数设置: 初始化线程3,最大并发5
21 | factory.setConcurrentConsumers(3);
22 | factory.setMaxConcurrentConsumers(3);
23 |
24 | ////限流,同一单位时间内只有5条消息消费
25 | factory.setConnectionFactory(connectionFactory);
26 | factory.setPrefetchCount(5);
27 | factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
28 |
29 | return factory;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/controller/DeadReceiver.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.controller;
2 |
3 | import com.rabbitmq.client.Channel;
4 | import com.skypyb.rabbitmq.config.RabbitBindConfig;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.amqp.rabbit.annotation.RabbitHandler;
8 | import org.springframework.amqp.rabbit.annotation.RabbitListener;
9 | import org.springframework.amqp.support.AmqpHeaders;
10 | import org.springframework.messaging.handler.annotation.Headers;
11 | import org.springframework.messaging.handler.annotation.Payload;
12 | import org.springframework.stereotype.Component;
13 |
14 | import java.io.IOException;
15 | import java.util.Map;
16 |
17 | //
18 | //containerFactory 监听器工厂设置,指定一个被Spring管理的监听器工厂
19 | @RabbitListener(queues = {RabbitBindConfig.SKYPYB_DEAD_QUEUE}, containerFactory = "prefetchCount5Container")
20 | @Component
21 | public class DeadReceiver {
22 |
23 | private Logger logger = LoggerFactory.getLogger(DeadReceiver.class);
24 |
25 | @RabbitHandler
26 | public void onDeadMessage(@Payload String message,
27 | @Headers Map headers,
28 | Channel channel) throws IOException {
29 |
30 | logger.info("死信队列接收消息: {}", message);
31 |
32 | //delivery tag可以从headers中get出来
33 | Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
34 |
35 | try {
36 | channel.basicAck(deliveryTag, false);
37 | } catch (Exception e) {
38 | System.err.println(e.getMessage());
39 | boolean redelivered = (boolean) headers.get(AmqpHeaders.REDELIVERED);
40 | channel.basicNack(deliveryTag, false, !redelivered);
41 | }
42 |
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/controller/DelayReceiver.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.controller;
2 |
3 | import com.rabbitmq.client.Channel;
4 | import com.skypyb.rabbitmq.config.RabbitBindConfig;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.amqp.rabbit.annotation.RabbitHandler;
8 | import org.springframework.amqp.rabbit.annotation.RabbitListener;
9 | import org.springframework.amqp.support.AmqpHeaders;
10 | import org.springframework.messaging.handler.annotation.Headers;
11 | import org.springframework.messaging.handler.annotation.Payload;
12 | import org.springframework.stereotype.Component;
13 |
14 | import java.io.IOException;
15 | import java.util.Map;
16 |
17 | @RabbitListener(queues = {RabbitBindConfig.SKYPYB_DELAY_QUEUE})
18 | @Component
19 | public class DelayReceiver {
20 |
21 | private Logger logger = LoggerFactory.getLogger(DelayReceiver.class);
22 |
23 | @RabbitHandler
24 | public void onDelayMessage(@Payload String message,
25 | @Headers Map headers,
26 | Channel channel) throws IOException {
27 |
28 | logger.info("监听延时交换机, 收到消息: {}", message);
29 |
30 | //delivery tag可以从headers中get出来
31 | Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
32 |
33 | try {
34 | channel.basicAck(deliveryTag, false);
35 | } catch (Exception e) {
36 | boolean redelivered = (boolean) headers.get(AmqpHeaders.REDELIVERED);
37 | channel.basicNack(deliveryTag, false, !redelivered);
38 | }
39 |
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/controller/User1Receiver.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.controller;
2 |
3 | import com.rabbitmq.client.Channel;
4 | import com.skypyb.rabbitmq.entity.User1;
5 | import org.springframework.amqp.rabbit.annotation.*;
6 | import org.springframework.amqp.support.AmqpHeaders;
7 | import org.springframework.messaging.handler.annotation.Headers;
8 | import org.springframework.messaging.handler.annotation.Payload;
9 | import org.springframework.stereotype.Component;
10 |
11 | import java.io.IOException;
12 | import java.util.Map;
13 |
14 | @Component
15 | public class User1Receiver {
16 |
17 | /**
18 | * @param user1 消息体,使用 @Payload 注解
19 | * @param headers 消息头,使用 @Headers 注解
20 | * @param channel
21 | */
22 | /*@RabbitListener表示监听的具体队列.
23 | bindings属性代表绑定。里边有几个值填写,填写好绑定的队列名字和交换机名字
24 | 指定好routingKey。若指定的这些参数不存在的话。则会自行给你创建好
25 | durable代表是否持久化
26 | */
27 | @RabbitListener(bindings = @QueueBinding(
28 | value = @Queue(value = "user1-queue", durable = "true"),
29 | exchange = @Exchange(name = "user1-exchange", durable = "true", type = "topic"),
30 | key = "user1.#"
31 | )
32 | )
33 | @RabbitHandler//标识这个方法用于消费消息
34 | public void onUser1Message(@Payload User1 user1,
35 | @Headers Map headers,
36 | Channel channel) throws IOException {
37 | //消费者操作
38 | System.out.println("-------收到消息辣!-----");
39 | System.out.println("发过来的用户名为:" + user1.getName());
40 |
41 | //delivery tag可以从消息头里边get出来
42 | Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
43 |
44 | try{
45 |
46 | //basicAck()表示确认已经消费消息。通知一下mq,需要先得到 delivery tag
47 | channel.basicAck(deliveryTag, false);
48 | }catch (Exception e){
49 |
50 | boolean redelivered = (boolean) headers.get(AmqpHeaders.REDELIVERED);
51 | //requeue参数:如果被拒绝的消息应该被重新排队而不是丢弃/死信,则为true,这个参数代表是否重新分发
52 | channel.basicNack(deliveryTag,false,!redelivered);
53 | }
54 |
55 |
56 |
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/java/com/skypyb/rabbitmq/entity/User1.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | public class User1 implements Serializable{
6 |
7 | private Long id;
8 | private String name;
9 | private String messageId;//储存消息发送的唯一标识
10 |
11 |
12 | public User1() {
13 | }
14 |
15 | public User1(Long id, String name, String messageId) {
16 | this.id = id;
17 | this.name = name;
18 | this.messageId = messageId;
19 | }
20 |
21 | public Long getId() {
22 | return id;
23 | }
24 |
25 | public void setId(Long id) {
26 | this.id = id;
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public void setName(String name) {
34 | this.name = name;
35 | }
36 |
37 | public String getMessageId() {
38 | return messageId;
39 | }
40 |
41 | public void setMessageId(String messageId) {
42 | this.messageId = messageId;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Consumer/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8081
3 | servlet:
4 | context-path: /
5 | spring:
6 | http:
7 | encoding:
8 | charset: UTF-8
9 | jackson:
10 | #前端页面传Date值时格式化
11 | date-format: yyyy-MM-dd HH:mm:ss
12 | time-zone: GMT+8
13 | #rabbitmq基本配置
14 | rabbitmq:
15 | addresses: 192.168.194.132:5672
16 | username: admin
17 | password: 614
18 | virtual-host: /
19 | connection-timeout: 15s
20 | #rabbitmq消费端配置
21 | listener:
22 | simple:
23 | #并发数
24 | concurrency: 5
25 | #最大并发数
26 | max-concurrency: 10
27 | #签收模式:手工签收、自动签收
28 | acknowledge-mode: manual
29 | #限流,在此消费端同一时间只有一条消息消费
30 | prefetch: 1
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.4.RELEASE'
4 | }
5 | repositories {
6 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
7 | mavenCentral()
8 | }
9 | dependencies {
10 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
11 | }
12 | }
13 |
14 | apply plugin: 'java'
15 | apply plugin: 'idea'
16 | apply plugin: 'org.springframework.boot'
17 |
18 | jar {
19 | baseName = 'RabbitMQ-Producer'
20 | version = '0.0.1-SNAPSHOT'
21 | }
22 |
23 | sourceCompatibility = 1.8
24 | targetCompatibility = 1.8
25 |
26 | allprojects {
27 | repositories {
28 | mavenLocal()
29 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
30 | mavenCentral()
31 | }
32 | }
33 |
34 | dependencies {
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | // compile('org.springframework.boot:spring-boot-starter-data-redis:2.0.4.RELEASE')
37 | compile('org.springframework.boot:spring-boot-starter-amqp:2.0.4.RELEASE')
38 | // compile("com.google.code.gson:gson:2.8.0")
39 | compile('org.springframework.boot:spring-boot-starter-web:2.0.4.RELEASE')
40 | // compile('org.springframework.boot:spring-boot-starter-thymeleaf')
41 | // compile group: 'org.freemarker', name: 'freemarker', version: '2.3.23'
42 | // compile('org.springframework.boot:spring-boot-starter-data-jpa')
43 | // compile group: 'org.mybatis', name: 'mybatis', version: '3.4.6'
44 | compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
45 | // compile "org.springframework.boot:spring-boot-devtools:2.0.4.RELEASE"
46 | testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE')
47 | }
48 |
49 | tasks.withType(JavaCompile) {
50 | options.encoding = "UTF-8"
51 | }
52 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/out/production/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8080
3 | servlet:
4 | context-path: /
5 | spring:
6 | http:
7 | encoding:
8 | charset: UTF-8
9 | jackson:
10 | #前端页面传Date值时格式化
11 | date-format: yyyy-MM-dd HH:mm:ss
12 | time-zone: GMT+8
13 | rabbitmq:
14 | port: 5672
15 | host: 192.168.194.132
16 | username: admin
17 | password: 614
18 | virtual-host: /
19 | connection-timeout: 15s
20 | #启用消息确认机制。能收到MQ Broker的异步响应
21 | publisher-confirms: true
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'RabbitMQ-Producer'
2 |
3 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/src/main/java/com/skypyb/rabbitmq/Application.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Application.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/src/main/java/com/skypyb/rabbitmq/entity/User1.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | public class User1 implements Serializable{
6 |
7 | private Long id;
8 | private String name;
9 | private String messageId;//储存消息发送的唯一标识
10 |
11 |
12 | public User1() {
13 | }
14 |
15 | public User1(Long id, String name, String messageId) {
16 | this.id = id;
17 | this.name = name;
18 | this.messageId = messageId;
19 | }
20 |
21 | public Long getId() {
22 | return id;
23 | }
24 |
25 | public void setId(Long id) {
26 | this.id = id;
27 | }
28 |
29 | public String getName() {
30 | return name;
31 | }
32 |
33 | public void setName(String name) {
34 | this.name = name;
35 | }
36 |
37 | public String getMessageId() {
38 | return messageId;
39 | }
40 |
41 | public void setMessageId(String messageId) {
42 | this.messageId = messageId;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/src/main/java/com/skypyb/rabbitmq/producer/User1Sender.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.rabbitmq.producer;
2 |
3 | import com.skypyb.rabbitmq.entity.User1;
4 | import org.springframework.amqp.rabbit.core.RabbitTemplate;
5 | import org.springframework.amqp.rabbit.support.CorrelationData;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Component;
8 |
9 |
10 | @Component
11 | public class User1Sender {
12 |
13 | @Autowired
14 | private RabbitTemplate rabbitTemplate;//操作rabbitmq的模板
15 |
16 |
17 | /**
18 | * 回调函数,confirm 确认
19 | */
20 | final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
21 |
22 | /**
23 | *
24 | * @param correlationData 消息唯一ID
25 | * @param ack 确认消息是否被MQBroker接收,true是已被接收,false为没被接收/投递失败/异常/...
26 | * @param cause
27 | */
28 | @Override
29 | public void confirm(CorrelationData correlationData, boolean ack, String cause) {
30 | System.out.println("CorrelationData:" + correlationData);
31 |
32 | if (ack) {
33 | System.out.println("消息已被消费~~~");
34 | } else {
35 | System.err.println("消息未被消费!!!");
36 | }
37 | }
38 | };
39 |
40 | public void send(User1 user1) {
41 |
42 | //这里是设置回调
43 | rabbitTemplate.setConfirmCallback(confirmCallback);
44 |
45 | //下面是发消息
46 | CorrelationData correlationData = new CorrelationData();
47 | correlationData.setId(user1.getMessageId());
48 | rabbitTemplate.convertAndSend(
49 | "user1-exchange",//exchange
50 | "user1.key1",//routingKey
51 | user1,//消息体内容
52 | correlationData//消息唯一ID
53 | );
54 | }
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8080
3 | servlet:
4 | context-path: /
5 | spring:
6 | http:
7 | encoding:
8 | charset: UTF-8
9 | jackson:
10 | #前端页面传Date值时格式化
11 | date-format: yyyy-MM-dd HH:mm:ss
12 | time-zone: GMT+8
13 | rabbitmq:
14 | port: 5672
15 | host: 192.168.194.132
16 | username: admin
17 | password: 614
18 | virtual-host: /
19 | connection-timeout: 15s
20 | #启用消息确认机制。能收到MQ Broker的异步响应
21 | publisher-confirms: true
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/RabbitMQ-SpringBoot/RabbitMQ-Producer/src/test/java/com/skypyb/test/RabbitmqTest.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.test;
2 |
3 | import com.skypyb.rabbitmq.Application;
4 | import com.skypyb.rabbitmq.entity.User1;
5 | import com.skypyb.rabbitmq.producer.User1Sender;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.amqp.core.Message;
11 | import org.springframework.amqp.core.MessageBuilder;
12 | import org.springframework.amqp.core.MessagePostProcessor;
13 | import org.springframework.amqp.rabbit.core.RabbitTemplate;
14 | import org.springframework.beans.factory.annotation.Autowired;
15 | import org.springframework.boot.test.context.SpringBootTest;
16 | import org.springframework.test.context.junit4.SpringRunner;
17 |
18 | import java.util.UUID;
19 |
20 | @RunWith(SpringRunner.class)
21 | @SpringBootTest(classes = Application.class)
22 | public class RabbitmqTest {
23 |
24 | @Autowired
25 | private User1Sender userSender;
26 |
27 | @Autowired
28 | private RabbitTemplate rabbitTemplate;
29 |
30 | Logger logger = LoggerFactory.getLogger(RabbitmqTest.class);
31 |
32 | @Test
33 | public void testSend1() {
34 |
35 | for (long i = 0; i < 10; i++) {
36 | User1 user1 = new User1();
37 |
38 | user1.setId(i);
39 | user1.setName("测试用户" + i);
40 | user1.setMessageId("user1$" + System.currentTimeMillis() + "$" + UUID.randomUUID().toString());
41 |
42 | userSender.send(user1);
43 | }
44 | }
45 |
46 |
47 | @Test
48 | public void testDead() {
49 |
50 | //单位毫秒
51 | String ttl = "3000";
52 |
53 | MessagePostProcessor msgProcessor = (Message msg) -> {
54 | msg.getMessageProperties().setExpiration(ttl);
55 | return msg;
56 | };
57 |
58 |
59 | rabbitTemplate.convertAndSend("skypyb-ordinary-exchange",
60 | "skypyb.key.ordinary.one", "死信 -- 指定时间:" + ttl, msgProcessor);
61 |
62 | rabbitTemplate.convertAndSend("skypyb-ordinary-exchange",
63 | "skypyb.key.ordinary.one", "死信 -- 默认值");
64 |
65 |
66 | logger.info("-----消息发送完毕-----");
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/WebSocket/README.md:
--------------------------------------------------------------------------------
1 | SpringBoot开发WebSocket应用
2 | ---
3 |
4 | * IDEA中选择[Project Structure]的Project子菜单, 进行如下操作导入:
5 | `绿色加号 -> Import Module -> 选择build.gradle -> OK -> ... `
6 | * 启动服务器后直接本地打开resources下的HTML文件即可
7 |
8 |
9 | com.skypyb.websocket 包下为传统 @ServerEndpoint 注解方式的 WebSocket 开发演示
10 | com.skypyb.springboot_websocket 包下为集成 spring-boot-starter-websocket 的 WebSocket 开发演示
--------------------------------------------------------------------------------
/WebSocket/websocket/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.4.RELEASE'
4 | }
5 | repositories {
6 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
7 | mavenCentral()
8 | }
9 | dependencies {
10 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
11 | }
12 | }
13 |
14 | apply plugin: 'java'
15 | apply plugin: 'idea'
16 | apply plugin: 'org.springframework.boot'
17 |
18 | jar {
19 | baseName = 'websocket'
20 | version = '0.0.1-SNAPSHOT'
21 | }
22 |
23 | sourceCompatibility = 1.8
24 | targetCompatibility = 1.8
25 |
26 | allprojects {
27 | repositories {
28 | mavenLocal()
29 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
30 | mavenCentral()
31 | }
32 | }
33 |
34 | dependencies {
35 | compile fileTree(dir: 'libs', include: ['*.jar'])
36 | compile('org.springframework.boot:spring-boot-starter-websocket:2.0.4.RELEASE')
37 | testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE')
38 | }
39 |
40 | tasks.withType(JavaCompile) {
41 | options.encoding = "UTF-8"
42 | }
43 |
--------------------------------------------------------------------------------
/WebSocket/websocket/out/production/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8080
3 | spring:
4 | http:
5 | encoding:
6 | charset: UTF-8
7 | jackson:
8 | #前端页面传Date值时格式化
9 | date-format: yyyy-MM-dd HH:mm:ss
10 | time-zone: GMT+8
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/WebSocket/websocket/out/production/resources/view/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | webSocket
6 |
9 |
10 |
11 | WebSocket Demo.
12 | WebSocket Demo..
13 | WebSocket Demo...
14 |
15 |
16 |
60 |
--------------------------------------------------------------------------------
/WebSocket/websocket/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'websocket'
2 |
3 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/java/com/skypyb/WebSocketApplication.java:
--------------------------------------------------------------------------------
1 | package com.skypyb;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.scheduling.annotation.EnableScheduling;
6 |
7 | @SpringBootApplication
8 | @EnableScheduling
9 | public class WebSocketApplication {
10 | public static void main(String[] args) {
11 | SpringApplication.run(WebSocketApplication.class, args);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/java/com/skypyb/scheduled/SchedulerConfig.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.scheduled;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
6 |
7 | @Configuration
8 | public class SchedulerConfig {
9 |
10 | @Bean
11 | public ThreadPoolTaskScheduler taskScheduler() {
12 | ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
13 | return taskScheduler;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/java/com/skypyb/scheduled/WebSocketSendMessageScheduled.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.scheduled;
2 |
3 | import com.skypyb.springboot_websocket.MyWebSocketHandler;
4 | import com.skypyb.websocket.WebSocketServerOne;
5 | import org.springframework.scheduling.annotation.Scheduled;
6 | import org.springframework.stereotype.Component;
7 |
8 | import java.time.LocalDateTime;
9 | import java.util.concurrent.TimeUnit;
10 |
11 | @Component
12 | public class WebSocketSendMessageScheduled {
13 |
14 | @Scheduled(fixedRate = 3 * 1000)
15 | public void publish() {
16 | String msg = LocalDateTime.now().toString();
17 | WebSocketServerOne.fanoutMessage(msg);
18 | MyWebSocketHandler.fanoutMessage(msg);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/java/com/skypyb/websocket/WebSocketConfigOne.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.websocket;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.socket.server.standard.ServerEndpointExporter;
6 |
7 | @Configuration
8 | public class WebSocketConfigOne {
9 |
10 | /**
11 | * 这个bean会自动注册使用了@ServerEndpoint注解声明的对象
12 | * 没有的话会报404
13 | *
14 | * @return
15 | */
16 | @Bean
17 | public ServerEndpointExporter serverEndpointExporter() {
18 |
19 | return new ServerEndpointExporter();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/java/com/skypyb/websocket/WebSocketServerOne.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.websocket;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | import javax.websocket.*;
6 | import javax.websocket.server.ServerEndpoint;
7 | import java.io.IOException;
8 | import java.util.concurrent.CopyOnWriteArraySet;
9 |
10 | /**
11 | * @ServerEndpoint 该注解可以将类定义成一个WebSocket服务器端,
12 | * @OnOpen 表示有浏览器链接过来的时候被调用
13 | * @OnClose 表示浏览器发出关闭请求的时候被调用
14 | * @OnMessage 表示浏览器发消息的时候被调用
15 | * @OnError 表示报错了
16 | */
17 | @ServerEndpoint("/ws/serverOne")
18 | @Component
19 | public class WebSocketServerOne {
20 |
21 | //concurrent包下线程安全的Set
22 | private static final CopyOnWriteArraySet SESSIONS = new CopyOnWriteArraySet<>();
23 |
24 | private Session session;
25 |
26 | @OnOpen
27 | public void onOpen(Session session) {
28 | this.session = session;
29 | SESSIONS.add(this);
30 | System.out.println(String.format("成功建立连接~ 当前总连接数为:%s", SESSIONS.size()));
31 | }
32 |
33 | @OnClose
34 | public void onClose() {
35 | SESSIONS.remove(this);
36 | System.out.println(String.format("成功关闭连接~ 当前总连接数为:%s", SESSIONS.size()));
37 | }
38 |
39 | @OnMessage
40 | public void onMessage(String message, Session session) {
41 | System.out.println(message);
42 | }
43 |
44 | @OnError
45 | public void onError(Session session, Throwable error) {
46 | System.out.println("发生错误");
47 | error.printStackTrace();
48 | }
49 |
50 | /**
51 | * 指定发消息
52 | *
53 | * @param message
54 | */
55 | public void sendMessage(String message) {
56 | try {
57 | this.session.getBasicRemote().sendText(message);
58 | } catch (IOException e) {
59 | e.printStackTrace();
60 | }
61 | }
62 |
63 | /**
64 | * 群发消息
65 | *
66 | * @param message
67 | */
68 | public static void fanoutMessage(String message) {
69 | SESSIONS.forEach(ws -> ws.sendMessage(message));
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8080
3 | spring:
4 | http:
5 | encoding:
6 | charset: UTF-8
7 | jackson:
8 | #前端页面传Date值时格式化
9 | date-format: yyyy-MM-dd HH:mm:ss
10 | time-zone: GMT+8
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/WebSocket/websocket/src/main/resources/view/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | webSocket
6 |
9 |
10 |
11 | WebSocket Demo.
12 | WebSocket Demo..
13 | WebSocket Demo...
14 |
15 |
16 |
60 |
--------------------------------------------------------------------------------
/distributed-lock/build.gradle:
--------------------------------------------------------------------------------
1 | //def springBootVersion = rootProject.ext.springBootVersion
2 |
3 |
4 |
5 | buildscript {
6 | ext {
7 | bootGroupName = 'org.springframework.boot'
8 | bootVersion = '2.0.4.RELEASE'
9 | }
10 | repositories {
11 | mavenLocal()
12 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
13 | mavenCentral()
14 | }
15 | dependencies {
16 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${bootVersion}")
17 | }
18 | }
19 |
20 |
21 | apply plugin: 'java'
22 | apply plugin: 'idea'
23 | apply plugin: 'org.springframework.boot'
24 |
25 | jar {
26 | baseName = 'distributed-lock'
27 | version = '0.0.1-SNAPSHOT'
28 | }
29 |
30 | sourceCompatibility = 1.8
31 | targetCompatibility = 1.8
32 |
33 | allprojects {
34 | repositories {
35 | mavenLocal()
36 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
37 | mavenCentral()
38 | }
39 | }
40 |
41 | dependencies {
42 | compile fileTree(dir: 'libs', include: ['*.jar'])
43 | testCompile(
44 | group: bootGroupName,
45 | name: 'spring-boot-starter-test',
46 | version: bootVersion
47 | )
48 | compile(
49 | [group: bootGroupName, name: 'spring-boot-starter-data-redis', version: bootVersion],
50 | [group: bootGroupName, name: 'spring-boot-starter-web', version: bootVersion],
51 | [group: 'com.101tec', name: 'zkclient', version: '0.11'],
52 | [group: 'redis.clients', name: 'jedis',version: '2.9.0'],
53 | )
54 | }
55 |
56 |
57 | tasks.withType(JavaCompile) {
58 | options.encoding = "UTF-8"
59 | }
60 |
--------------------------------------------------------------------------------
/distributed-lock/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'distributed-lock'
2 |
3 |
--------------------------------------------------------------------------------
/distributed-lock/src/main/java/com/skypyb/DemoApplication.java:
--------------------------------------------------------------------------------
1 | package com.skypyb;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class DemoApplication {
8 | public static void main(String[] args) {
9 | SpringApplication.run(DemoApplication.class, args);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/distributed-lock/src/main/java/com/skypyb/config/RedisConfig.java:
--------------------------------------------------------------------------------
1 | package com.skypyb.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.data.redis.connection.RedisConnectionFactory;
6 | import org.springframework.data.redis.core.RedisTemplate;
7 | import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
8 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
9 | import org.springframework.data.redis.serializer.StringRedisSerializer;
10 |
11 | @Configuration
12 | public class RedisConfig {
13 | @Bean
14 | public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
15 | RedisTemplate redisTemplate = new RedisTemplate<>();
16 | StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
17 | redisTemplate.setKeySerializer(stringRedisSerializer);
18 | redisTemplate.setHashKeySerializer(stringRedisSerializer);
19 | redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer