├── .gitignore
├── Dubbo-Demo
├── Service-Client
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── cn
│ │ └── mrdear
│ │ └── client
│ │ ├── dto
│ │ └── UserDTO.java
│ │ └── service
│ │ └── IUserService.java
├── Service-Consumer
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── java
│ │ │ └── cn
│ │ │ │ └── mrdear
│ │ │ │ └── consumer
│ │ │ │ ├── controller
│ │ │ │ └── UserController.java
│ │ │ │ └── manager
│ │ │ │ ├── UserManager.java
│ │ │ │ └── impl
│ │ │ │ └── UserManagerImpl.java
│ │ ├── resources
│ │ │ ├── applicationContext.xml
│ │ │ └── dispatcher-servlet.xml
│ │ └── webapp
│ │ │ ├── WEB-INF
│ │ │ ├── view
│ │ │ │ └── error.jsp
│ │ │ └── web.xml
│ │ │ └── index.jsp
│ │ └── test
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── test
│ │ │ └── UserManagerTest.java
│ │ └── resources
│ │ └── applicationContext.xml
├── Service-Provider
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── java
│ │ │ └── cn
│ │ │ │ └── mrdear
│ │ │ │ └── provider
│ │ │ │ ├── Application.java
│ │ │ │ ├── convert
│ │ │ │ └── UserConvert.java
│ │ │ │ ├── dao
│ │ │ │ └── UserRepository.java
│ │ │ │ ├── domain
│ │ │ │ └── User.java
│ │ │ │ └── service
│ │ │ │ └── UserServiceImpl.java
│ │ └── resources
│ │ │ ├── applicationContext.xml
│ │ │ ├── db.properties
│ │ │ ├── h2
│ │ │ ├── data.sql
│ │ │ └── schema.sql
│ │ │ └── logback.xml
│ │ └── test
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── test
│ │ │ └── UserServiceTest.java
│ │ └── resources
│ │ ├── applicationContext.xml
│ │ ├── db.properties
│ │ ├── h2
│ │ ├── data.sql
│ │ └── schema.sql
│ │ └── logback.xml
├── doc
│ └── readme.md
└── pom.xml
├── Excel-Demo
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── cn
│ │ └── mrdear
│ │ └── excel
│ │ ├── constant
│ │ └── ExcelType.java
│ │ ├── core
│ │ ├── ExcelExtractor.java
│ │ └── ExcelFormat.java
│ │ └── util
│ │ ├── BeanUtils.java
│ │ └── FieldName.java
│ └── test
│ └── java
│ └── cn
│ └── mrdear
│ └── excel
│ ├── BeanUtilTest.java
│ ├── Demo.java
│ └── ExcelFormatTest.java
├── HtmlUnit-Demo
├── doc
│ └── SS账号密码.bat
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── cn
│ │ └── mrdear
│ │ ├── Setting.java
│ │ ├── core
│ │ ├── Main.java
│ │ ├── MianVpn.java
│ │ └── TutorialVpn.java
│ │ ├── model
│ │ ├── ConfigsBean.java
│ │ └── SSModel.java
│ │ └── util
│ │ ├── ModelUtil.java
│ │ ├── SystemUtil.java
│ │ ├── WEBUtil.java
│ │ └── WebClientUtil.java
│ └── resources
│ └── setting.json
├── JPA-Demo
├── doc
│ ├── SpringDataJPA学习记录(一)--环境配置.md
│ ├── SpringDataJPA学习记录(三)--复杂查询的封装.md
│ ├── SpringDataJPA学习记录(二)--增删改查.md
│ ├── SpringDataJPA学习记录(四)--使用QueryDSL.md
│ └── sql.sql
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ ├── entity
│ │ │ ├── TCity.java
│ │ │ └── THotel.java
│ │ │ ├── jpa
│ │ │ ├── Filter.java
│ │ │ ├── Order.java
│ │ │ └── QueryParams.java
│ │ │ └── repository
│ │ │ ├── BaseRepository.java
│ │ │ ├── TCityRepository.java
│ │ │ ├── THotelRepository.java
│ │ │ └── custom
│ │ │ ├── TCityRepositoryCustom.java
│ │ │ ├── TCityRepositoryImpl.java
│ │ │ ├── THotelRepositoryCustom.java
│ │ │ └── THotelRepositoryImpl.java
│ ├── resources
│ │ ├── config.properties
│ │ └── spring
│ │ │ └── applicationContext.xml
│ └── webapp
│ │ ├── WEB-INF
│ │ └── web.xml
│ │ └── index.jsp
│ └── test
│ └── java
│ └── TCityTest.java
├── Jersey-Demo
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── haikong
│ │ ├── ResultVO.java
│ │ ├── application
│ │ └── RESTApplication.java
│ │ ├── dao
│ │ └── DeviceMapper.java
│ │ ├── exception
│ │ ├── DeviceExceptionMapper.java
│ │ └── ErrorEntity.java
│ │ ├── filter
│ │ ├── PreRequestFilter.java
│ │ └── ResponseFilter.java
│ │ ├── interceptor
│ │ └── GzipInterceptor.java
│ │ ├── model
│ │ ├── Device.java
│ │ ├── ReqDevice.java
│ │ └── ServicesBean.java
│ │ ├── resources
│ │ └── DeviceController.java
│ │ ├── service
│ │ └── DeviceService.java
│ │ └── util
│ │ ├── CheckUtil.java
│ │ ├── Constants.java
│ │ ├── DecriptUtil.java
│ │ └── DeviceUtil.java
│ ├── resources
│ ├── applicationContext.xml
│ ├── db.properties
│ ├── db.sql
│ ├── log4j.properties
│ └── mybatis
│ │ ├── Mapper
│ │ └── DeviceMapper.xml
│ │ └── SqlMapConfig.xml
│ └── webapp
│ ├── WEB-INF
│ └── web.xml
│ └── index.jsp
├── Maven-Demo
├── doc
│ └── README.MD
├── haikong-common
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── haikong
│ │ │ └── common
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ └── mapper
│ │ │ └── UserMapper.java
│ │ └── resources
│ │ └── mybatis
│ │ └── mapper
│ │ └── userMapper.xml
├── haikong-core
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── haikong
│ │ │ └── core
│ │ │ └── controller
│ │ │ └── indexController.java
│ │ ├── resources
│ │ ├── config.properties
│ │ ├── db.properties
│ │ ├── log4j.properties
│ │ ├── mybatis
│ │ │ ├── SqlMapConfig.xml
│ │ │ └── mapper
│ │ │ │ └── 2.txt
│ │ └── spring
│ │ │ ├── applicationContext.xml
│ │ │ └── dispatcher-servlet.xml
│ │ └── webapp
│ │ ├── WEB-INF
│ │ └── web.xml
│ │ └── index.jsp
├── haikong-switch
│ └── pom.xml
└── pom.xml
├── Motan-Demo
├── Service-Client
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── cn
│ │ └── mrdear
│ │ └── client
│ │ ├── dto
│ │ └── UserDTO.java
│ │ └── service
│ │ └── IUserService.java
├── Service-Consumer
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── consumer
│ │ │ └── ApplicationStart.java
│ │ └── resources
│ │ ├── applicationContext.xml
│ │ └── logback.xml
├── Service-Provider
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── provider
│ │ │ ├── ApplicationStart.java
│ │ │ ├── convert
│ │ │ └── UserConvert.java
│ │ │ ├── dao
│ │ │ └── UserRepository.java
│ │ │ ├── domain
│ │ │ └── User.java
│ │ │ └── service
│ │ │ └── UserServiceImpl.java
│ │ └── resources
│ │ ├── applicationContext.xml
│ │ ├── h2
│ │ ├── data.sql
│ │ └── schema.sql
│ │ └── logback.xml
└── pom.xml
├── Pay-Demo
├── lib
│ ├── alipay-sdk-java20161029120104-source.jar
│ └── alipay-sdk-java20161029120104.jar
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── pay
│ │ │ ├── alipay
│ │ │ ├── AliPayConfig.java
│ │ │ └── AlipayTrade.java
│ │ │ ├── unionpay
│ │ │ ├── UnionPayClient.java
│ │ │ ├── UnionPayConfig.java
│ │ │ ├── UnionPayTrade.java
│ │ │ └── sdk
│ │ │ │ ├── AcpService.java
│ │ │ │ ├── BaseHttpSSLSocketFactory.java
│ │ │ │ ├── CertUtil.java
│ │ │ │ ├── HttpClient.java
│ │ │ │ ├── LogUtil.java
│ │ │ │ ├── SDKConfig.java
│ │ │ │ ├── SDKConstants.java
│ │ │ │ ├── SDKUtil.java
│ │ │ │ └── SecureUtil.java
│ │ │ ├── util
│ │ │ ├── Assert.java
│ │ │ ├── DateUtil.java
│ │ │ ├── RSAUtils.java
│ │ │ ├── SignUtil.java
│ │ │ ├── WebUtils.java
│ │ │ └── XmlUtil.java
│ │ │ └── wechat
│ │ │ ├── WechatClient.java
│ │ │ ├── WechatConfig.java
│ │ │ ├── WechatTrade.java
│ │ │ └── entity
│ │ │ ├── WechatPayNotify.java
│ │ │ ├── WechatRefund.java
│ │ │ ├── WechatRefundQuery.java
│ │ │ └── WechatUnifiedOrder.java
│ └── resources
│ │ └── acp_sdk.properties
│ └── test
│ ├── java
│ └── cn
│ │ └── mrdear
│ │ └── pay
│ │ ├── alipay
│ │ └── AlipayTradeTest.java
│ │ ├── unionpay
│ │ └── UnionPayTradeTest.java
│ │ ├── util
│ │ ├── SignUtilTest.java
│ │ └── XMLUtilTest.java
│ │ └── wechat
│ │ └── WechatTradeTest.java
│ └── resources
│ └── acp_sdk.properties
├── README.MD
├── SSM-Demo
├── doc
│ └── readme.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── cn
│ │ └── mrdear
│ │ ├── controller
│ │ ├── BookController.java
│ │ └── ErrorController.java
│ │ ├── entity
│ │ └── Book.java
│ │ ├── exception
│ │ └── GlobalException.java
│ │ ├── mapper
│ │ └── BookMapper.java
│ │ └── service
│ │ ├── BookService.java
│ │ └── impl
│ │ └── BookServiceImpl.java
│ ├── resources
│ ├── ModelGenerator.xml
│ ├── db.properties
│ ├── db.sql
│ ├── ehcache.xml
│ ├── logback.xml
│ ├── mybatis
│ │ ├── mapper
│ │ │ └── BookMapper.xml
│ │ └── sqlmapconfig.xml
│ └── spring
│ │ ├── applicationContext.xml
│ │ └── dispatcher-servlet.xml
│ └── webapp
│ ├── WEB-INF
│ ├── view
│ │ └── error.jsp
│ └── web.xml
│ └── index.jsp
├── Spring-Boot-Demo
├── logs
│ └── loging.log
│ │ └── spring.log
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── cn
│ │ └── mrdear
│ │ ├── Application.java
│ │ ├── conf
│ │ ├── DataSourcesConfig.java
│ │ ├── FilterConfig.java
│ │ ├── MybatisConfig.java
│ │ ├── ServletConfig.java
│ │ └── WEBMessageConvert.java
│ │ ├── controller
│ │ └── HelloController.java
│ │ ├── entity
│ │ └── User.java
│ │ ├── exception
│ │ └── PageException.java
│ │ └── mapper
│ │ └── UserMapper.java
│ └── resources
│ ├── application.properties
│ ├── banner.txt
│ ├── ehcache.xml
│ ├── mapper
│ └── UserMapper.xml
│ ├── static
│ └── css
│ │ └── bootstrap.min.css
│ └── templates
│ └── hello.html
├── Spring-Cloud-Demo
├── Service-Discovery-Eureka
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── EurekaApplication.java
│ │ └── resources
│ │ └── application.yml
├── Service-Product-Consumer-Feign-Hystrix
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ ├── UserConsumeFeignHystrixApplication.java
│ │ └── cn
│ │ │ └── medear
│ │ │ └── springcloud
│ │ │ ├── controller
│ │ │ └── ConsumeUserController.java
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ └── restclient
│ │ │ ├── UserClient.java
│ │ │ └── failback
│ │ │ └── UserClientFailBack.java
│ │ └── resources
│ │ └── application.yml
├── Service-Product-Consumer-Feign
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ ├── UserConsumeFeignApplication.java
│ │ └── cn
│ │ │ └── medear
│ │ │ └── springcloud
│ │ │ ├── controller
│ │ │ └── ConsumeUserController.java
│ │ │ ├── entity
│ │ │ └── User.java
│ │ │ └── restclient
│ │ │ └── UserClient.java
│ │ └── resources
│ │ └── application.yml
├── Service-Product-Consumer-Ribbon
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ └── springcloud
│ │ │ ├── UserConsumeApplication.java
│ │ │ ├── config
│ │ │ └── BeanConfig.java
│ │ │ └── controller
│ │ │ └── ConsumeUserController.java
│ │ └── resources
│ │ └── application.yml
├── Service-User-Provider
│ ├── pom.xml
│ ├── src
│ │ └── main
│ │ │ ├── java
│ │ │ └── cn
│ │ │ │ └── mrdear
│ │ │ │ ├── UserApplication.java
│ │ │ │ ├── controller
│ │ │ │ └── UserController.java
│ │ │ │ ├── entity
│ │ │ │ └── User.java
│ │ │ │ └── resporitory
│ │ │ │ └── UserResporitory.java
│ │ │ └── resources
│ │ │ ├── application.yml
│ │ │ └── database
│ │ │ ├── data.sql
│ │ │ └── schema.sql
│ └── target
│ │ └── classes
│ │ └── cn
│ │ └── mrdear
│ │ └── Application.class
└── pom.xml
├── Spring-Data-Redis
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── cn
│ │ │ └── mrdear
│ │ │ ├── Application.java
│ │ │ ├── conf
│ │ │ └── SwaggerConfig.java
│ │ │ ├── controller
│ │ │ └── UserController.java
│ │ │ ├── dao
│ │ │ └── UserDao.java
│ │ │ ├── model
│ │ │ └── User.java
│ │ │ ├── publish
│ │ │ ├── Listen.java
│ │ │ └── PublishConfig.java
│ │ │ └── util
│ │ │ └── MockUserUtil.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── cn
│ └── mrdear
│ └── test
│ └── RedisConnectTest.java
├── Spring-Security-Demo
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── cn
│ │ └── mrdear
│ │ └── security
│ │ ├── Application.java
│ │ ├── config
│ │ ├── CommonBeanConfig.java
│ │ ├── CorsFilter.java
│ │ ├── SecurityConfig.java
│ │ └── VerifyTokenFilter.java
│ │ ├── controller
│ │ └── LoginCntroller.java
│ │ ├── dto
│ │ ├── TokenUserAuthentication.java
│ │ └── TokenUserDTO.java
│ │ └── util
│ │ └── JwtTokenUtil.java
│ └── resources
│ └── application.properties
├── Util-Demo
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── cn
│ │ └── mrdear
│ │ └── util
│ │ ├── SecurityUtil
│ │ ├── AESUtil.java
│ │ ├── DigestUtil.java
│ │ └── RSAUtils.java
│ │ ├── dateutil
│ │ └── DateUtil.java
│ │ ├── httpUtil
│ │ └── WebUtils.java
│ │ ├── jniUtil
│ │ └── NativeLibraryLoader.java
│ │ ├── moneyUtil
│ │ └── MoneyUtil.java
│ │ ├── propsUtil
│ │ └── PropertiesUtils.java
│ │ ├── redis
│ │ ├── calback
│ │ │ └── WorkCallback.java
│ │ └── service
│ │ │ ├── JedisClient.java
│ │ │ └── JedisClientSingle.java
│ │ ├── vo
│ │ └── ResultWrapper.java
│ │ └── xml
│ │ └── XmlUtil.java
│ └── test
│ ├── java
│ ├── AESUtilTest.java
│ ├── DataUtilTest.java
│ ├── DigestUtilTest.java
│ ├── RedisTest.java
│ ├── XmlTest.java
│ └── httpUtilTest.java
│ └── resources
│ └── message.xml
└── gRPC-Demo
├── pom.xml
└── src
└── main
├── java
└── cn
│ └── mrdear
│ └── grpc
│ ├── clientProcess
│ ├── ClientInterruptImpl.java
│ ├── HelloWorldClientProcess.java
│ ├── HelloWorldServerProcess.java
│ ├── ServerInterruptImpl.java
│ └── forwardExample
│ │ ├── Client.java
│ │ ├── ClientImp.java
│ │ ├── ForwardingClient.java
│ │ ├── ForwardingClientImpl.java
│ │ └── InterceptTest.java
│ ├── common
│ └── WorkCallBack.java
│ ├── hello
│ ├── HelloWorldClient.java
│ └── HelloWorldServer.java
│ ├── hellopool
│ ├── HelloWorldClientPool.java
│ ├── HelloWorldClientSingle.java
│ ├── HelloWorldClientTest.java
│ └── HelloWorldFactory.java
│ └── route
│ ├── RouteGuideClient.java
│ ├── RouteGuideServer.java
│ ├── RouteGuideService.java
│ └── RouteGuideUtil.java
├── proto
├── hello.proto
└── route.proto
└── resources
└── route_guide_db.json
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
5 |
6 | # User-specific stuff:
7 | .idea
8 | .idea/**/tasks.xml
9 | .idea/dictionaries
10 |
11 | # Sensitive or high-churn files:
12 | .idea/**/dataSources/
13 | .idea/**/dataSources.ids
14 | .idea/**/dataSources.xml
15 | .idea/**/dataSources.local.xml
16 | .idea/**/sqlDataSources.xml
17 | .idea/**/dynamic.xml
18 | # Gradle:
19 | .idea/**/gradle.xml
20 | # CMake
21 | cmake-build-debug/
22 |
23 | # Mongo Explorer plugin:
24 | .idea/**/mongoSettings.xml
25 |
26 | ## File-based project format:
27 | *.iws
28 |
29 | ## Plugin-specific files:
30 |
31 | # IntelliJ
32 | out/
33 |
34 | # mpeltonen/sbt-idea plugin
35 | .idea_modules/
36 |
37 | # JIRA plugin
38 | atlassian-ide-plugin.xml
39 |
40 | # Cursive Clojure plugin
41 | .idea/replstate.xml
42 |
43 | # Crashlytics plugin (for Android Studio and IntelliJ)
44 | com_crashlytics_export_strings.xml
45 | crashlytics.properties
46 | crashlytics-build.properties
47 | fabric.properties
48 | ### Java template
49 | # Compiled class file
50 | # Log file
51 | *.log
52 |
53 | # BlueJ files
54 | *.ctxt
55 |
56 | # Mobile Tools for Java (J2ME)
57 | .mtj.tmp/
58 |
59 | # Package Files #
60 | *.jar
61 | *.ear
62 | *.zip
63 | *.tar.gz
64 | *.rar
65 |
66 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
67 | hs_err_pid*
68 |
69 | # custom
70 | *.iml
71 |
72 | **/target
73 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Client/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | cn.mrdear.dubbo
7 | Dubbo-Demo
8 | 1.0.0
9 |
10 | 4.0.0
11 | Service-Client
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Client/src/main/java/cn/mrdear/client/dto/UserDTO.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.client.dto;
2 |
3 | import lombok.Data;
4 |
5 | import java.io.Serializable;
6 |
7 | /**
8 | * 用户DTO,用于Service层传输
9 | * @author Niu Li
10 | * @since 2017/6/12
11 | */
12 | @Data
13 | public class UserDTO implements Serializable{
14 |
15 | private static final long serialVersionUID = 4086492518942464226L;
16 |
17 | private Long id;
18 |
19 | private String username;
20 |
21 | private String password;
22 |
23 | private Integer age;
24 |
25 | private String nickname;
26 |
27 | private String mail;
28 |
29 | private String memo;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Client/src/main/java/cn/mrdear/client/service/IUserService.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.client.service;
2 |
3 | import cn.mrdear.client.dto.UserDTO;
4 |
5 | import java.util.Collection;
6 | import java.util.List;
7 |
8 | /**
9 | * 用户服务,一般都会在返回层再包裹一层,这里简而化之
10 | * @author Niu Li
11 | * @since 2017/6/12
12 | */
13 | public interface IUserService {
14 |
15 | /**
16 | * 根据id查找
17 | */
18 | UserDTO findById(Long id);
19 |
20 | /**
21 | * 根据id批量查询
22 | */
23 | List queryByIds(Collection ids);
24 |
25 | /**
26 | * 更新用户
27 | * @return 返回更新后的实体
28 | */
29 | UserDTO updateById(UserDTO userDTO);
30 |
31 | /**
32 | * 根据id删除用户
33 | */
34 | Boolean deleteById(Long id);
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/java/cn/mrdear/consumer/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.consumer.controller;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RestController;
6 |
7 | import cn.mrdear.client.dto.UserDTO;
8 | import cn.mrdear.consumer.manager.UserManager;
9 |
10 | import javax.annotation.Resource;
11 |
12 | /**
13 | * @author Niu Li
14 | * @since 2017/6/14
15 | */
16 | @RestController
17 | public class UserController {
18 |
19 | @Resource
20 | private UserManager userManager;
21 |
22 | @GetMapping("/user/{id}")
23 | public UserDTO getUserById(@PathVariable Long id) {
24 | UserDTO userDTO = userManager.findById(id);
25 | return userDTO;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/java/cn/mrdear/consumer/manager/UserManager.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.consumer.manager;
2 |
3 | import cn.mrdear.client.dto.UserDTO;
4 |
5 | /**
6 | * manager
7 | * @author Niu Li
8 | * @since 2017/6/13
9 | */
10 |
11 | public interface UserManager {
12 |
13 | UserDTO findById(Long id);
14 |
15 | UserDTO findByIdBack(Long id);
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/java/cn/mrdear/consumer/manager/impl/UserManagerImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.consumer.manager.impl;
2 |
3 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
4 |
5 | import org.springframework.stereotype.Service;
6 |
7 | import cn.mrdear.client.dto.UserDTO;
8 | import cn.mrdear.client.service.IUserService;
9 | import cn.mrdear.consumer.manager.UserManager;
10 |
11 | import javax.annotation.Resource;
12 |
13 | import java.util.Objects;
14 |
15 | /**
16 | * manager调用远程RPC组装数据,此处调试只是再加一层封装
17 | * @author Niu Li
18 | * @since 2017/6/13
19 | */
20 | @Service
21 | public class UserManagerImpl implements UserManager {
22 |
23 | @Resource
24 | private IUserService userService;
25 |
26 | @Override
27 | @HystrixCommand(groupKey = "user", fallbackMethod = "findByIdBack")
28 | public UserDTO findById(Long id) {
29 | if (Objects.equals(id, 1L)) {
30 | try {
31 | Thread.sleep(1000000);
32 | } catch (InterruptedException e) {
33 | // do nothing
34 | }
35 | }
36 | if (Objects.equals(id, 2L)) {
37 | throw new RuntimeException("熔断测试");
38 | }
39 | return userService.findById(id);
40 | }
41 |
42 | public UserDTO findByIdBack(Long id) {
43 | System.err.println("findByIdBack");
44 | UserDTO userDTO = new UserDTO();
45 | userDTO.setAge(1);
46 | userDTO.setUsername("备用用户");
47 | return userDTO;
48 | }
49 |
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/resources/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
35 |
36 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/resources/dispatcher-servlet.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/webapp/WEB-INF/view/error.jsp:
--------------------------------------------------------------------------------
1 | <%--
2 | Created by IntelliJ IDEA.
3 | User: niuli
4 | Date: 2017/4/19
5 | Time: 09:45
6 | To change this template use File | Settings | File Templates.
7 | --%>
8 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 |
10 |
11 | Title
12 |
13 |
14 | Error 页面
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 | <%--
2 | Created by IntelliJ IDEA.
3 | User: NL
4 | Date: 2017/1/23
5 | Time: 9:09
6 | To change this template use File | Settings | File Templates.
7 | --%>
8 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 |
10 |
11 |
12 |
13 |
14 | Hello World!
15 | 请访问/user/{id}测试
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/test/java/cn/mrdear/test/UserManagerTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.test;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.test.context.ContextConfiguration;
7 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
8 |
9 | import cn.mrdear.client.dto.UserDTO;
10 | import cn.mrdear.consumer.manager.UserManager;
11 |
12 | import javax.annotation.Resource;
13 |
14 | /**
15 | * @author Niu Li
16 | * @since 2017/6/13
17 | */
18 | @RunWith(SpringJUnit4ClassRunner.class)
19 | @ContextConfiguration(locations = "classpath:applicationContext.xml")
20 | public class UserManagerTest {
21 |
22 | @Resource
23 | private UserManager userManager;
24 |
25 |
26 | @Test
27 | public void testFindById() {
28 | UserDTO userDTO = userManager.findById(1L);
29 | Assert.assertNotNull(userDTO);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Consumer/src/test/resources/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
26 |
27 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/java/cn/mrdear/provider/Application.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider;
2 |
3 | import org.springframework.context.support.ClassPathXmlApplicationContext;
4 |
5 | import java.io.IOException;
6 |
7 | /**
8 | * @author Niu Li
9 | * @since 2017/6/12
10 | */
11 | public class Application {
12 | public static void main(String[] args) throws IOException {
13 | ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
14 | context.start();
15 | System.in.read(); // 为保证服务一直开着,利用输入流的阻塞来模拟
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/java/cn/mrdear/provider/convert/UserConvert.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.convert;
2 |
3 | import org.springframework.beans.BeanUtils;
4 | import org.springframework.util.CollectionUtils;
5 |
6 | import cn.mrdear.client.dto.UserDTO;
7 | import cn.mrdear.provider.domain.User;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import java.util.stream.Collectors;
12 |
13 | /**
14 | * @author Niu Li
15 | * @since 2017/6/12
16 | */
17 | public class UserConvert {
18 |
19 | public static UserDTO toDTO(User user) {
20 | UserDTO userDTO = new UserDTO();
21 | BeanUtils.copyProperties(user,userDTO);
22 | return userDTO;
23 | }
24 |
25 |
26 | public static List toDTOS(List users) {
27 | if (CollectionUtils.isEmpty(users)) {
28 | return new ArrayList<>(1);
29 | }
30 | List results = new ArrayList<>();
31 | return users.stream().map(UserConvert::toDTO)
32 | .collect(Collectors.toList());
33 | }
34 |
35 |
36 | public static User toDO(UserDTO userDTO) {
37 | User user = new User();
38 | BeanUtils.copyProperties(userDTO,user);
39 | return user;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/java/cn/mrdear/provider/dao/UserRepository.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.dao;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.data.jpa.repository.Query;
5 |
6 | import cn.mrdear.provider.domain.User;
7 |
8 | import java.util.Collection;
9 | import java.util.List;
10 |
11 | /**
12 | * JPA repo层
13 | * @author Niu Li
14 | * @since 2017/6/12
15 | */
16 | public interface UserRepository extends JpaRepository{
17 |
18 | User findById(Long id);
19 |
20 | @Query("select p from User p where id in (?1)")
21 | List queryByIds(Collection ids);
22 |
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/java/cn/mrdear/provider/domain/User.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.domain;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import java.io.Serializable;
11 |
12 | /**
13 | * 用户实体类,对应数据库
14 | * @author Niu Li
15 | * @since 2017/6/12
16 | */
17 | @Data
18 | @Entity
19 | @Table(name = "user")
20 | public class User implements Serializable{
21 |
22 | private static final long serialVersionUID = 1793488098966504793L;
23 | @Id
24 | @GeneratedValue
25 | private Long id;
26 |
27 | private String username;
28 |
29 | private String password;
30 |
31 | private Integer age;
32 |
33 | private String nickname;
34 |
35 | private String mail;
36 |
37 | private String memo;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/java/cn/mrdear/provider/service/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.service;
2 |
3 | import com.alibaba.dubbo.config.annotation.Service;
4 |
5 | import cn.mrdear.client.dto.UserDTO;
6 | import cn.mrdear.client.service.IUserService;
7 | import cn.mrdear.provider.convert.UserConvert;
8 | import cn.mrdear.provider.dao.UserRepository;
9 | import cn.mrdear.provider.domain.User;
10 |
11 | import javax.annotation.Resource;
12 |
13 | import java.util.Collection;
14 | import java.util.List;
15 |
16 | /**
17 | * 用户服务的具体实现,作为服务提供方提供出去
18 | * @author Niu Li
19 | * @since 2017/6/12
20 | */
21 | @Service(version = "1.0.0")
22 | public class UserServiceImpl implements IUserService {
23 |
24 | @Resource
25 | private UserRepository userRepository;
26 |
27 | @Override
28 | public UserDTO findById(Long id) {
29 | User user = userRepository.findById(id);
30 | return UserConvert.toDTO(user);
31 | }
32 |
33 | @Override
34 | public List queryByIds(Collection ids) {
35 | List users = userRepository.queryByIds(ids);
36 | return UserConvert.toDTOS(users);
37 | }
38 |
39 | @Override
40 | public UserDTO updateById(UserDTO userDTO) {
41 | User user = UserConvert.toDO(userDTO);
42 | userRepository.save(user);
43 | return this.findById(userDTO.getId());
44 | }
45 |
46 | @Override
47 | public Boolean deleteById(Long id) {
48 | userRepository.delete(id);
49 | return true;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/resources/db.properties:
--------------------------------------------------------------------------------
1 | jdbc.driver=com.mysql.jdbc.Driver
2 | jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf8&characterSetResults\
3 | =utf8
4 | jdbc.username=root
5 | jdbc.password=7946521
6 |
7 | filters:stat
8 |
9 | maxActive:20
10 | initialSize:1
11 | maxWait:60000
12 | minIdle:10
13 |
14 | timeBetweenEvictionRunsMillis:60000
15 | minEvictableIdleTimeMillis:300000
16 |
17 | testWhileIdle:true
18 | testOnBorrow:false
19 | testOnReturn:false
20 |
21 | maxOpenPreparedStatements:20
22 | removeAbandoned:true
23 | removeAbandonedTimeout:1800
24 | logAbandoned:true
25 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/resources/h2/data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('zhangsan',
2 | '123456', 18, '张三', '1111@qq.com', 'hahahah');
3 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('lis',
4 | '123456', 19, '李四', '123131@qq.com', 'xixiixxi');
5 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('wanger',
6 | '123456', 29, '王二', '12131984@qq.com', 'dqdh');
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/resources/h2/schema.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE user if exist;
2 | create table user (
3 | id INT(11) AUTO_INCREMENT PRIMARY KEY ,
4 | username VARCHAR(255),
5 | password VARCHAR(255),
6 | age INT(3),
7 | nickname VARCHAR(255),
8 | mail VARCHAR(255),
9 | memo VARCHAR(255),
10 | );
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | %d{HH:mm:ss} [%t] %logger{5} [%line] %p - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/test/java/cn/mrdear/test/UserServiceTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.test;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.test.context.ContextConfiguration;
7 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
8 |
9 | import cn.mrdear.client.dto.UserDTO;
10 | import cn.mrdear.provider.service.UserServiceImpl;
11 |
12 | import javax.annotation.Resource;
13 |
14 | /**
15 | * @author Niu Li
16 | * @since 2017/6/13
17 | */
18 | @RunWith(SpringJUnit4ClassRunner.class)
19 | @ContextConfiguration(locations = "classpath:applicationContext.xml")
20 | public class UserServiceTest {
21 |
22 | @Resource
23 | private UserServiceImpl userService;
24 |
25 | @Test
26 | public void testFindById() {
27 | UserDTO userDTO = userService.findById(1L);
28 | Assert.assertNotNull(userDTO);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/test/resources/db.properties:
--------------------------------------------------------------------------------
1 | jdbc.driver=com.mysql.jdbc.Driver
2 | jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf8&characterSetResults\
3 | =utf8
4 | jdbc.username=root
5 | jdbc.password=7946521
6 |
7 | filters:stat
8 |
9 | maxActive:20
10 | initialSize:1
11 | maxWait:60000
12 | minIdle:10
13 |
14 | timeBetweenEvictionRunsMillis:60000
15 | minEvictableIdleTimeMillis:300000
16 |
17 | testWhileIdle:true
18 | testOnBorrow:false
19 | testOnReturn:false
20 |
21 | maxOpenPreparedStatements:20
22 | removeAbandoned:true
23 | removeAbandonedTimeout:1800
24 | logAbandoned:true
25 |
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/test/resources/h2/data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('zhangsan',
2 | '123456', 18, '张三', '1111@qq.com', 'hahahah');
3 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('lis',
4 | '123456', 19, '李四', '123131@qq.com', 'xixiixxi');
5 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('wanger',
6 | '123456', 29, '王二', '12131984@qq.com', 'dqdh');
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/test/resources/h2/schema.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE user if exist;
2 | create table user (
3 | id INT(11) AUTO_INCREMENT PRIMARY KEY ,
4 | username VARCHAR(255),
5 | password VARCHAR(255),
6 | age INT(3),
7 | nickname VARCHAR(255),
8 | mail VARCHAR(255),
9 | memo VARCHAR(255),
10 | );
--------------------------------------------------------------------------------
/Dubbo-Demo/Service-Provider/src/test/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | %d{HH:mm:ss} [%t] %logger{5} [%line] %p - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Dubbo-Demo/doc/readme.md:
--------------------------------------------------------------------------------
1 |
2 | 1. 启动需要先下载zk,然后启动
3 | 2. Provider中spring配置文件host改成本机ip地址,然后启动
4 | 3. 启动Consumer
5 | 4. 可下载Simple-monitor http://download.csdn.net/detail/liweifengwf/7864009
6 | 5. 可下载dubbo-admin http://download.csdn.net/detail/leiyong0326/9548973
7 | 6. dubbo的调用基本就是这样,大多数规则都可以在admin中配置也可以在spring注册服务和引用的时候配置
--------------------------------------------------------------------------------
/Excel-Demo/src/main/java/cn/mrdear/excel/constant/ExcelType.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel.constant;
2 |
3 | /**
4 | * 定义excel格式
5 | * @author Niu Li
6 | * @since 2017/3/17
7 | */
8 | public enum ExcelType {
9 | XLS, XLSX;
10 | }
11 |
--------------------------------------------------------------------------------
/Excel-Demo/src/main/java/cn/mrdear/excel/util/BeanUtils.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel.util;
2 |
3 | import java.lang.reflect.Field;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * 对bean一些转换方法
9 | *
10 | * @author Niu Li
11 | * @since 2017/2/23
12 | */
13 | public class BeanUtils {
14 |
15 | /**
16 | * 转换bean为map
17 | *
18 | * @param source 要转换的bean
19 | * @param bean类型
20 | * @return 转换结果
21 | */
22 | public static Map bean2Map(T source) throws IllegalAccessException {
23 | Map result = new HashMap<>();
24 |
25 | Class> sourceClass = source.getClass();
26 | //拿到所有的字段,不包括继承的字段
27 | Field[] sourceFiled = sourceClass.getDeclaredFields();
28 | for (Field field : sourceFiled) {
29 | field.setAccessible(true);//设置可访问,不然拿不到private
30 | //配置了注解的话则使用注解名称,作为header字段
31 | FieldName fieldName = field.getAnnotation(FieldName.class);
32 | if (fieldName == null) {
33 | result.put(field.getName(), field.get(source));
34 | } else {
35 | if (fieldName.Ignore()) continue;
36 | result.put(fieldName.value(), field.get(source));
37 | }
38 | }
39 | return result;
40 | }
41 |
42 | /**
43 | * map转bean
44 | * @param source map属性
45 | * @param instance 要转换成的备案
46 | * @return 该bean
47 | */
48 | public static T map2Bean(Map source, Class instance) {
49 | try {
50 | T object = instance.newInstance();
51 | Field[] fields = object.getClass().getDeclaredFields();
52 | for (Field field : fields) {
53 | field.setAccessible(true);
54 | FieldName fieldName = field.getAnnotation(FieldName.class);
55 | if (fieldName != null){
56 | field.set(object,source.get(fieldName.value()));
57 | }else {
58 | field.set(object,source.get(field.getName()));
59 | }
60 | }
61 | return object;
62 | } catch (InstantiationException | IllegalAccessException e) {
63 | e.printStackTrace();
64 | }
65 | return null;
66 | }
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/Excel-Demo/src/main/java/cn/mrdear/excel/util/FieldName.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel.util;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * 自定义字段名
10 | * @author Niu Li
11 | * @since 2017/2/23
12 | */
13 | @Retention(RetentionPolicy.RUNTIME)
14 | @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
15 | public @interface FieldName {
16 | /**
17 | * 字段名
18 | */
19 | String value() default "";
20 | /**
21 | * 是否忽略
22 | */
23 | boolean Ignore() default false;
24 | }
25 |
--------------------------------------------------------------------------------
/Excel-Demo/src/test/java/cn/mrdear/excel/BeanUtilTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Map;
6 |
7 | import cn.mrdear.excel.util.BeanUtils;
8 |
9 | /**
10 | * @author Niu Li
11 | * @since 2017/2/23
12 | */
13 | public class BeanUtilTest {
14 |
15 |
16 | @Test
17 | public void test() throws IllegalAccessException {
18 | Demo demo = new Demo();
19 | demo.setUserName("111");
20 | demo.setPassWord("222");
21 | Map map = BeanUtils.bean2Map(demo);
22 | System.out.println(map);
23 | Demo demo1 = BeanUtils.map2Bean(map,Demo.class);
24 | System.out.println(demo1);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/Excel-Demo/src/test/java/cn/mrdear/excel/Demo.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel;
2 |
3 | import cn.mrdear.excel.util.FieldName;
4 |
5 | /**
6 | * @author Niu Li
7 | * @since 2017/2/23
8 | */
9 | public class Demo {
10 |
11 | public Demo(String username, String password) {
12 | this.userName = username;
13 | this.passWord = password;
14 | }
15 | public Demo() {
16 | }
17 | //fildName字段需要和header对应
18 | @FieldName(value = "username")
19 | private String userName;
20 | private String passWord;
21 |
22 | public String getUserName() {
23 | return userName;
24 | }
25 |
26 | public void setUserName(String userName) {
27 | this.userName = userName;
28 | }
29 |
30 | public String getPassWord() {
31 | return passWord;
32 | }
33 |
34 | public void setPassWord(String passWord) {
35 | this.passWord = passWord;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return "Demo{" +
41 | "userName='" + userName + '\'' +
42 | ", passWord='" + passWord + '\'' +
43 | '}';
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Excel-Demo/src/test/java/cn/mrdear/excel/ExcelFormatTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.excel;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import java.io.File;
7 | import java.io.FileInputStream;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.util.ArrayList;
11 | import java.util.LinkedHashMap;
12 | import java.util.List;
13 |
14 | import cn.mrdear.excel.constant.ExcelType;
15 | import cn.mrdear.excel.core.ExcelExtractor;
16 | import cn.mrdear.excel.core.ExcelFormat;
17 |
18 | /**
19 | * @author Niu Li
20 | * @since 2017/2/23
21 | */
22 | public class ExcelFormatTest {
23 | LinkedHashMap headers;
24 | LinkedHashMap extractorHeaders;
25 |
26 | @Before
27 | public void init() {
28 | headers = new LinkedHashMap<>();
29 | extractorHeaders = new LinkedHashMap<>();
30 | headers.put("username","用户名");
31 | headers.put("passWord", "密码");
32 | extractorHeaders.put("用户名","username");
33 | extractorHeaders.put("密码", "passWord");
34 | }
35 |
36 | @Test
37 | public void testMake() {
38 | List content = new ArrayList<>();
39 | Demo demo1 = new Demo("1","1");
40 | Demo demo2 = new Demo("2","2");
41 | Demo demo3 = new Demo("3","3");
42 | Demo demo4 = new Demo("4","4");
43 | content.add(demo1);
44 | content.add(demo2);
45 | content.add(demo3);
46 | content.add(demo4);
47 |
48 | //写入
49 | ExcelFormat.from(headers,content)
50 | .excelType(ExcelType.XLS)
51 | .build("niuli")
52 | .write("/tmp/niuli.xls");
53 | System.out.println("写入成功");
54 | //读取
55 | try {
56 | InputStream in = new FileInputStream(new File("/tmp/niuli.xls"));
57 | List result = ExcelExtractor.extractFrom(ExcelType.XLS,in,Demo.class,
58 | extractorHeaders,0);
59 | System.out.println(result);
60 | } catch (IOException e) {
61 | e.printStackTrace();
62 | }
63 | System.out.println("读取成功");
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/HtmlUnit-Demo/doc/SS账号密码.bat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrdear/JavaWEB/a7b8da4e680ab0b06d057b3537e19f47d103bf54/HtmlUnit-Demo/doc/SS账号密码.bat
--------------------------------------------------------------------------------
/HtmlUnit-Demo/src/main/java/cn/mrdear/Setting.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear;
2 |
3 | import java.util.List;
4 |
5 | import cn.mrdear.model.ConfigsBean;
6 |
7 | /**
8 | * @author Niu Li
9 | * @date 2016/10/11
10 | */
11 | public class Setting
12 | {
13 |
14 | /**
15 | * sspath : D:\tools\翻墙\gui-config.json
16 | */
17 |
18 | private String sspath;
19 | /**
20 | * 本地节点配置
21 | */
22 | private List local;
23 |
24 |
25 | public String getSspath() {
26 | return sspath;
27 | }
28 |
29 | public void setSspath(String sspath) {
30 | this.sspath = sspath;
31 | }
32 |
33 | public List getLocal() {
34 | return local;
35 | }
36 |
37 | public void setLocal(List local) {
38 | this.local = local;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/HtmlUnit-Demo/src/main/java/cn/mrdear/util/ModelUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * @author Niu Li
7 | * @date 2016/10/8
8 | */
9 | public class ModelUtil {
10 |
11 | private static final String[] letters = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V" ,
12 | "W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
13 |
14 | //B7-24-D6-39-59-BC-B2-AE-E1-B2-B3-64-24-60-ED-C0
15 | public static String generateId(){
16 | StringBuilder builder = new StringBuilder();
17 | Random random = new Random();
18 | for (int i = 0; i < 16; i++) {
19 | if (i != 15){
20 | builder.append(letters[random.nextInt(letters.length)]).append(letters[random.nextInt(letters.length)]).append("-");
21 | }else {
22 | builder.append(letters[random.nextInt(letters.length)]).append(letters[random.nextInt(letters.length)]);
23 | }
24 | }
25 | return builder.toString();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/HtmlUnit-Demo/src/main/java/cn/mrdear/util/SystemUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util;
2 |
3 | import com.alibaba.fastjson.JSON;
4 |
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 |
8 | import cn.mrdear.Setting;
9 |
10 | /**
11 | * @author Niu Li
12 | * @date 2016/10/11
13 | */
14 | public class SystemUtil {
15 |
16 |
17 | public static Setting getSetting() throws IOException {
18 | InputStream in = SystemUtil.class.getClassLoader().getResourceAsStream("setting.json");
19 | Setting setting = JSON.parseObject(in,null,Setting.class);
20 | if (setting == null){
21 | throw new RuntimeException("未配置ss文件路径");
22 | }
23 | return setting;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/HtmlUnit-Demo/src/main/java/cn/mrdear/util/WebClientUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util;
2 |
3 | import com.gargoylesoftware.htmlunit.BrowserVersion;
4 | import com.gargoylesoftware.htmlunit.WebClient;
5 |
6 | /**
7 | * @author Niu Li
8 | * @date 2016/10/8
9 | */
10 | public enum WebClientUtil {
11 |
12 | INSTANCE;
13 |
14 | public WebClient webClient;
15 |
16 | WebClientUtil() {
17 | webClient = new WebClient(BrowserVersion.CHROME);
18 | webClient.getOptions().setUseInsecureSSL(true);//支持https
19 | webClient.getOptions().setJavaScriptEnabled(true); // 启用JS解释器,默认为true
20 | webClient.getOptions().setCssEnabled(false); // 禁用css支持
21 | webClient.getOptions().setThrowExceptionOnScriptError(false); // js运行错误时,是否抛出异常
22 | webClient.getOptions().setTimeout(10000); // 设置连接超时时间 ,这里是10S。如果为0,则无限期等待
23 | webClient.getOptions().setDoNotTrackEnabled(false);
24 | webClient.setJavaScriptTimeout(8000);//设置js运行超时时间
25 | webClient.waitForBackgroundJavaScript(500);//设置页面等待js响应时间,
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/HtmlUnit-Demo/src/main/resources/setting.json:
--------------------------------------------------------------------------------
1 | {
2 | "sspath":"E:\\jar\\gui-config.json",
3 | "local":[
4 | {
5 | "remarks" : "加利福尼亚,洛杉矶,美国",
6 | "server" : "23.105.203.111",
7 | "server_port" : 111,
8 | "password" : "1111",
9 | "method" : "aes-256-cfb",
10 | "obfs" : "plain",
11 | "obfsparam" : "",
12 | "remarks_base64" : "",
13 | "tcp_over_udp" : false,
14 | "udp_over_tcp" : false,
15 | "protocol" : "origin",
16 | "obfs_udp" : false,
17 | "enable" : true,
18 | "id" : "6B-7C-2E-E6-75-BD-0B-75-B6-12-30-06-39-61-69-37"
19 | }
20 | ]
21 | }
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/BaseRepository.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository;
2 |
3 | import org.springframework.data.repository.NoRepositoryBean;
4 |
5 | import javax.persistence.EntityManager;
6 | import javax.persistence.PersistenceContext;
7 |
8 | /**
9 | * @author Niu Li
10 | * @date 2017/1/8
11 | */
12 | @NoRepositoryBean
13 | public class BaseRepository {
14 |
15 | @PersistenceContext(unitName = "TestJPA")
16 | protected EntityManager em;
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/TCityRepository.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.data.querydsl.QueryDslPredicateExecutor;
5 |
6 | import cn.mrdear.entity.TCity;
7 |
8 | /**
9 | * @author Niu Li
10 | * @date 2017/1/7
11 | */
12 | public interface TCityRepository extends JpaRepository,QueryDslPredicateExecutor, cn.mrdear.repository.custom.TCityRepositoryCustom {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/THotelRepository.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository;
2 |
3 | /**
4 | * @author Niu Li
5 | * @date 2017/1/7
6 | */
7 | public interface THotelRepository {
8 | }
9 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/custom/TCityRepositoryCustom.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository.custom;
2 |
3 | import com.querydsl.core.QueryResults;
4 | import com.querydsl.core.Tuple;
5 | import com.querydsl.core.types.Predicate;
6 |
7 | import org.springframework.data.domain.Pageable;
8 |
9 | import java.util.List;
10 |
11 | /**
12 | * @author Niu Li
13 | * @date 2017/1/7
14 | */
15 | public interface TCityRepositoryCustom {
16 | /**
17 | * 关联查询示例,查询出城市和对应的旅店
18 | * @param predicate 查询条件
19 | * @return 查询实体
20 | */
21 | public List findCityAndHotel(Predicate predicate);
22 |
23 | /**
24 | * 关联查询示例,查询出城市和对应的旅店
25 | * @param predicate 查询条件
26 | * @return 查询实体
27 | */
28 | public QueryResults findCityAndHotelPage(Predicate predicate,Pageable pageable);
29 | }
30 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/custom/TCityRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository.custom;
2 |
3 | import com.querydsl.core.QueryResults;
4 | import com.querydsl.core.Tuple;
5 | import com.querydsl.core.types.Predicate;
6 | import com.querydsl.jpa.impl.JPAQuery;
7 | import com.querydsl.jpa.impl.JPAQueryFactory;
8 |
9 | import org.springframework.data.domain.Pageable;
10 |
11 | import java.util.List;
12 |
13 | import cn.mrdear.entity.QTCity;
14 | import cn.mrdear.entity.QTHotel;
15 | import cn.mrdear.repository.BaseRepository;
16 |
17 | /**
18 | * @author Niu Li
19 | * @date 2017/1/7
20 | */
21 | public class TCityRepositoryImpl extends BaseRepository implements TCityRepositoryCustom {
22 |
23 | @Override
24 | public List findCityAndHotel(Predicate predicate) {
25 | JPAQueryFactory queryFactory = new JPAQueryFactory(em);
26 | JPAQuery jpaQuery = queryFactory.select(QTCity.tCity,QTHotel.tHotel)
27 | .from(QTCity.tCity)
28 | .leftJoin(QTHotel.tHotel)
29 | .on(QTHotel.tHotel.city.longValue().eq(QTCity.tCity.id.longValue()));
30 | jpaQuery.where(predicate);
31 | return jpaQuery.fetch();
32 | }
33 |
34 | @Override
35 | public QueryResults findCityAndHotelPage(Predicate predicate,Pageable pageable) {
36 | JPAQueryFactory queryFactory = new JPAQueryFactory(em);
37 | JPAQuery jpaQuery = queryFactory.select(QTCity.tCity.id,QTHotel.tHotel)
38 | .from(QTCity.tCity)
39 | .leftJoin(QTHotel.tHotel)
40 | .on(QTHotel.tHotel.city.longValue().eq(QTCity.tCity.id.longValue()))
41 | .offset(pageable.getOffset())
42 | .limit(pageable.getPageSize());
43 | return jpaQuery.fetchResults();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/custom/THotelRepositoryCustom.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository.custom;
2 |
3 | /**
4 | * @author Niu Li
5 | * @date 2017/1/7
6 | */
7 | public interface THotelRepositoryCustom {
8 | }
9 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/java/cn/mrdear/repository/custom/THotelRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.repository.custom;
2 |
3 | /**
4 | * @author Niu Li
5 | * @date 2017/1/7
6 | */
7 | public class THotelRepositoryImpl {
8 | }
9 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/resources/config.properties:
--------------------------------------------------------------------------------
1 | #jdbc start
2 | jdbc.driver=com.mysql.jdbc.Driver
3 | jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8
4 | jdbc.username=root
5 | jdbc.password=7946521
6 |
7 | #druid start
8 | filters=stat
9 | maxActive=20
10 | initialSize=1
11 | maxWait=60000
12 | minIdle=10
13 | timeBetweenEvictionRunsMillis=60000
14 | minEvictableIdleTimeMillis=300000
15 | testWhileIdle=true
16 | testOnBorrow=false
17 | testOnReturn=false
18 | maxOpenPreparedStatements=20
19 | removeAbandoned=true
20 | removeAbandonedTimeout=1800
21 | logAbandoned=true
22 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
8 |
9 |
10 |
11 | webAppRootKey
12 | web.root
13 |
14 |
15 |
16 | contextConfigLocation
17 |
18 | classpath:spring/applicationContext.xml
19 |
20 |
21 |
22 |
23 | encodingFilter
24 | org.springframework.web.filter.CharacterEncodingFilter
25 |
26 | encoding
27 | UTF-8
28 |
29 |
30 |
31 | forceEncoding
32 | true
33 |
34 |
35 |
36 | encodingFilter
37 | /*
38 |
39 |
40 |
41 |
42 |
43 | org.springframework.web.util.WebAppRootListener
44 |
45 |
46 | org.springframework.web.context.ContextLoaderListener
47 |
48 |
49 |
50 | org.springframework.web.util.IntrospectorCleanupListener
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/JPA-Demo/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 |
2 |
3 | Hello World!
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/ResultVO.java:
--------------------------------------------------------------------------------
1 | package com.haikong;
2 |
3 | /**
4 | * Created by 牛李 on 2016/7/26.
5 | */
6 | public enum ResultVO {
7 | OK(0,"OK"),ID_INVALID(1,"ID is invalid"),OTHER_ERR(2,"未知错误");
8 |
9 | private int code;
10 | private String message;
11 |
12 | ResultVO(int code, String message) {
13 | this.code = code;
14 | this.message = message;
15 | }
16 |
17 | public int getCode() {
18 | return code;
19 | }
20 |
21 | public void setCode(int code) {
22 | this.code = code;
23 | }
24 |
25 | public String getMessage() {
26 | return message;
27 | }
28 |
29 | public void setMessage(String message) {
30 | this.message = message;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/application/RESTApplication.java:
--------------------------------------------------------------------------------
1 | package com.haikong.application;
2 |
3 | import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
4 | import com.haikong.filter.PreRequestFilter;
5 | import com.haikong.filter.ResponseFilter;
6 | import com.haikong.interceptor.GzipInterceptor;
7 | import org.glassfish.jersey.filter.LoggingFilter;
8 | import org.glassfish.jersey.server.ResourceConfig;
9 |
10 | /**
11 | * @author Niu Li
12 | * @date 2016/7/25
13 | */
14 | public class RESTApplication extends ResourceConfig {
15 |
16 | public RESTApplication() {
17 |
18 | //想让jersey托管的部分需要加入扫描,或者使用register指定托管类也可以
19 | packages("com.haikong.resources","com.haikong.exception");
20 | register(LoggingFilter.class);
21 | //json支持
22 | register(JacksonJsonProvider.class);
23 | //xml支持
24 | // register(MoxyXmlFeature.class);
25 | //文件上传支持
26 | // register(MultiPartFeature.class);
27 | //注册拦截器
28 | register(GzipInterceptor.class);
29 | //注册过滤器,扫包对@PreMatching注解无用,只能手动加入
30 | register(PreRequestFilter.class);
31 | register(ResponseFilter.class);
32 | /**
33 | * 对于链接,先执行请求过滤,有异常则执行异常过滤,最后执行回复过滤
34 | */
35 | System.out.println("加载RESTApplication");
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/dao/DeviceMapper.java:
--------------------------------------------------------------------------------
1 | package com.haikong.dao;
2 |
3 | import com.haikong.model.ReqDevice;
4 | import org.mybatis.spring.SqlSessionTemplate;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import javax.annotation.Resource;
8 |
9 | /**
10 | * 具体设备的dao层
11 | */
12 | @Repository("DeviceMapper")
13 | public class DeviceMapper {
14 | @Resource(name = "sqlSessionTemplate")
15 | private SqlSessionTemplate sqlSessionTemplate;
16 |
17 | /**
18 | * 根据传送的设备信息,更新设备状态为关闭
19 | * @param reqDevice
20 | * @return
21 | */
22 | public boolean updateDeviceOff(ReqDevice reqDevice){
23 | int k = sqlSessionTemplate.update("deviceMapper.updateDeviceOff",reqDevice);
24 | return k>0;
25 | }
26 |
27 | /**
28 | * 更新设备的data和onoff字段
29 | * @param reqDevice
30 | * @return
31 | */
32 | public boolean updateDeviceDetail(ReqDevice reqDevice){
33 | int k = sqlSessionTemplate.update("deviceMapper.updateDeviceDetail",reqDevice);
34 | return k>0;
35 | }
36 |
37 | /**
38 | * 插入一个设备记录,然后再插入一条用户和设备关系记录
39 | * @param reqDevice
40 | * @return
41 | */
42 | public boolean insertDevice(ReqDevice reqDevice){
43 | if (findDeviceData(reqDevice.getDevice_id())==null){//如果设备记录不存在
44 | sqlSessionTemplate.insert("deviceMapper.insertDevice",reqDevice);
45 | }
46 | int m = sqlSessionTemplate.insert("deviceMapper.insertUserDevice",reqDevice);//插入设备和用户关系
47 |
48 | return m>0;
49 | }
50 |
51 | /**
52 | * 删除一条用户设备关系记录,但是不删除设备记录
53 | * @param reqDevice
54 | * @return
55 | */
56 | public boolean deleteUserDevice(ReqDevice reqDevice){
57 | int k = sqlSessionTemplate.delete("deviceMapper.deleteUserDevice",reqDevice);
58 | return k>0;
59 | }
60 |
61 | /**
62 | * 根据device_id查找粗其data字段
63 | * @param device_id
64 | * @return
65 | */
66 | public String findDeviceData(String device_id){
67 | return sqlSessionTemplate.selectOne("deviceMapper.findDeviceData",device_id);
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/exception/DeviceExceptionMapper.java:
--------------------------------------------------------------------------------
1 | package com.haikong.exception;
2 |
3 | import com.haikong.ResultVO;
4 |
5 | import org.apache.log4j.Logger;
6 |
7 | import javax.ws.rs.core.MediaType;
8 | import javax.ws.rs.core.Response;
9 | import javax.ws.rs.ext.ExceptionMapper;
10 | import javax.ws.rs.ext.Provider;
11 |
12 | /**
13 | * @author Niu Li
14 | * @date 2016/7/26
15 | */
16 | @Provider
17 | public class DeviceExceptionMapper implements ExceptionMapper {
18 |
19 | @Override
20 | public Response toResponse(Exception e) {
21 | logger.error("错误信息:",e);
22 | Response.ResponseBuilder ResponseBuilder = null;
23 | if (e instanceof NumberFormatException){
24 | ErrorEntity entity = new ErrorEntity(ResultVO.OTHER_ERR.getCode(),ResultVO.OTHER_ERR.getMessage());
25 | ResponseBuilder = Response.ok(entity, MediaType.APPLICATION_JSON);
26 | }else {
27 | ErrorEntity entity = new ErrorEntity(ResultVO.OTHER_ERR.getCode(),e.getMessage());
28 | ResponseBuilder = Response.ok(entity, MediaType.APPLICATION_JSON);
29 | }
30 | System.out.println("执行自定义异常");
31 | return ResponseBuilder.build();
32 | }
33 |
34 | private static Logger logger = Logger.getLogger(DeviceExceptionMapper.class);
35 | }
36 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/exception/ErrorEntity.java:
--------------------------------------------------------------------------------
1 | package com.haikong.exception;
2 |
3 | import javax.xml.bind.annotation.XmlRootElement;
4 |
5 | /**
6 | * @author Niu Li
7 | * @date 2016/7/26
8 | */
9 | @XmlRootElement//标识该资源可以被jersey转为json或者xml
10 | public class ErrorEntity {
11 | private int resp_code;
12 | private String resp_msg;
13 |
14 | public ErrorEntity(int resp_code, String resp_msg) {
15 | this.resp_code = resp_code;
16 | this.resp_msg = resp_msg;
17 | }
18 | public ErrorEntity() {
19 | }
20 |
21 | public int getResp_code() {
22 | return resp_code;
23 | }
24 |
25 | public void setResp_code(int resp_code) {
26 | this.resp_code = resp_code;
27 | }
28 |
29 | public String getResp_msg() {
30 | return resp_msg;
31 | }
32 |
33 | public void setResp_msg(String resp_msg) {
34 | this.resp_msg = resp_msg;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/filter/PreRequestFilter.java:
--------------------------------------------------------------------------------
1 | package com.haikong.filter;
2 |
3 | import javax.ws.rs.container.ContainerRequestContext;
4 | import javax.ws.rs.container.ContainerRequestFilter;
5 | import javax.ws.rs.container.PreMatching;
6 | import java.io.IOException;
7 |
8 | /**
9 | * 对于request的过滤器
10 | * 过滤器主要是用来操纵请求和响应参数像HTTP头,URI和/或HTTP方法
11 | * @author Niu Li
12 | * @date 2016/7/27
13 | * Provider //这个是匹配后增加参数或者减少参数
14 | */
15 | @PreMatching //不知道为什么和后请求过滤器冲突,不能同时使用
16 | public class PreRequestFilter implements ContainerRequestFilter {
17 | @Override
18 | public void filter(ContainerRequestContext containerRequestContext) throws IOException {
19 | /**
20 | * 具体可以获取什么参数,加个断点就可以看到了
21 | */
22 | System.out.println("PreRequestFilter");
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/filter/ResponseFilter.java:
--------------------------------------------------------------------------------
1 | package com.haikong.filter;
2 |
3 | import javax.ws.rs.container.ContainerRequestContext;
4 | import javax.ws.rs.container.ContainerResponseContext;
5 | import javax.ws.rs.container.ContainerResponseFilter;
6 | import javax.ws.rs.ext.Provider;
7 | import java.io.IOException;
8 |
9 | /**
10 | * 对于response的过滤器
11 | * 过滤器主要是用来操纵请求和响应参数像HTTP头,URI和/或HTTP方法
12 | * @author Niu Li
13 | * @date 2016/7/27
14 | */
15 | @Provider
16 | public class ResponseFilter implements ContainerResponseFilter {
17 | @Override
18 | public void filter(ContainerRequestContext containerRequestContext,
19 | ContainerResponseContext containerResponseContext) throws IOException {
20 | /**
21 | * 具体可以获取什么参数,加个断点就可以看到了
22 | */
23 | System.out.println("执行回复过滤");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/interceptor/GzipInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.haikong.interceptor;
2 |
3 | import javax.ws.rs.WebApplicationException;
4 | import javax.ws.rs.core.MultivaluedMap;
5 | import javax.ws.rs.ext.WriterInterceptor;
6 | import javax.ws.rs.ext.WriterInterceptorContext;
7 | import java.io.IOException;
8 | import java.io.OutputStream;
9 | import java.util.zip.GZIPOutputStream;
10 |
11 | /**
12 | * Gzip压缩输出
13 | * 拦截器意图操纵的实体,通过操纵实体的输入/输出数据流。比如你需要编码的客户端请求的实体主体
14 | *
15 | * @author Niu Li
16 | * @date 2016/7/27
17 | */
18 | public class GzipInterceptor implements WriterInterceptor {
19 | @Override
20 | public void aroundWriteTo(WriterInterceptorContext context)
21 | throws IOException, WebApplicationException {
22 |
23 | MultivaluedMap headers = context.getHeaders();
24 | headers.add("Content-Encoding", "gzip");
25 | String ContentType = context.getMediaType().toString();
26 | headers.add("Content-Type",ContentType+";charset=utf-8");//解决乱码问题
27 | final OutputStream outputStream = context.getOutputStream();
28 | context.setOutputStream(new GZIPOutputStream(outputStream));
29 | context.proceed();
30 | System.out.println("GZIP拦截器压缩");
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/model/Device.java:
--------------------------------------------------------------------------------
1 | package com.haikong.model;
2 |
3 | import java.sql.Timestamp;
4 |
5 | /**
6 | * 保存设备消息的类
7 | */
8 | public class Device {
9 |
10 | /**
11 | * device_id : gh_4f7d3885c0a9_9ea2808950a2dce5
12 | * device_type : gh_4f7d3885c0a9
13 | * msg_id : 72553035
14 | * msg_type : notify
15 | * services : {"operation_status":{"status":1},"power_switch":{"on_off":true}}
16 | * create_time : 1463367815
17 | * data : {"vol":2265,"power":3,"ene":0,"t1":"0-0-0-0","t2":"0-0-0-0","t3":"0-0-0-0","t4":"0-0-0-0","ct":"0-0-1"}
18 | */
19 |
20 | private String device_id;
21 | private String device_type;
22 | private long msg_id;
23 | private String msg_type;
24 | /**
25 | * operation_status : {"status":1}
26 | * power_switch : {"on_off":true}
27 | */
28 |
29 | private ServicesBean services;
30 | private Timestamp create_time;
31 | private String data;
32 |
33 | public String getDevice_id() {
34 | return device_id;
35 | }
36 |
37 | public void setDevice_id(String device_id) {
38 | this.device_id = device_id;
39 | }
40 |
41 | public String getDevice_type() {
42 | return device_type;
43 | }
44 |
45 | public void setDevice_type(String device_type) {
46 | this.device_type = device_type;
47 | }
48 |
49 | public long getMsg_id() {
50 | return msg_id;
51 | }
52 |
53 | public void setMsg_id(long msg_id) {
54 | this.msg_id = msg_id;
55 | }
56 |
57 | public String getMsg_type() {
58 | return msg_type;
59 | }
60 |
61 | public void setMsg_type(String msg_type) {
62 | this.msg_type = msg_type;
63 | }
64 |
65 | public ServicesBean getServices() {
66 | return services;
67 | }
68 |
69 | public void setServices(ServicesBean services) {
70 | this.services = services;
71 | }
72 |
73 | public Timestamp getCreate_time() {
74 | return create_time;
75 | }
76 |
77 | public void setCreate_time(long create_time) {
78 | this.create_time = new Timestamp(create_time*1000);
79 | }
80 |
81 | public String getData() {
82 | return data;
83 | }
84 |
85 | public void setData(String data) {
86 | this.data = data;
87 | }
88 |
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/model/ReqDevice.java:
--------------------------------------------------------------------------------
1 | package com.haikong.model;
2 |
3 | import javax.xml.bind.annotation.XmlRootElement;
4 |
5 | /**
6 | * 主动请求时,返回值使用这个模型
7 | */
8 | @XmlRootElement
9 | public class ReqDevice extends Device {
10 | private int asy_error_code;
11 | private String asy_error_msg;
12 |
13 | private String user;//用户的openid
14 |
15 | public int getAsy_error_code() {
16 | return asy_error_code;
17 | }
18 |
19 | public void setAsy_error_code(int asy_error_code) {
20 | this.asy_error_code = asy_error_code;
21 | }
22 |
23 | public String getAsy_error_msg() {
24 | return asy_error_msg;
25 | }
26 |
27 | public void setAsy_error_msg(String asy_error_msg) {
28 | this.asy_error_msg = asy_error_msg;
29 | }
30 |
31 | public String getUser() {
32 | return user;
33 | }
34 |
35 | public void setUser(String user) {
36 | this.user = user;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/model/ServicesBean.java:
--------------------------------------------------------------------------------
1 | package com.haikong.model;
2 |
3 | public class ServicesBean {
4 | /**
5 | * status : 1
6 | */
7 |
8 | private OperationStatusBean operation_status;
9 | /**
10 | * on_off : true
11 | */
12 |
13 | private PowerSwitchBean power_switch;
14 |
15 | public ServicesBean(int status,boolean on_off){
16 | operation_status = new OperationStatusBean();
17 | operation_status.setStatus(status);
18 | power_switch = new PowerSwitchBean();
19 | power_switch.setOn_off(on_off);
20 | }
21 |
22 | public ServicesBean(){}
23 |
24 | public OperationStatusBean getOperation_status() {
25 | return operation_status;
26 | }
27 |
28 | public void setOperation_status(OperationStatusBean operation_status) {
29 | this.operation_status = operation_status;
30 | }
31 |
32 | public PowerSwitchBean getPower_switch() {
33 | return power_switch;
34 | }
35 |
36 | public void setPower_switch(PowerSwitchBean power_switch) {
37 | this.power_switch = power_switch;
38 | }
39 |
40 | public static class OperationStatusBean {
41 | private int status = 0;
42 |
43 | public int getStatus() {
44 | return status;
45 | }
46 |
47 | public void setStatus(int status) {
48 | this.status = status;
49 | }
50 | }
51 |
52 | public static class PowerSwitchBean {
53 | private boolean on_off = false;
54 |
55 | public boolean getOn_off() {
56 | return on_off;
57 | }
58 |
59 | public void setOn_off(boolean on_off) {
60 | this.on_off = on_off;
61 | }
62 | }
63 | }
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/service/DeviceService.java:
--------------------------------------------------------------------------------
1 | package com.haikong.service;
2 |
3 | import com.alibaba.fastjson.JSONObject;
4 | import com.haikong.dao.DeviceMapper;
5 |
6 | import org.apache.log4j.Logger;
7 | import org.springframework.stereotype.Service;
8 |
9 | import javax.annotation.Resource;
10 |
11 | /**
12 | * 处理设备传送来数据的service
13 | */
14 | @Service("DeviceService")
15 | public class DeviceService {
16 |
17 | @Resource(name = "DeviceMapper")
18 | private DeviceMapper deviceMapper;
19 |
20 | /**
21 | * 接收notify类型的设备消息
22 | * 如果设备未联网,则设置为关闭状态
23 | * @param object
24 | */
25 | public void deviceNotify(JSONObject object){
26 | }
27 |
28 | /**
29 | * 接收get_resp类型的设备消息,这里还要根据返回码来设置设备的其他状态
30 | * @param object
31 | */
32 | public void deviceGetResp(JSONObject object){
33 | }
34 |
35 | /**
36 | * 接收set_resp类型的设备消息,这里还要根据返回码来设置设备的其他状态
37 | * @param object
38 | */
39 | public void deviceSetResp(JSONObject object){
40 | }
41 |
42 | /**
43 | * 处理用户绑定事件
44 | * @param object
45 | */
46 | public void deviceBind(JSONObject object){
47 | }
48 | /**
49 | * 处理用户解绑事件
50 | * @param object
51 | */
52 | public void deviceUnBind(JSONObject object){
53 |
54 | }
55 |
56 | private static Logger logger = Logger.getLogger(DeviceService.class);
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/util/CheckUtil.java:
--------------------------------------------------------------------------------
1 | package com.haikong.util;
2 |
3 | import org.springframework.util.Assert;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * 具体检查登录验证的工具类
9 | */
10 | public class CheckUtil {
11 | public static boolean checkSignature(String signature,String timestamp,String nonce){
12 | Assert.notNull(signature,"签名值不能为null");
13 | Assert.notNull(timestamp,"时间戳不能为null");
14 | Assert.notNull(nonce,"nonce不为null");
15 |
16 | String[] strArr = {Constants.TOKEN,timestamp,nonce};
17 | Arrays.sort(strArr);
18 | StringBuilder builder = new StringBuilder();
19 | for (String aStrArr : strArr) {
20 | builder.append(aStrArr);
21 | }
22 | System.out.println("验证结果:"+DecriptUtil.SHA1(builder.toString()).equals(signature));
23 |
24 | return DecriptUtil.SHA1(builder.toString()).equals(signature);
25 | }
26 |
27 | private CheckUtil(){}
28 | }
29 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/util/Constants.java:
--------------------------------------------------------------------------------
1 | package com.haikong.util;
2 |
3 | /**
4 | * 保存常量信息
5 | */
6 | public class Constants {
7 | /**
8 | * 微信接入token ,用于验证微信接口
9 | */
10 | public static String TOKEN = "niuli123";
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/java/com/haikong/util/DeviceUtil.java:
--------------------------------------------------------------------------------
1 | package com.haikong.util;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.JSONObject;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import java.io.BufferedReader;
8 | import java.io.IOException;
9 | import java.io.InputStreamReader;
10 |
11 | /**
12 | * 处理设备消息的工具类
13 | */
14 | public class DeviceUtil {
15 |
16 | /**
17 | * 把设备传送来的json解析为json对象
18 | * @param req 设备请求
19 | * @return json对象
20 | */
21 | public static JSONObject parseJSON(HttpServletRequest req){
22 | BufferedReader reader = null;
23 | try {
24 | reader = new BufferedReader(new InputStreamReader(req.getInputStream()));//获取请求的输入流
25 |
26 | StringBuilder builder = new StringBuilder();
27 | String str = null;
28 | //读入json串
29 | while ((str = reader.readLine())!=null){
30 | builder.append(str);
31 | }
32 | //转换为json对象,并返回
33 | return JSON.parseObject(builder.toString());
34 |
35 | } catch (IOException e) {
36 | e.printStackTrace();
37 | }finally {
38 | try {
39 | if (reader!=null) reader.close();
40 | reader = null;
41 | } catch (IOException e) {
42 | e.printStackTrace();
43 | }
44 | }
45 | return null;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/resources/db.properties:
--------------------------------------------------------------------------------
1 | jdbc.driver=com.mysql.jdbc.Driver
2 | jdbc.url=jdbc:mysql://localhost:3306/haikong?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
3 | jdbc.username=root
4 | jdbc.password=7946521
5 |
6 | filters:stat
7 |
8 | maxActive:20
9 | initialSize:1
10 | maxWait:60000
11 | minIdle:10
12 |
13 | timeBetweenEvictionRunsMillis:60000
14 | minEvictableIdleTimeMillis:300000
15 |
16 | validationQuery:SELECT 1
17 | testWhileIdle:true
18 | testOnBorrow:false
19 | testOnReturn:false
20 |
21 | maxOpenPreparedStatements:20
22 | removeAbandoned:true
23 | removeAbandonedTimeout:1800
24 | logAbandoned:true
25 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.logger.com.haikong = warn, file
2 | log4j.rootLogger=warn, stdout
3 | #Console
4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
5 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss} [%t] %c %p - %m%n
7 |
8 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/resources/mybatis/Mapper/DeviceMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 | UPDATE device set onoffStatus = 0 ,asy_error_code = #{asy_error_code},create_time = #{create_time}
8 | WHERE device_id = #{device_id}
9 |
10 |
11 |
12 | UPDATE device SET onoffStatus = #{services.power_switch.on_off},data = #{data},create_time = #{create_time}
13 | ,asy_error_code = #{asy_error_code}
14 | WHERE device_id = #{device_id};
15 |
16 |
17 |
18 | INSERT INTO device (device_id, device_type, onoffStatus) VALUES (#{device_id},#{device_type},0)
19 |
20 |
21 |
22 | INSERT INTO user_device (device_id, user) VALUES (#{device_id},#{user})
23 |
24 |
25 |
26 | DELETE FROM user_device WHERE device_id = #{device_id} AND user = #{user}
27 |
28 |
29 |
32 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/resources/mybatis/SqlMapConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 | Archetype Created Web Application
7 |
8 |
9 | JerseyApplication
10 | org.glassfish.jersey.servlet.ServletContainer
11 |
12 | javax.ws.rs.Application
13 | com.haikong.application.RESTApplication
14 |
15 | 1
16 |
17 |
18 | JerseyApplication
19 | /*
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Jersey-Demo/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 |
2 |
3 | Hello World!
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Maven-Demo/doc/README.MD:
--------------------------------------------------------------------------------
1 | ##一.模块详解
2 |
3 | 1. core主要是分发器,接收请求后转向其他模块寻找对应的Service来调用其方法.
4 | 2. common里面我打算放置通用的数据库表(比如用户表,这个任何设备都通用)和一些utils工具(例如httpclient以及xml解析器)
5 | 3. switch里面主要封装了插座操作的entity,mapper,service,对外提供方法
6 |
7 | ##二.改动
8 |
9 | 1. mybatis全部采用mapper代理方式开发,配置多数据源也方便.
10 | 2. 替换jsp为thymeleaf模板引擎
11 | 3. springMVC的json解析器替换为fastjson
12 |
13 | ##三.扩展
14 |
15 | 1. 扩展的话直接另起一个maven项目,仿照switch里面来封装service,在core中控制行为即可.
16 | 2. 目前是都放在一个数据库中,等项目大了另起数据库的话,只需要在application中配置多数据源即可.
--------------------------------------------------------------------------------
/Maven-Demo/haikong-common/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | haikong
7 | com.haikong
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | haikong-common
13 |
14 |
15 |
16 |
17 |
18 |
19 | dom4j
20 | dom4j
21 |
22 |
23 |
24 | com.thoughtworks.xstream
25 | xstream
26 |
27 |
28 |
29 | org.apache.httpcomponents
30 | httpclient
31 |
32 |
33 | org.apache.httpcomponents
34 | httpcore
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-common/src/main/java/com/haikong/common/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package com.haikong.common.mapper;
2 |
3 | import com.haikong.common.entity.User;
4 |
5 | /**
6 | * @author Niu Li
7 | * @date 2016/9/6
8 | */
9 | public interface UserMapper {
10 |
11 | public User find(String openId);
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-common/src/main/resources/mybatis/mapper/userMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
9 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/pom.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 | haikong
6 | com.haikong
7 | 1.0.0
8 |
9 | 4.0.0
10 | haikong-core
11 | war
12 | haikong-core
13 | http://maven.apache.org
14 |
15 |
16 |
17 | junit
18 | junit
19 | 4.10
20 | test
21 |
22 |
23 |
24 | org.thymeleaf
25 | thymeleaf
26 |
27 |
28 | org.thymeleaf
29 | thymeleaf-spring4
30 |
31 |
32 |
33 | com.haikong
34 | haikong-switch
35 | 1.0.0
36 |
37 |
38 | com.haikong
39 | haikong-common
40 | 1.0.0
41 |
42 |
43 |
44 |
45 | core
46 |
47 |
48 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/java/com/haikong/core/controller/indexController.java:
--------------------------------------------------------------------------------
1 | package com.haikong.core.controller;
2 |
3 | import com.haikong.common.entity.User;
4 | import com.haikong.common.mapper.UserMapper;
5 |
6 | import org.springframework.stereotype.Controller;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 | import org.springframework.web.bind.annotation.ResponseBody;
10 |
11 | import javax.annotation.Resource;
12 |
13 | /**
14 | * @author Niu Li
15 | * @date 2016/9/6
16 | */
17 | @Controller
18 | public class indexController {
19 |
20 | @Resource
21 | private UserMapper userMapper;
22 |
23 |
24 | @RequestMapping(value = "/hello",method = RequestMethod.GET)
25 | public @ResponseBody User toIndex(){
26 |
27 | User user = userMapper.find("ov4a6wg2snvQ3eJiZcxJI31noVZk");
28 | return user;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/resources/config.properties:
--------------------------------------------------------------------------------
1 | #\u300Ecomments\u300FUpdate key\uFF1AACCESS_TOKEN
2 | #Fri May 13 09:10:55 CST 2016
3 | OVERDUE_ACCESS_TOKEN_TIME=7200
4 | ACCESS_TOKEN=hEzgNHDk6-iVa0Mg8orfXahGLaL4DUPf01_e3tNnJ7hwZDQ2pXknDiWn97xM4iewIBR19K4k4SF9yu3eiRwXOGcRj0iMKFX8iQ-Y2_xdKKT9-eMnfjvD_KJqB3XDxTfuZSRdAEAUNM
5 |
6 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/resources/db.properties:
--------------------------------------------------------------------------------
1 | jdbc.driver=com.mysql.jdbc.Driver
2 | jdbc.url=jdbc:mysql://localhost:3306/haikong?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
3 | jdbc.username=root
4 | jdbc.password=7946521
5 |
6 | filters:stat
7 |
8 | maxActive:20
9 | initialSize:1
10 | maxWait:60000
11 | minIdle:10
12 |
13 | timeBetweenEvictionRunsMillis:60000
14 | minEvictableIdleTimeMillis:300000
15 |
16 | validationQuery:SELECT 1
17 | testWhileIdle:true
18 | testOnBorrow:false
19 | testOnReturn:false
20 |
21 | maxOpenPreparedStatements:20
22 | removeAbandoned:true
23 | removeAbandonedTimeout:1800
24 | logAbandoned:true
25 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.logger.com.haikong = debug
2 | log4j.rootLogger=debug, stdout
3 | #Console
4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
5 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.stdout.layout.ConversionPattern=%-5p - %m%n
7 |
8 | log4j.logger.org.springframework.web=debug
9 | log4j.logger.org.springframework=info
10 |
11 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/resources/mybatis/SqlMapConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/resources/mybatis/mapper/2.txt:
--------------------------------------------------------------------------------
1 | 222
--------------------------------------------------------------------------------
/Maven-Demo/haikong-core/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 |
2 |
3 | Hello World!
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Maven-Demo/haikong-switch/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | haikong
7 | com.haikong
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | haikong-switch
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Client/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | Motan-Demo
7 | cn.mrdear.motan
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | cn.mrdear.motan
13 | Service-Client
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Client/src/main/java/cn/mrdear/client/dto/UserDTO.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.client.dto;
2 |
3 | import lombok.Data;
4 |
5 | import java.io.Serializable;
6 |
7 | /**
8 | * 用户DTO,用于Service层传输
9 | * @author Niu Li
10 | * @since 2017/6/12
11 | */
12 | @Data
13 | public class UserDTO implements Serializable{
14 |
15 | private static final long serialVersionUID = 4086492518942464226L;
16 |
17 | private Long id;
18 |
19 | private String username;
20 |
21 | private String password;
22 |
23 | private Integer age;
24 |
25 | private String nickname;
26 |
27 | private String mail;
28 |
29 | private String memo;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Client/src/main/java/cn/mrdear/client/service/IUserService.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.client.service;
2 |
3 | import cn.mrdear.client.dto.UserDTO;
4 |
5 | import java.util.Collection;
6 | import java.util.List;
7 |
8 | /**
9 | * 用户服务,一般都会在返回层再包裹一层,这里简而化之
10 | * @author Niu Li
11 | * @since 2017/6/12
12 | */
13 | public interface IUserService {
14 |
15 | /**
16 | * 根据id查找
17 | */
18 | UserDTO findById(Long id);
19 |
20 | /**
21 | * 根据id批量查询
22 | */
23 | List queryByIds(Collection ids);
24 |
25 | /**
26 | * 更新用户
27 | * @return 返回更新后的实体
28 | */
29 | UserDTO updateById(UserDTO userDTO);
30 |
31 | /**
32 | * 根据id删除用户
33 | */
34 | Boolean deleteById(Long id);
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Consumer/src/main/java/cn/mrdear/consumer/ApplicationStart.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.consumer;
2 |
3 | import org.springframework.context.ApplicationContext;
4 | import org.springframework.context.support.ClassPathXmlApplicationContext;
5 |
6 | import cn.mrdear.client.service.IUserService;
7 |
8 | /**
9 | * @author Niu Li
10 | * @since 2017/6/14
11 | */
12 | public class ApplicationStart {
13 |
14 | public static void main(String[] args) throws InterruptedException {
15 | ApplicationContext ctx = new ClassPathXmlApplicationContext(
16 | "classpath:applicationContext.xml");
17 | IUserService service = (IUserService) ctx.getBean("userService");
18 | System.out.println(service.findById(1L));
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Consumer/src/main/resources/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
22 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Consumer/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | %d{HH:mm:ss} [%t] %logger{5} [%line] %p - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/java/cn/mrdear/provider/ApplicationStart.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider;
2 |
3 | import com.weibo.api.motan.common.MotanConstants;
4 | import com.weibo.api.motan.util.MotanSwitcherUtil;
5 |
6 | import org.springframework.context.ApplicationContext;
7 | import org.springframework.context.support.ClassPathXmlApplicationContext;
8 |
9 | /**
10 | * @author Niu Li
11 | * @since 2017/6/14
12 | */
13 | public class ApplicationStart {
14 |
15 | public static void main(String[] args) throws InterruptedException {
16 | ApplicationContext applicationContext =
17 | new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
18 | MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
19 | System.out.println("server start...");
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/java/cn/mrdear/provider/convert/UserConvert.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.convert;
2 |
3 | import org.springframework.beans.BeanUtils;
4 | import org.springframework.util.CollectionUtils;
5 |
6 | import cn.mrdear.client.dto.UserDTO;
7 | import cn.mrdear.provider.domain.User;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 | import java.util.stream.Collectors;
12 |
13 | /**
14 | * @author Niu Li
15 | * @since 2017/6/12
16 | */
17 | public class UserConvert {
18 |
19 | public static UserDTO toDTO(User user) {
20 | UserDTO userDTO = new UserDTO();
21 | BeanUtils.copyProperties(user,userDTO);
22 | return userDTO;
23 | }
24 |
25 |
26 | public static List toDTOS(List users) {
27 | if (CollectionUtils.isEmpty(users)) {
28 | return new ArrayList<>(1);
29 | }
30 | List results = new ArrayList<>();
31 | return users.stream().map(UserConvert::toDTO)
32 | .collect(Collectors.toList());
33 | }
34 |
35 |
36 | public static User toDO(UserDTO userDTO) {
37 | User user = new User();
38 | BeanUtils.copyProperties(userDTO,user);
39 | return user;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/java/cn/mrdear/provider/dao/UserRepository.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.dao;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.data.jpa.repository.Query;
5 |
6 | import cn.mrdear.provider.domain.User;
7 |
8 | import java.util.Collection;
9 | import java.util.List;
10 |
11 | /**
12 | * JPA repo层
13 | * @author Niu Li
14 | * @since 2017/6/12
15 | */
16 | public interface UserRepository extends JpaRepository{
17 |
18 | User findById(Long id);
19 |
20 | @Query("select p from User p where id in (?1)")
21 | List queryByIds(Collection ids);
22 |
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/java/cn/mrdear/provider/domain/User.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.domain;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import java.io.Serializable;
11 |
12 | /**
13 | * 用户实体类,对应数据库
14 | * @author Niu Li
15 | * @since 2017/6/12
16 | */
17 | @Data
18 | @Entity
19 | @Table(name = "user")
20 | public class User implements Serializable{
21 |
22 | private static final long serialVersionUID = 1793488098966504793L;
23 | @Id
24 | @GeneratedValue
25 | private Long id;
26 |
27 | private String username;
28 |
29 | private String password;
30 |
31 | private Integer age;
32 |
33 | private String nickname;
34 |
35 | private String mail;
36 |
37 | private String memo;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/java/cn/mrdear/provider/service/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.provider.service;
2 |
3 | import cn.mrdear.client.dto.UserDTO;
4 | import cn.mrdear.client.service.IUserService;
5 | import cn.mrdear.provider.convert.UserConvert;
6 | import cn.mrdear.provider.dao.UserRepository;
7 | import cn.mrdear.provider.domain.User;
8 |
9 | import javax.annotation.Resource;
10 |
11 | import java.util.Collection;
12 | import java.util.List;
13 |
14 | /**
15 | * @author Niu Li
16 | * @since 2017/6/14
17 | */
18 | public class UserServiceImpl implements IUserService{
19 | @Resource
20 | private UserRepository userRepository;
21 |
22 | @Override
23 | public UserDTO findById(Long id) {
24 | User user = userRepository.findById(id);
25 | return UserConvert.toDTO(user);
26 | }
27 |
28 | @Override
29 | public List queryByIds(Collection ids) {
30 | List users = userRepository.queryByIds(ids);
31 | return UserConvert.toDTOS(users);
32 | }
33 |
34 | @Override
35 | public UserDTO updateById(UserDTO userDTO) {
36 | User user = UserConvert.toDO(userDTO);
37 | userRepository.save(user);
38 | return this.findById(userDTO.getId());
39 | }
40 |
41 | @Override
42 | public Boolean deleteById(Long id) {
43 | userRepository.delete(id);
44 | return true;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/resources/h2/data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('zhangsan',
2 | '123456', 18, '张三', '1111@qq.com', 'hahahah');
3 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('lis',
4 | '123456', 19, '李四', '123131@qq.com', 'xixiixxi');
5 | INSERT INTO user (username, password, age, nickname, mail, memo) VALUES ('wanger',
6 | '123456', 29, '王二', '12131984@qq.com', 'dqdh');
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/resources/h2/schema.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE user if exist;
2 | create table user (
3 | id INT(11) AUTO_INCREMENT PRIMARY KEY ,
4 | username VARCHAR(255),
5 | password VARCHAR(255),
6 | age INT(3),
7 | nickname VARCHAR(255),
8 | mail VARCHAR(255),
9 | memo VARCHAR(255),
10 | );
--------------------------------------------------------------------------------
/Motan-Demo/Service-Provider/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | %d{HH:mm:ss} [%t] %logger{5} [%line] %p - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Pay-Demo/lib/alipay-sdk-java20161029120104-source.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrdear/JavaWEB/a7b8da4e680ab0b06d057b3537e19f47d103bf54/Pay-Demo/lib/alipay-sdk-java20161029120104-source.jar
--------------------------------------------------------------------------------
/Pay-Demo/lib/alipay-sdk-java20161029120104.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrdear/JavaWEB/a7b8da4e680ab0b06d057b3537e19f47d103bf54/Pay-Demo/lib/alipay-sdk-java20161029120104.jar
--------------------------------------------------------------------------------
/Pay-Demo/src/main/java/cn/mrdear/pay/unionpay/UnionPayTrade.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.unionpay;
2 |
3 |
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import java.util.Map;
8 |
9 |
10 | import cn.mrdear.pay.unionpay.sdk.AcpService;
11 | import cn.mrdear.pay.util.SignUtil;
12 |
13 | /**
14 | * 银联交易入口,只为了和支付宝,微信调用统一
15 | * @author Niu Li
16 | * @date 2016/10/31
17 | */
18 | public class UnionPayTrade {
19 |
20 | private static Logger logger = LoggerFactory.getLogger(UnionPayTrade.class);
21 |
22 | /**
23 | * 开通token支付
24 | * @param paramMap 请求参数
25 | * @return 请求返回结果
26 | */
27 | public String tokenOpen(Map paramMap,Map customerInfo){
28 | return UnionPayConfig.getInstance().tokenOpen(paramMap,customerInfo);
29 | }
30 |
31 | /**
32 | * 发送短信
33 | * @param paramMap 请求参数
34 | * @return 返回结果
35 | */
36 | public Map msg(Map paramMap,Map customerInfo){
37 | return UnionPayConfig.getInstance().msgSend(paramMap,customerInfo);
38 | }
39 |
40 | /**
41 | * 消费
42 | * @param paramMap 请求参数
43 | * @return 请求结果
44 | */
45 | public Map consume(Map paramMap,Map customerInfo){
46 | return UnionPayConfig.getInstance().consume(paramMap,customerInfo);
47 | }
48 |
49 | /**
50 | * 退款
51 | * @param paramMap 请求参数
52 | * @return 请求结果
53 | */
54 | public Map refund(Map paramMap){
55 | return UnionPayConfig.getInstance().refund(paramMap);
56 | }
57 |
58 | /**
59 | * 银行卡回调验签
60 | * @param request 回调请求
61 | * @return true成功
62 | */
63 | public boolean verifyNotify(HttpServletRequest request){
64 | Map paranMap = SignUtil.request2Map(request);
65 | logger.debug("银行卡回调参数:"+paranMap.toString());
66 | boolean ischeck = AcpService.validate(paranMap, UnionPayConfig.ENCODING_UTF8);
67 | logger.debug("银行卡回调验签结果:"+ischeck);
68 | return ischeck;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Pay-Demo/src/main/java/cn/mrdear/pay/util/XmlUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.util;
2 |
3 |
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.InputStream;
6 | import java.io.InputStreamReader;
7 | import java.io.StringReader;
8 | import java.io.UnsupportedEncodingException;
9 |
10 | import javax.xml.bind.JAXBContext;
11 | import javax.xml.bind.JAXBException;
12 | import javax.xml.bind.Marshaller;
13 | import javax.xml.bind.Unmarshaller;
14 |
15 | public class XmlUtil {
16 |
17 |
18 | /**
19 | * XML转对象
20 | *
21 | * @param xmlStr
22 | * @param t
23 | * @return
24 | */
25 | @SuppressWarnings("unchecked")
26 | public static T xmlToBean(String xmlStr, Class t) {
27 | try {
28 | JAXBContext context = JAXBContext.newInstance(t);
29 | Unmarshaller unmarshaller = context.createUnmarshaller();
30 | T ts = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
31 | return ts;
32 | } catch (JAXBException e) {
33 | e.printStackTrace();
34 | return null;
35 | }
36 | }
37 |
38 | /**
39 | * XML转对象
40 | *
41 | * @param t
42 | * @return
43 | */
44 | @SuppressWarnings("unchecked")
45 | public static T xmlToBean(InputStream input, Class t) {
46 | try {
47 | JAXBContext context = JAXBContext.newInstance(t);
48 | Unmarshaller unmarshaller = context.createUnmarshaller();
49 | T ts = (T) unmarshaller.unmarshal(new InputStreamReader(input,
50 | "UTF-8"));
51 | return ts;
52 | } catch (JAXBException e) {
53 | e.printStackTrace();
54 | } catch (UnsupportedEncodingException e) {
55 | e.printStackTrace();
56 | }
57 | return null;
58 | }
59 |
60 | /**
61 | * 对象转XML
62 | *
63 | * @param out
64 | * @param to
65 | */
66 | public static String beanToXml(ByteArrayOutputStream out, Object to) {
67 | try {
68 | JAXBContext context = JAXBContext.newInstance(to.getClass());
69 | Marshaller marshaller = context.createMarshaller();
70 | marshaller.marshal(to, out);
71 | return new String(out.toByteArray(), "UTF-8");
72 | } catch (JAXBException e) {
73 | e.printStackTrace();
74 | } catch (UnsupportedEncodingException e) {
75 | e.printStackTrace();
76 | }
77 | return null;
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/Pay-Demo/src/main/java/cn/mrdear/pay/wechat/WechatConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.wechat;
2 |
3 | /**
4 | * 微信支付配置
5 | * @author Niu Li
6 | * @date 2016/10/29
7 | */
8 | public final class WechatConfig {
9 | /**
10 | * 用户的id
11 | */
12 | public static final String APP_ID = "xxxxx";
13 | /**
14 | * 身份密钥
15 | */
16 | public static final String APP_SECRET = "xxxxx";
17 | /**
18 | * 商户id
19 | */
20 | public static final String MCH_ID = "xxxxx";
21 | /**
22 | * 统一下单地址
23 | */
24 | public static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
25 | /**
26 | * 交易退款地址
27 | */
28 | public static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
29 | /**
30 | * 交易退款查询地址
31 | */
32 | public static final String REFUND_QUERY = "https://api.mch.weixin.qq.com/pay/refundquery";
33 | /**
34 | * 支付成功回调
35 | */
36 | public static final String NOTIFY_PAY = "http://mart.xxxxxx.com/api/rest/notify/wechatNotify";
37 | /**
38 | * 支付类型
39 | */
40 | public static final String TRADE_TYPE = "APP";
41 | /**
42 | * 证书地址
43 | */
44 | public static final String CERT_PATH = "C:\\Users\\NL\\cert\\apiclient_cert.p12";
45 | /**
46 | * 成功标识
47 | */
48 | public static final String SUCCESS_REQUEST = "SUCCUSS";
49 |
50 | /**
51 | * 不可实例化
52 | */
53 | private WechatConfig(){}
54 |
55 | private volatile static WechatClient wechatClient = null;
56 |
57 | /**
58 | * 双重锁单例
59 | * @return WechatClient实例
60 | */
61 | public static WechatClient getInstance(){
62 | if (wechatClient == null){
63 | synchronized (WechatConfig.class){
64 | if (wechatClient == null){
65 | return new WechatClient(APP_ID,MCH_ID,APP_SECRET,TRADE_TYPE);
66 | }
67 | }
68 | }
69 | return wechatClient;
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/Pay-Demo/src/main/resources/acp_sdk.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | acpsdk.frontTransUrl=https://gateway.95516.com/gateway/api/frontTransReq.do
5 |
6 | acpsdk.backTransUrl=https://gateway.95516.com/gateway/api/backTransReq.do
7 |
8 | acpsdk.singleQueryUrl=https://gateway.95516.com/gateway/api/queryTrans.do
9 |
10 | acpsdk.batchTransUrl=https://gateway.95516.com/gateway/api/batchTrans.do
11 |
12 | acpsdk.fileTransUrl=https://filedownload.95516.com/
13 |
14 | acpsdk.signCert.pwd=123456
15 |
16 | #linux
17 | #acpsdk.signCert.path=/home/web_as/certs/mypfx.pfx
18 | #
19 | #acpsdk.signCert.type=PKCS12
20 | #
21 | #acpsdk.encryptCert.path=/home/web_as/certs/RSA2048_PROD_index_22.cer
22 | #
23 | #acpsdk.validateCert.dir=/home/web_as/certs/
24 | #
25 | #acpsdk.signCert.dir=/home/web_as/certs/
26 | #
27 | #log.back.rootPath=/home/web_as/logs
28 |
29 |
30 | #linux-product
31 | acpsdk.signCert.path=D:/certs/mypfx.pfx
32 |
33 | acpsdk.signCert.type=PKCS12
34 |
35 | acpsdk.encryptCert.path=D:/certs/RSA2048_PROD_index_22.cer
36 |
37 | acpsdk.validateCert.dir=D:/certs
38 |
39 | acpsdk.signCert.dir=D:/certs
40 |
41 | log.back.rootPath=D:/certs
42 |
43 |
--------------------------------------------------------------------------------
/Pay-Demo/src/test/java/cn/mrdear/pay/alipay/AlipayTradeTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.alipay;
2 |
3 | import com.alipay.api.AlipayApiException;
4 |
5 | import org.junit.Test;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * @author Niu Li
12 | * @date 2016/10/29
13 | */
14 | public class AlipayTradeTest {
15 |
16 | @Test
17 | public void testTradeWapPayRequest(){
18 | AlipayTrade alipayTrade = new AlipayTrade();
19 | Map paraMap = new HashMap();
20 | paraMap.put("out_trade_no",System.currentTimeMillis()+"");
21 | paraMap.put("total_amount","0.01");
22 | paraMap.put("subject","测试下单");
23 | paraMap.put("product_code","QUICK_WAP_PAY");
24 | alipayTrade.TradeWapPayRequest(paraMap);
25 | }
26 | @Test
27 | public void testRefund() throws AlipayApiException {
28 | AlipayTrade alipayTrade = new AlipayTrade();
29 | Map paraMap = new HashMap<>();
30 | paraMap.put("trade_no","2016103121001004620234152469");
31 | paraMap.put("refund_amount","0.01");
32 | paraMap.put("refund_reason","测试退款");
33 | paraMap.put("out_request_no","HZ01RF001");
34 | paraMap.put("operator_id","OP001");
35 | paraMap.put("store_id","NJ_S_001");
36 | paraMap.put("terminal_id","NJ_T_001");
37 | alipayTrade.tradeRefundRequest(paraMap);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Pay-Demo/src/test/java/cn/mrdear/pay/util/SignUtilTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.util;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import static cn.mrdear.pay.util.SignUtil.joinKeyValue;
9 |
10 | /**
11 | * @author Niu Li
12 | * @date 2016/10/29
13 | */
14 | public class SignUtilTest {
15 |
16 | @Test
17 | public void testJoinKeyValue(){
18 | Map parameterMap = new HashMap();
19 | parameterMap.put("service", "create_direct_pay_by_user");
20 | parameterMap.put("_input_charset", "utf-8");
21 | parameterMap.put("sign_type", "MD5");
22 | parameterMap.put("out_trade_no", System.currentTimeMillis());
23 | parameterMap.put("payment_type", "1");
24 | parameterMap.put("paymethod", "bankPay");
25 | parameterMap.put("extend_param", "isv^1860648a1");
26 | parameterMap.put("extra_common_param", "shopxx");
27 | System.out.println("测试joinKeyValue,连接Map键值对");
28 | System.out.println(joinKeyValue(parameterMap,"?",null,"&",true));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Pay-Demo/src/test/java/cn/mrdear/pay/util/XMLUtilTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.util;
2 |
3 | import org.junit.Test;
4 |
5 | import java.io.ByteArrayOutputStream;
6 |
7 | import javax.xml.bind.annotation.XmlRootElement;
8 |
9 | import static cn.mrdear.pay.util.XmlUtil.beanToXml;
10 |
11 | /**
12 | * @author Niu Li
13 | * @date 2016/10/29
14 | */
15 | public class XMLUtilTest {
16 |
17 | @Test
18 | public void testJava2XML(){
19 | Xml x = new Xml();
20 | x.setName("冯");
21 | x.setAttach("丽娟");
22 | String buffer = beanToXml(new ByteArrayOutputStream(), x);
23 | System.out.println(buffer);
24 | System.out.println(buffer.substring(55));
25 | }
26 |
27 |
28 | @XmlRootElement(name = "xml")
29 | static class Xml {
30 | private String name;
31 | private String attach;
32 |
33 | public void setName(String name) {
34 | this.name = name;
35 | }
36 |
37 | public String getName() {
38 | return name;
39 | }
40 |
41 | public void setAttach(String attach) {
42 | this.attach = attach;
43 | }
44 |
45 | public String getAttach() {
46 | return attach;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Pay-Demo/src/test/java/cn/mrdear/pay/wechat/WechatTradeTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.pay.wechat;
2 |
3 |
4 | import com.alibaba.fastjson.JSON;
5 |
6 | import org.junit.Test;
7 |
8 | import cn.mrdear.pay.wechat.entity.WechatRefund;
9 | import cn.mrdear.pay.wechat.entity.WechatRefundQuery;
10 | import cn.mrdear.pay.wechat.entity.WechatUnifiedOrder;
11 |
12 | /**
13 | * @author Niu Li
14 | * @date 2016/10/29
15 | */
16 | public class WechatTradeTest {
17 |
18 | /**
19 | * 测试下单
20 | */
21 | @Test
22 | public void testunifiedOrder(){
23 | WechatUnifiedOrder request = new WechatUnifiedOrder();
24 | request.setBody("测试商品");
25 | request.setDetail("一个好商品");
26 | request.setGoods_tag("测试");
27 | request.setOut_trade_no(System.currentTimeMillis()+"");
28 | request.setFee_type("CNY");
29 | request.setTotal_fee(1000);
30 | request.setSpbill_create_ip("127.0.0.1");
31 | request.setTime_start(System.currentTimeMillis()+"");
32 | request.setLimit_pay("cera");
33 | WechatUnifiedOrder.Response response = WechatConfig.getInstance().unifiedOrder(request);
34 | System.out.println(JSON.toJSONString(response));
35 | }
36 |
37 | /**
38 | * 退款
39 | */
40 | @Test
41 | public void refund(){
42 | WechatRefund refund = new WechatRefund();
43 | refund.setTransaction_id("4006602001201610318291951971");
44 | refund.setOut_refund_no(System.currentTimeMillis()+"");
45 | refund.setTotal_fee(1858);
46 | refund.setRefund_fee(1858);
47 | refund.setOp_user_id("NIULI");
48 | refund.setRefund_account("REFUND_SOURCE_UNSETTLED_FUNDS");
49 | WechatRefund.Response response = WechatConfig.getInstance().refund(refund);
50 | System.out.println(JSON.toJSONString(response));
51 | }
52 |
53 | /**
54 | * 退款查询
55 | */
56 | @Test
57 | public void testRefundQuery(){
58 | WechatRefundQuery refundQuery = new WechatRefundQuery();
59 | refundQuery.setTransaction_id("4007522001201610308199783330");
60 | WechatRefundQuery.Response response = WechatConfig.getInstance().refundQuery(refundQuery);
61 | System.out.println(JSON.toJSONString(response));
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Pay-Demo/src/test/resources/acp_sdk.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | acpsdk.frontTransUrl=https://gateway.95516.com/gateway/api/frontTransReq.do
5 |
6 | acpsdk.backTransUrl=https://gateway.95516.com/gateway/api/backTransReq.do
7 |
8 | acpsdk.singleQueryUrl=https://gateway.95516.com/gateway/api/queryTrans.do
9 |
10 | acpsdk.batchTransUrl=https://gateway.95516.com/gateway/api/batchTrans.do
11 |
12 | acpsdk.fileTransUrl=https://filedownload.95516.com/
13 |
14 | acpsdk.signCert.pwd=123456
15 |
16 | #linux
17 | #acpsdk.signCert.path=/home/web_as/certs/mypfx.pfx
18 | #
19 | #acpsdk.signCert.type=PKCS12
20 | #
21 | #acpsdk.encryptCert.path=/home/web_as/certs/RSA2048_PROD_index_22.cer
22 | #
23 | #acpsdk.validateCert.dir=/home/web_as/certs/
24 | #
25 | #acpsdk.signCert.dir=/home/web_as/certs/
26 | #
27 | #log.back.rootPath=/home/web_as/logs
28 |
29 |
30 | #inux-test
31 | acpsdk.signCert.path=D:/certs/mypfx.pfx
32 |
33 | acpsdk.signCert.type=PKCS12
34 |
35 | acpsdk.encryptCert.path=D:/certs/RSA2048_PROD_index_22.cer
36 |
37 | acpsdk.validateCert.dir=D:/certs
38 |
39 | acpsdk.signCert.dir=D:/certs
40 |
41 | log.back.rootPath=D:/certs
42 |
43 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | ### 2017.9.27
2 | 随着开发经验的增加,现在觉得这种Demo对于学习一个框架起不到太大的作用,顶多是个参考,并且由于使用经验的增加,对于之前一些错误的用法很难得到纠正,如果想要快速入门的话官方+造轮子才是最佳选择,类似豆瓣有许多开放的API,都可以用来练手,最后该项目不再更新,这点经验希望能帮助你.
3 |
4 |
5 | #该仓库主要记录学习javaWEB中一些Demo
6 |
7 | 1.SSM-Demo
8 | ----------
9 | 使用maven整合的Spring,SpringMVC,Mybatis的案例,数据库使用mysql,数据源为druid,可以直接拿过来使用,进行开发.
10 |
11 |
12 | ----------
13 |
14 | 2.Jersey-Demo
15 | --------------
16 | 该Demo是做微信设备功能开发时学习整合的,Demo里面写了Jersey常用配置,以及和Spring的整合,还有微信服务器的验证入口,对于微信设备开发可以直接使用,随着不断的学习会继续更新该项目
17 |
18 |
19 | ----------
20 |
21 | 3.Spring-Boot-Demo
22 | --------------
23 | 该Demo是做学习Spring-Boot时整合环境,整合了thymeleaf,Mybatis,Druid,ehcache可以拉下来直接进行二次开发,如果是WebService服务的话,去掉thymeleaf即可.
24 |
25 | 4.Maven-Demo
26 | --------------
27 | 该demo针对具体项目所整合.主要设计mybatis多模块使用,spring多模块使用,要点就是无论什么模块,只要配置文件加载位置正确配置,就不会出问题.
28 |
29 | 5.HtmlUnit-Demo
30 | --------------
31 | 使用htmlUnit模拟浏览器请求,抓取Shadowsocks的一些免费账户使用,在win下配合bat脚本启动,很是方便.详情可以看项目的Main方法使用说明.
32 |
33 |
34 | 6.Pay-Demo
35 | --------------
36 | 对接银联无跳转支付,支付宝wap支付,微信支付,项目结构清晰,注释全面,可以很好的帮你理清对接支付的顺序,测试Demo配置好Config后都可以直接运行,希望对你有帮助.参考博客地址:http://blog.csdn.net/u012706811/article/details/52988782
37 |
38 | 7.JPA-Demo
39 | --------------
40 | SpringDataJPA+QueryDSL使用,需要配合博客博文http://www.jianshu.com/p/e3812fc23f83 ,两者配合很好地解决了单表动态查询,多表动态查询.
41 |
42 | 8.Util-Demo
43 | --------------
44 | 开发中常用工具类的写法,比如PropertiesUtil,XmlUtil,HttpUtil等,该Demo希望大家能不断扩充.
45 |
46 | 9.gRPC-Demo
47 | --------------
48 | 参考官方案例的gRPC的Demo,里面有Hello World和 RouteGuide案例,适合入门.相关博文参考 http://www.jianshu.com/nb/9491747
49 |
50 | 10.Excel-Demo
51 | --------------
52 | 使用Apache-poi封装的一个通用表单导出模块和解析模块,可以很容易的迁移到项目中,配合Jackxml使用更佳
53 |
54 | 11.Spring-Data-Redis
55 | --------------
56 | SpringDataRedis学习的一个Demo,内容不多,配合博文:[redis学习记录(四)-SpringDataRedis分析](http://mrdear.cn/2017/03/29/linux/redis%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95(%E5%9B%9B)-SpringDataRedis%E5%88%86%E6%9E%90/)可以很好的入手
57 |
58 | 12.Spring-Cloud-Demo
59 | --------------
60 | 学习Spring Cloud的一个Demo,其中对于Eureka,Ribbon,Feign等都有相应的Demo,相应博文会更新在[我的博客](mrdear.cn)上,希望对你有帮助
61 |
62 | 13.Dubbo-Demo
63 | --------------
64 | 增加Dubbo-Demo,一个基本的RPC调用Demo
65 |
66 | 14.Motan-Demo
67 | --------------
68 | 增加Motan-Demo,一个基本的RPC调用Demo
69 |
70 | 15.Spring-Security-Demo
71 | --------------
72 | 增加Spring Security Demo,项目中使用了JWT Token验证机制,该项目可以很好的了解整个流程的作用,需要配合我博客中Spring Security相关博文食用.
73 |
74 | 16.待添加
75 | --------------
76 |
--------------------------------------------------------------------------------
/SSM-Demo/doc/readme.md:
--------------------------------------------------------------------------------
1 |
2 | SSM项目基本整合,对于IDEA可以直接拉取下来使用.很方便
3 |
4 | 基本使用工具,下次再介绍
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/controller/BookController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.controller;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.RestController;
5 |
6 | import java.util.List;
7 |
8 | import javax.annotation.Resource;
9 |
10 | import cn.mrdear.entity.Book;
11 | import cn.mrdear.service.BookService;
12 |
13 | /**
14 | * @author Niu Li
15 | * @since 2016/9/22
16 | */
17 | @RestController
18 | public class BookController {
19 |
20 | @Resource
21 | private BookService bookService;
22 |
23 | @GetMapping("/books")
24 | public List books(){
25 | return bookService.findAll();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/controller/ErrorController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 |
6 | /**
7 | * @author Niu Li
8 | * @since 2017/4/19
9 | */
10 | @Controller
11 | public class ErrorController {
12 |
13 | @GetMapping("/error")
14 | public String error(){
15 | return "error";
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/entity/Book.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.*;
6 |
7 | @Table(name = "book")
8 | public class Book implements Serializable{
9 |
10 | private static final long serialVersionUID = 4189250872871101725L;
11 | /**
12 | * 图书ID
13 | */
14 | @Id
15 | @Column(name = "book_id")
16 | @GeneratedValue(strategy = GenerationType.IDENTITY)
17 | private Long bookId;
18 |
19 | /**
20 | * 图书名称
21 | */
22 | private String name;
23 |
24 | /**
25 | * 馆藏数量
26 | */
27 | private Integer number;
28 |
29 | /**
30 | * 获取图书ID
31 | *
32 | * @return book_id - 图书ID
33 | */
34 | public Long getBookId() {
35 | return bookId;
36 | }
37 |
38 | /**
39 | * 设置图书ID
40 | *
41 | * @param bookId 图书ID
42 | */
43 | public void setBookId(Long bookId) {
44 | this.bookId = bookId;
45 | }
46 |
47 | /**
48 | * 获取图书名称
49 | *
50 | * @return name - 图书名称
51 | */
52 | public String getName() {
53 | return name;
54 | }
55 |
56 | /**
57 | * 设置图书名称
58 | *
59 | * @param name 图书名称
60 | */
61 | public void setName(String name) {
62 | this.name = name;
63 | }
64 |
65 | /**
66 | * 获取馆藏数量
67 | *
68 | * @return number - 馆藏数量
69 | */
70 | public Integer getNumber() {
71 | return number;
72 | }
73 |
74 | /**
75 | * 设置馆藏数量
76 | *
77 | * @param number 馆藏数量
78 | */
79 | public void setNumber(Integer number) {
80 | this.number = number;
81 | }
82 | }
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/mapper/BookMapper.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.mapper;
2 |
3 | import cn.mrdear.entity.Book;
4 | import tk.mybatis.mapper.common.Mapper;
5 |
6 | public interface BookMapper extends Mapper {
7 |
8 | }
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/service/BookService.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.service;
2 |
3 | import org.springframework.cache.annotation.Cacheable;
4 |
5 | import java.util.List;
6 |
7 | import cn.mrdear.entity.Book;
8 |
9 | /**
10 | * @author Niu Li
11 | * @date 2016/9/23
12 | */
13 | public interface BookService {
14 | /**
15 | * 查询所有的books
16 | * @return 结果集
17 | */
18 | List findAll();
19 | }
20 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/java/cn/mrdear/service/impl/BookServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.service.impl;
2 |
3 | import org.springframework.cache.annotation.Cacheable;
4 | import org.springframework.stereotype.Service;
5 |
6 | import java.util.List;
7 |
8 | import javax.annotation.Resource;
9 |
10 | import cn.mrdear.entity.Book;
11 | import cn.mrdear.mapper.BookMapper;
12 | import cn.mrdear.service.BookService;
13 |
14 | /**
15 | * @author Niu Li
16 | * @since 2017/1/23
17 | */
18 | @Service
19 | public class BookServiceImpl implements BookService {
20 |
21 | @Resource
22 | private BookMapper bookMapper;
23 |
24 | @Override
25 | @Cacheable(cacheNames = "bookcache")
26 | public List findAll() {
27 | List books = bookMapper.selectAll();
28 | System.out.println("测试缓存,如果缓存开启,多次请求则该方法会执行一次");
29 | return books;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/ModelGenerator.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/db.properties:
--------------------------------------------------------------------------------
1 | jdbc.driver=com.mysql.jdbc.Driver
2 | jdbc.url=jdbc:mysql://115.159.185.14:3306/ssm?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
3 | jdbc.username=root
4 | jdbc.password=7946521
5 |
6 | filters:stat
7 |
8 | maxActive:20
9 | initialSize:1
10 | maxWait:60000
11 | minIdle:10
12 |
13 | timeBetweenEvictionRunsMillis:60000
14 | minEvictableIdleTimeMillis:300000
15 |
16 | testWhileIdle:true
17 | testOnBorrow:false
18 | testOnReturn:false
19 |
20 | maxOpenPreparedStatements:20
21 | removeAbandoned:true
22 | removeAbandonedTimeout:1800
23 | logAbandoned:true
24 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/db.sql:
--------------------------------------------------------------------------------
1 | /*
2 | SQLyog Ultimate v12.08 (64 bit)
3 | MySQL - 5.6.24 : Database - ssm
4 | *********************************************************************
5 | */
6 |
7 |
8 | /*!40101 SET NAMES utf8 */;
9 |
10 | CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssm` /*!40100 DEFAULT CHARACTER SET utf8 */;
11 |
12 | USE `ssm`;
13 |
14 |
15 |
16 | /*Table structure for table `book` */
17 |
18 | CREATE TABLE `book` (
19 | `book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图书ID',
20 | `name` varchar(100) NOT NULL COMMENT '图书名称',
21 | `number` int(11) NOT NULL COMMENT '馆藏数量',
22 | PRIMARY KEY (`book_id`)
23 | ) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8 COMMENT='图书表';
24 |
25 | /*Data for the table `book` */
26 |
27 | LOCK TABLES `book` WRITE;
28 |
29 | insert into `book`(`book_id`,`name`,`number`) values (1000,'Java程序设计',10),(1001,'数据结构',10),(1002,'设计模式',10),(1003,'编译原理',10);
30 |
31 | UNLOCK TABLES;
32 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/ehcache.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
14 |
15 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | %d{HH:mm:ss} [%t] %logger{5} [%line] %p - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/mybatis/mapper/BookMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
13 |
16 | book_id, name, number
17 |
18 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/resources/mybatis/sqlmapconfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/webapp/WEB-INF/view/error.jsp:
--------------------------------------------------------------------------------
1 | <%--
2 | Created by IntelliJ IDEA.
3 | User: niuli
4 | Date: 2017/4/19
5 | Time: 09:45
6 | To change this template use File | Settings | File Templates.
7 | --%>
8 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 |
10 |
11 | Title
12 |
13 |
14 | Error 页面
15 |
16 |
17 |
--------------------------------------------------------------------------------
/SSM-Demo/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 | <%--
2 | Created by IntelliJ IDEA.
3 | User: NL
4 | Date: 2017/1/23
5 | Time: 9:09
6 | To change this template use File | Settings | File Templates.
7 | --%>
8 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 |
10 |
11 |
12 |
13 |
14 | Hello World!
15 | 请访问/books测试
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/Application.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | /**
7 | * 默认启动类
8 | */
9 | @SpringBootApplication
10 | public class Application
11 | {
12 | public static void main( String[] args )
13 | {
14 | SpringApplication.run(Application.class, args);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/conf/FilterConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.conf;
2 |
3 | import net.sf.ehcache.constructs.web.filter.GzipFilter;
4 | import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;
5 |
6 | import org.springframework.boot.web.servlet.FilterRegistrationBean;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 |
10 | import java.util.Arrays;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | /**
15 | * 定义一些Filter使用
16 | * @author Niu Li
17 | * @date 2016/8/13
18 | */
19 | @Configuration
20 | public class FilterConfig {
21 | /**
22 | * 配置ehcache的Gzip压缩
23 | * @return
24 | */
25 | @Bean
26 | public FilterRegistrationBean gzipFilter(){
27 | FilterRegistrationBean gzipFilter = new FilterRegistrationBean(new GzipFilter());
28 | String[] arrs = {"*.js","*.css","*.json","*.html"};
29 | gzipFilter.setUrlPatterns(Arrays.asList(arrs));
30 | return gzipFilter;
31 | }
32 | /**
33 | * 配置页面缓存,页面缓存会自动开启GZIP压缩
34 | */
35 | @Bean
36 | public FilterRegistrationBean helloFilter(){
37 | FilterRegistrationBean helloFilter = new FilterRegistrationBean(new SimplePageCachingFilter());
38 | Map maps = new HashMap<>();
39 | //设置参数
40 | maps.put("cacheName","hello");
41 | helloFilter.setInitParameters(maps);
42 | //设置路径
43 | String[] arrs = {"/hello"};
44 | helloFilter.setUrlPatterns(Arrays.asList(arrs));
45 | return helloFilter;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/conf/ServletConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.conf;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 |
5 | /**
6 | * 定义一些servlet使用
7 | * @author Niu Li
8 | * @date 2016/8/13
9 | */
10 | @Configuration
11 | public class ServletConfig {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/conf/WEBMessageConvert.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.conf;
2 |
3 | import com.alibaba.fastjson.serializer.SerializerFeature;
4 | import com.alibaba.fastjson.support.config.FastJsonConfig;
5 | import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
6 | import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 | import org.springframework.http.converter.HttpMessageConverter;
10 |
11 | /**
12 | * 使用fastjson作为消息转换器
13 | * @author Niu Li
14 | * @date 2016/8/9
15 | */
16 | @Configuration
17 | public class WEBMessageConvert {
18 | /**
19 | * 使用bean注入,才能使其有效果,验证的话就在Entity字段中使用fastjson的
20 | * 注解@JSONField(serialize = false),转换出来的信息不含该字段,则成功
21 | * @return
22 | */
23 | @Bean
24 | public HttpMessageConverters customConverters() {
25 | FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
26 | FastJsonConfig fastJsonConfig = new FastJsonConfig();
27 | fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
28 | fastConverter.setFastJsonConfig(fastJsonConfig);
29 | return new HttpMessageConverters((HttpMessageConverter>) fastConverter);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/controller/HelloController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.controller;
2 |
3 | import cn.mrdear.entity.User;
4 | import cn.mrdear.mapper.UserMapper;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.stereotype.Controller;
8 | import org.springframework.ui.Model;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.ResponseBody;
12 |
13 | import javax.annotation.Resource;
14 |
15 | /**
16 | * @author Niu Li
17 | * @date 2016/8/9
18 | */
19 | @Controller
20 | public class HelloController {
21 |
22 | private Logger logger = LoggerFactory.getLogger(HelloController.class);
23 | @Resource
24 | private UserMapper userMapper;
25 | /**
26 | * 测试hello
27 | * @return
28 | */
29 | @RequestMapping(value = "/hello",method = RequestMethod.GET)
30 | public String hello(Model model) {
31 | model.addAttribute("name", "Dear");
32 | return "hello";
33 | }
34 |
35 | @RequestMapping(value = "/users",method = RequestMethod.GET)
36 | public @ResponseBody User testUserDao(){
37 | User user = userMapper.findById(1);
38 | return user;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * 用户实体类
7 | * @author Niu Li
8 | * @date 2016/8/12
9 | */
10 | public class User implements Serializable{
11 | private int id;
12 | private String username;
13 | private String password;
14 |
15 | public int getId() {
16 | return id;
17 | }
18 |
19 | public void setId(int id) {
20 | this.id = id;
21 | }
22 |
23 | public String getUsername() {
24 | return username;
25 | }
26 |
27 | public void setUsername(String username) {
28 | this.username = username;
29 | }
30 |
31 | public String getPassword() {
32 | return password;
33 | }
34 |
35 | public void setPassword(String password) {
36 | this.password = password;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/exception/PageException.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.exception;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.web.bind.annotation.ControllerAdvice;
6 | import org.springframework.web.servlet.HandlerExceptionResolver;
7 | import org.springframework.web.servlet.ModelAndView;
8 |
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 |
12 | /**
13 | * 自定义异常类
14 | * @author Niu Li
15 | * @date 2016/8/10
16 | */
17 | @ControllerAdvice//配置文件没了,所以使用注解让spring管理
18 | public class PageException implements HandlerExceptionResolver {
19 |
20 | private Logger logger = LoggerFactory.getLogger(PageException.class);
21 |
22 | @Override
23 | public ModelAndView resolveException(HttpServletRequest Request, HttpServletResponse Response, Object o, Exception ex) {
24 | logger.warn("==============异常开始=============");
25 | logger.error("异常:",ex);
26 | logger.warn("==============异常结束=============");
27 | ModelAndView mv = new ModelAndView();
28 | mv.addObject("error", ex.getMessage());
29 | mv.setViewName("error");
30 | return mv;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/java/cn/mrdear/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.mapper;
2 |
3 | import cn.mrdear.entity.User;
4 | import org.apache.ibatis.annotations.Mapper;
5 |
6 | /**
7 | * UserMapper.xml代理
8 | * @author Niu Li
9 | * @date 2016/8/13
10 | */
11 | @Mapper
12 | public interface UserMapper {
13 | /**
14 | * 根据id查询用户
15 | * @param id
16 | * @return
17 | */
18 | User findById(int id);
19 | }
20 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #logger start
2 | logging.path = logs/loging.log
3 | logging.level.org.springframework.web = info
4 | logging.level.cn.mrdear = debug
5 | logging.level.net.sf.ehcache = debug
6 | logging.level.org.mybatis.caches = debug
7 | logging.level.cn.mrdear.mapper = trace
8 | #logger end
9 |
10 | #thymeleaf start
11 | spring.thymeleaf.mode=HTML5
12 | spring.thymeleaf.encoding=UTF-8
13 | spring.thymeleaf.contents-type=text/html
14 | #����ʱ�رջ���,��Ȼû������ʵʱҳ��
15 | spring.thymeleaf.cache=false
16 | #thymeleaf end
17 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/resources/banner.txt:
--------------------------------------------------------------------------------
1 | 启动自定义banner,直接放入classpath下banner.txt即可
2 | 如果想关闭,则可以在配置中写入spring.main.banner-mode=off,或者在启动代码中设置均可
3 | --------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/resources/ehcache.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/resources/mapper/UserMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
10 |
--------------------------------------------------------------------------------
/Spring-Boot-Demo/src/main/resources/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | hello
5 |
6 |
7 |
8 |
9 |
10 |
11 | 3333
12 | 绝对路径
13 | 相对路径
14 | Content路径,默认访问static下的css文件夹
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Discovery-Eureka/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | cn.mrdear.springcloud
7 | springcloud-parent
8 | 1.0.0
9 |
10 | 4.0.0
11 | service-discovery-eureka
12 |
13 |
14 |
15 | org.springframework.cloud
16 | spring-cloud-starter-eureka-server
17 |
18 |
19 |
20 |
21 |
22 |
23 | org.apache.maven.plugins
24 | maven-compiler-plugin
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Discovery-Eureka/src/main/java/cn/mrdear/EurekaApplication.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear;
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 | /**
8 | * @author Niu Li
9 | * @since 2017/5/25
10 | */
11 | @EnableEurekaServer//启动服务注册中心
12 | @SpringBootApplication
13 | public class EurekaApplication {
14 | public static void main(String[] args) {
15 | SpringApplication.run(EurekaApplication.class,args);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Discovery-Eureka/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 |
2 | server:
3 | port: 8761
4 |
5 | spring:
6 | application:
7 | name: eureka-server
8 |
9 | eureka:
10 | instance:
11 | hostname: localhost
12 | prefer-ip-address: true
13 | client:
14 | register-with-eureka: false
15 | fetch-registry: false
16 | service-url:
17 | defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springcloud-parent
7 | cn.mrdear.springcloud
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | cn.mrdear.springcloud
13 | Service-Product-Consumer-Feign-Hystrix
14 |
15 |
16 |
17 | org.springframework.cloud
18 | spring-cloud-starter-feign
19 |
20 |
21 | org.springframework.cloud
22 | spring-cloud-starter-eureka
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/java/UserConsumeFeignHystrixApplication.java:
--------------------------------------------------------------------------------
1 | import org.springframework.boot.SpringApplication;
2 | import org.springframework.boot.autoconfigure.SpringBootApplication;
3 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
4 | import org.springframework.cloud.netflix.feign.EnableFeignClients;
5 |
6 |
7 | /**
8 | * @author Niu Li
9 | * @since 2017/6/3
10 | */
11 | @SpringBootApplication(scanBasePackages = "cn.medear.springcloud")
12 | @EnableDiscoveryClient
13 | @EnableFeignClients(basePackages = "cn.medear.springcloud.restclient")
14 | public class UserConsumeFeignHystrixApplication {
15 |
16 | public static void main(String[] args) {
17 | SpringApplication.run(UserConsumeFeignHystrixApplication.class, args);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/java/cn/medear/springcloud/controller/ConsumeUserController.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.controller;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 |
6 | import org.springframework.web.bind.annotation.GetMapping;
7 | import org.springframework.web.bind.annotation.PathVariable;
8 | import org.springframework.web.bind.annotation.RestController;
9 |
10 | import javax.annotation.Resource;
11 |
12 | import cn.medear.springcloud.entity.User;
13 | import cn.medear.springcloud.restclient.UserClient;
14 | import lombok.extern.slf4j.Slf4j;
15 |
16 | /**
17 | * 用于消费UserService的类
18 | * @author Niu Li
19 | * @since 2017/6/3
20 | */
21 | @RestController
22 | @Slf4j
23 | public class ConsumeUserController {
24 |
25 | @Resource
26 | private UserClient userClient;
27 |
28 | private static final ObjectMapper objectMapper = new ObjectMapper();
29 |
30 | @GetMapping("/{id}")
31 | public String findUserById(@PathVariable Long id) {
32 | User user = userClient.findById(id);
33 | String valueAsString = null;
34 | try {
35 | valueAsString = objectMapper.writeValueAsString(user);
36 | } catch (JsonProcessingException e) {
37 | log.error("parse json error. {}",e);
38 | }
39 | return valueAsString;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/java/cn/medear/springcloud/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 | import lombok.ToString;
8 |
9 | /**
10 | * @author Niu Li
11 | * @since 2017/6/3
12 | */
13 | @Data
14 | @NoArgsConstructor
15 | @ToString
16 | public class User implements Serializable{
17 |
18 | private static final long serialVersionUID = -2885884654600114856L;
19 |
20 | private Long id;
21 |
22 | private String username;
23 |
24 | private String password;
25 | }
26 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/java/cn/medear/springcloud/restclient/UserClient.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.restclient;
2 |
3 | import org.springframework.cloud.netflix.feign.FeignClient;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestMethod;
7 |
8 | import cn.medear.springcloud.entity.User;
9 | import cn.medear.springcloud.restclient.failback.UserClientFailBack;
10 |
11 | /**
12 | * @author Niu Li
13 | * @since 2017/6/4
14 | */
15 | @FeignClient(name = "service-user-provider",fallbackFactory = UserClientFailBack.class)
16 | public interface UserClient {
17 |
18 | @RequestMapping(value = "/{id}",method = RequestMethod.GET)
19 | User findById(@PathVariable("id") Long id);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/java/cn/medear/springcloud/restclient/failback/UserClientFailBack.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.restclient.failback;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | import cn.medear.springcloud.entity.User;
6 | import cn.medear.springcloud.restclient.UserClient;
7 | import feign.hystrix.FallbackFactory;
8 | import lombok.extern.slf4j.Slf4j;
9 |
10 | /**
11 | * 用户调用断路器
12 | * @author Niu Li
13 | * @since 2017/6/4
14 | */
15 | @Slf4j
16 | @Component
17 | public class UserClientFailBack implements FallbackFactory{
18 |
19 | private static UserClient userClient = new UserClientFailBackWithInfo();
20 |
21 | /**
22 | * 错误返回内容配置
23 | */
24 | @Override
25 | public UserClient create(Throwable throwable) {
26 | log.error("UserClient hystrix open,error is {}",throwable.getMessage());
27 | return userClient;
28 | }
29 |
30 |
31 | private static class UserClientFailBackWithInfo implements UserClient{
32 | @Override
33 | public User findById(Long id) {
34 | User user = new User();
35 | user.setId(0L);
36 | user.setUsername("失败用户");
37 | return user;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign-Hystrix/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8086
3 |
4 | spring:
5 | application:
6 | name: service-product-consumer-fegin-hystrix
7 |
8 | eureka:
9 | client:
10 | service-url:
11 | default-zone: http://localhost:8761/eureka/
12 | instance:
13 | prefer-ip-address: true
14 |
15 | #开启断路器
16 | feign:
17 | hystrix:
18 | enabled: true
19 |
20 | # 负载均衡配置为随机,不配置默认轮询
21 | service-user-provider:
22 | ribbon:
23 | NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
24 |
25 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springcloud-parent
7 | cn.mrdear.springcloud
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | cn.mrdear.springcloud
13 | Service-Product-Consumer-Feign
14 |
15 |
16 |
17 | org.springframework.cloud
18 | spring-cloud-starter-feign
19 |
20 |
21 | io.github.openfeign
22 | feign-httpclient
23 | 9.5.0
24 |
25 |
26 | org.springframework.cloud
27 | spring-cloud-starter-eureka
28 |
29 |
30 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/src/main/java/UserConsumeFeignApplication.java:
--------------------------------------------------------------------------------
1 | import org.apache.http.client.HttpClient;
2 | import org.apache.http.client.config.RequestConfig;
3 | import org.apache.http.config.RegistryBuilder;
4 | import org.apache.http.conn.socket.ConnectionSocketFactory;
5 | import org.apache.http.conn.socket.PlainConnectionSocketFactory;
6 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
7 | import org.apache.http.impl.client.CloseableHttpClient;
8 | import org.apache.http.impl.client.HttpClientBuilder;
9 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
10 | import org.springframework.boot.SpringApplication;
11 | import org.springframework.boot.autoconfigure.SpringBootApplication;
12 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
13 | import org.springframework.cloud.netflix.feign.EnableFeignClients;
14 | import org.springframework.context.annotation.Bean;
15 |
16 |
17 | /**
18 | * @author Niu Li
19 | * @since 2017/6/3
20 | */
21 | @SpringBootApplication(scanBasePackages = "cn.medear.springcloud.controller")
22 | @EnableDiscoveryClient
23 | @EnableFeignClients(basePackages = "cn.medear.springcloud.restclient")
24 | public class UserConsumeFeignApplication {
25 |
26 | public static void main(String[] args) {
27 | SpringApplication.run(UserConsumeFeignApplication.class, args);
28 | }
29 |
30 | /**
31 | * 自定义feign的Httpclient,其注入在HttpClientFeignLoadBalancedConfiguration中
32 | * @return
33 | */
34 | @Bean
35 | public HttpClient feignHttpClient() {
36 | PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER =
37 | new PoolingHttpClientConnectionManager(RegistryBuilder.create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
38 | HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);
39 | HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);
40 | RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();
41 | CloseableHttpClient httpClient = HttpClientBuilder.create()
42 | .setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER)
43 | .setDefaultRequestConfig(requestConfig).build();
44 | return httpClient;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/src/main/java/cn/medear/springcloud/controller/ConsumeUserController.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.controller;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 |
6 | import org.springframework.web.bind.annotation.GetMapping;
7 | import org.springframework.web.bind.annotation.PathVariable;
8 | import org.springframework.web.bind.annotation.RestController;
9 |
10 | import javax.annotation.Resource;
11 |
12 | import cn.medear.springcloud.entity.User;
13 | import cn.medear.springcloud.restclient.UserClient;
14 | import lombok.extern.slf4j.Slf4j;
15 |
16 | /**
17 | * 用于消费UserService的类
18 | * @author Niu Li
19 | * @since 2017/6/3
20 | */
21 | @RestController
22 | @Slf4j
23 | public class ConsumeUserController {
24 |
25 | @Resource
26 | private UserClient userClient;
27 |
28 | private static final ObjectMapper objectMapper = new ObjectMapper();
29 |
30 | @GetMapping("/{id}")
31 | public String findUserById(@PathVariable Long id) {
32 | User user = userClient.findById(id);
33 | String valueAsString = null;
34 | try {
35 | valueAsString = objectMapper.writeValueAsString(user);
36 | } catch (JsonProcessingException e) {
37 | log.error("parse json error. {}",e);
38 | }
39 | return valueAsString;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/src/main/java/cn/medear/springcloud/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 | import lombok.ToString;
8 |
9 | /**
10 | * @author Niu Li
11 | * @since 2017/6/3
12 | */
13 | @Data
14 | @NoArgsConstructor
15 | @ToString
16 | public class User implements Serializable{
17 |
18 | private static final long serialVersionUID = -2885884654600114856L;
19 |
20 | private Long id;
21 |
22 | private String username;
23 |
24 | private String password;
25 | }
26 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/src/main/java/cn/medear/springcloud/restclient/UserClient.java:
--------------------------------------------------------------------------------
1 | package cn.medear.springcloud.restclient;
2 |
3 | import org.springframework.cloud.netflix.feign.FeignClient;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestMethod;
7 |
8 | import cn.medear.springcloud.entity.User;
9 |
10 | /**
11 | * @author Niu Li
12 | * @since 2017/6/4
13 | */
14 | @FeignClient("service-user-provider")
15 | public interface UserClient {
16 |
17 | @RequestMapping(value = "/{id}",method = RequestMethod.GET)
18 | User findById(@PathVariable("id") Long id);
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Feign/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8085
3 |
4 | spring:
5 | application:
6 | name: service-product-consumer-fegin
7 |
8 | eureka:
9 | client:
10 | service-url:
11 | default-zone: http://localhost:8761/eureka/
12 | instance:
13 | prefer-ip-address: true
14 |
15 | feign:
16 | httpclient:
17 | enabled: true
18 |
19 | # 负载均衡配置为随机,不配置默认轮询
20 | service-user-provider:
21 | ribbon:
22 | NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
23 |
24 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Ribbon/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springcloud-parent
7 | cn.mrdear.springcloud
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | cn.mrdear.springcloud
13 | Service-Product-Consumer-Ribbon
14 |
15 |
16 |
17 | org.springframework.cloud
18 | spring-cloud-starter-eureka
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Ribbon/src/main/java/cn/mrdear/springcloud/UserConsumeApplication.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.springcloud;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
6 |
7 | /**
8 | * @author Niu Li
9 | * @since 2017/6/3
10 | */
11 | @SpringBootApplication
12 | @EnableDiscoveryClient
13 | public class UserConsumeApplication {
14 |
15 | public static void main(String[] args) {
16 | SpringApplication.run(UserConsumeApplication.class,args);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Ribbon/src/main/java/cn/mrdear/springcloud/config/BeanConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.springcloud.config;
2 |
3 | import org.springframework.cloud.client.loadbalancer.LoadBalanced;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.web.client.RestTemplate;
7 |
8 | /**
9 | * @author Niu Li
10 | * @since 2017/6/3
11 | */
12 | @Configuration
13 | //@RibbonClient(name = "user-resporitory",configuration = MyConfig.class)
14 | //可以指定针对某服务器采取指定的配置负载均衡算法,配置文件中配置更加方便
15 | public class BeanConfig {
16 |
17 | @Bean
18 | @LoadBalanced //开启客户端负载均衡,自动配置类在LoadBalancerAutoConfiguration中
19 | public RestTemplate restTemplate(){
20 | return new RestTemplate();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Ribbon/src/main/java/cn/mrdear/springcloud/controller/ConsumeUserController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.springcloud.controller;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.PathVariable;
5 | import org.springframework.web.bind.annotation.RestController;
6 | import org.springframework.web.client.RestTemplate;
7 |
8 | import javax.annotation.Resource;
9 |
10 | /**
11 | * 用于消费UserService的类
12 | * @author Niu Li
13 | * @since 2017/6/3
14 | */
15 | @RestController
16 | public class ConsumeUserController {
17 |
18 | @Resource
19 | private RestTemplate restTemplate;
20 |
21 | @GetMapping("/{id}")
22 | public String findUserById(@PathVariable Long id) {
23 | return restTemplate.getForObject("http://service-user-provider/"+id,String.class);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-Product-Consumer-Ribbon/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8082
3 |
4 | spring:
5 | application:
6 | name: service-product-consumer-ribbon
7 |
8 | eureka:
9 | client:
10 | service-url:
11 | default-zone: http://localhost:8761/eureka/
12 | instance:
13 | prefer-ip-address: true
14 |
15 | # 负载均衡配置为随机,不配置默认轮询
16 | service-user-provider:
17 | ribbon:
18 | NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
19 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springcloud-parent
7 | cn.mrdear.springcloud
8 | 1.0.0
9 |
10 | 4.0.0
11 |
12 | cn.mrdear.springcloud
13 | Service-User-Provider
14 |
15 |
16 |
17 |
18 | com.h2database
19 | h2
20 | runtime
21 |
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-web
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-data-jpa
31 |
32 |
33 | org.springframework.cloud
34 | spring-cloud-starter-eureka
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.apache.maven.plugins
42 | maven-compiler-plugin
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/java/cn/mrdear/UserApplication.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
6 |
7 | /**
8 | * @author Niu Li
9 | * @since 2017/5/25
10 | */
11 | @EnableDiscoveryClient
12 | @SpringBootApplication
13 | public class UserApplication {
14 |
15 | public static void main(String[] args) {
16 | SpringApplication.run(UserApplication.class,args);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/java/cn/mrdear/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.controller;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Value;
5 | import org.springframework.cloud.client.ServiceInstance;
6 | import org.springframework.cloud.client.discovery.DiscoveryClient;
7 | import org.springframework.web.bind.annotation.GetMapping;
8 | import org.springframework.web.bind.annotation.PathVariable;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import java.util.List;
14 |
15 | import javax.annotation.Resource;
16 |
17 | import cn.mrdear.entity.User;
18 | import cn.mrdear.resporitory.UserResporitory;
19 |
20 | /**
21 | * @author Niu Li
22 | * @since 2017/5/25
23 | */
24 | @RestController
25 | public class UserController {
26 |
27 | @Value("${spring.application.name}")
28 | private String serverName;
29 |
30 | @Resource
31 | private UserResporitory userResporitory;
32 |
33 | @Resource
34 | private DiscoveryClient discoveryClient;
35 |
36 | @RequestMapping(value = "/add" ,method = RequestMethod.GET)
37 | public User add(String username,String password) {
38 | User user = new User();
39 | user.setUsername(username);
40 | user.setPassword(password);
41 | userResporitory.saveAndFlush(user);
42 | return user;
43 | }
44 |
45 | @GetMapping("/{id}")
46 | public User find(@PathVariable Long id) {
47 | return userResporitory.findOne(id);
48 | }
49 |
50 | @GetMapping("/list")
51 | public List findAll(){
52 | return userResporitory.findAll();
53 | }
54 |
55 | @GetMapping("/console")
56 | public List console(){
57 | List instances = discoveryClient.getInstances(serverName);
58 | return instances;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/java/cn/mrdear/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.Id;
8 |
9 | import lombok.Data;
10 | import lombok.NoArgsConstructor;
11 | import lombok.ToString;
12 |
13 | /**
14 | * @author Niu Li
15 | * @since 2017/6/3
16 | */
17 | @Data
18 | @NoArgsConstructor
19 | @ToString
20 | @Entity
21 | public class User implements Serializable{
22 |
23 | private static final long serialVersionUID = -2885884654600114856L;
24 |
25 | @Id
26 | @GeneratedValue
27 | private Long id;
28 |
29 | private String username;
30 |
31 | private String password;
32 | }
33 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/java/cn/mrdear/resporitory/UserResporitory.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.resporitory;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import cn.mrdear.entity.User;
7 |
8 | /**
9 | * @author Niu Li
10 | * @since 2017/6/3
11 | */
12 | @Repository
13 | public interface UserResporitory extends JpaRepository{
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8083
3 | spring:
4 | application:
5 | name: service-user-provider
6 | jpa:
7 | generate-ddl: false
8 | show-sql: true
9 | hibernate:
10 | ddl-auto: none
11 | datasource:
12 | platform: h2
13 | schema: classpath:database/schema.sql
14 | data: classpath:database/data.sql
15 | eureka:
16 | client:
17 | service-url:
18 | default-zone: http://localhost:8761/eureka/
19 | instance:
20 | prefer-ip-address: true
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/resources/database/data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO user(username,password) VALUES ('张三','111111');
2 | INSERT INTO user(username,password) VALUES ('李四','111111');
3 | INSERT INTO user(username,password) VALUES ('王二','111111');
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/src/main/resources/database/schema.sql:
--------------------------------------------------------------------------------
1 | drop table user if exists;
2 | create table user (
3 | id INT(11) AUTO_INCREMENT PRIMARY KEY ,
4 | username VARCHAR(255),
5 | password VARCHAR(255)
6 | );
--------------------------------------------------------------------------------
/Spring-Cloud-Demo/Service-User-Provider/target/classes/cn/mrdear/Application.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrdear/JavaWEB/a7b8da4e680ab0b06d057b3537e19f47d103bf54/Spring-Cloud-Demo/Service-User-Provider/target/classes/cn/mrdear/Application.class
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/Application.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | /**
7 | * @author Niu Li
8 | * @since 2017/3/28
9 | */
10 | @SpringBootApplication
11 | public class Application {
12 | public static void main( String[] args )
13 | {
14 | SpringApplication.run(Application.class, args);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/conf/SwaggerConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.conf;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.context.request.async.DeferredResult;
6 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
8 |
9 | import springfox.documentation.builders.ApiInfoBuilder;
10 | import springfox.documentation.service.ApiInfo;
11 | import springfox.documentation.service.Contact;
12 | import springfox.documentation.spi.DocumentationType;
13 | import springfox.documentation.spring.web.plugins.Docket;
14 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
15 |
16 | /**
17 | * @author Niu Li
18 | * @since 2017/3/30
19 | */
20 | @Configuration
21 | @EnableSwagger2
22 | public class SwaggerConfig extends WebMvcConfigurerAdapter {
23 |
24 | /**
25 | * 使用enableMVC注解的话,该配置必须,否则无法映射资源
26 | */
27 | @Override
28 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
29 | registry.addResourceHandler("swagger-ui.html")
30 | .addResourceLocations("classpath:/META-INF/resources/");
31 | registry.addResourceHandler("/webjars/**")
32 | .addResourceLocations("classpath:/META-INF/resources/webjars/");
33 |
34 | }
35 |
36 | @Bean
37 | public Docket createRestApi() {
38 | return new Docket(DocumentationType.SWAGGER_2)
39 | .groupName("api")
40 | .genericModelSubstitutes(DeferredResult.class)
41 | .useDefaultResponseMessages(false)
42 | .forCodeGeneration(true)
43 | .pathMapping("/")
44 | .select()
45 | .build()
46 | .apiInfo(apiInfo());
47 | }
48 |
49 | private ApiInfo apiInfo() {
50 | Contact contact = new Contact("屈定","http://mrdear.cn","niudear@foxmail.com");
51 | return new ApiInfoBuilder()
52 | .title("Spring Data Redis")
53 | .description("Spring Data Redis学习记录")
54 | .termsOfServiceUrl("http://mrdear.cn")
55 | .contact(contact)
56 | .version("1.0")
57 | .build();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.controller;
2 |
3 | import org.springframework.web.bind.annotation.PathVariable;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.RequestMethod;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import java.util.Objects;
11 |
12 | import javax.annotation.Resource;
13 |
14 | import cn.mrdear.dao.UserDao;
15 | import cn.mrdear.model.User;
16 | import cn.mrdear.util.MockUserUtil;
17 | import io.swagger.annotations.Api;
18 | import io.swagger.annotations.ApiOperation;
19 | import io.swagger.annotations.ApiResponse;
20 |
21 | /**
22 | * @author Niu Li
23 | * @since 2017/3/30
24 | */
25 | @Api(description = "提供增删改查,swagger示例",tags = "API-UserController")
26 | @RestController
27 | @RequestMapping(value = "/api/v1")
28 | public class UserController {
29 | @Resource
30 | private UserDao userDao;
31 |
32 | @ApiOperation(value = "查询全部用户",httpMethod = "GET")
33 | @ApiResponse(code = 200,message = "Success")
34 | @RequestMapping(value = "/users",method = RequestMethod.GET)
35 | public List getAllUsers(){
36 | return userDao.query();
37 | }
38 |
39 | @ApiOperation(value = "查询单个用户",notes = "根据传入id查找用户",httpMethod = "GET")
40 | @ApiResponse(code = 200,message = "Success")
41 | @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
42 | public User getUser(@PathVariable("id") Integer id){
43 | return userDao.find(id);
44 | }
45 |
46 | @ApiOperation(value = "批量插入用户",notes = "根据传入参数增加用户",httpMethod = "POST")
47 | @ApiResponse(code = 200,message = "Success")
48 | @RequestMapping(value = "/user",method = RequestMethod.POST)
49 | public List InsertUser(Integer nums){
50 | if (Objects.isNull(nums)){
51 | nums = 10;
52 | }
53 | List users = new ArrayList<>();
54 | for (Integer i = 0; i < nums; i++) {
55 | User user = MockUserUtil.mockSignle();
56 | userDao.save(user);
57 | users.add(user);
58 | }
59 | return users;
60 | }
61 |
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/model/User.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.model;
2 |
3 | /**
4 | * 测试用户
5 | * @author Niu Li
6 | * @since 2017/3/30
7 | */
8 | public class User {
9 | private Long id;
10 | private String username;
11 | private String password;
12 |
13 | public Long getId() {
14 | return id;
15 | }
16 |
17 | public void setId(Long id) {
18 | this.id = id;
19 | }
20 |
21 | public String getUsername() {
22 | return username;
23 | }
24 |
25 | public void setUsername(String username) {
26 | this.username = username;
27 | }
28 |
29 | public String getPassword() {
30 | return password;
31 | }
32 |
33 | public void setPassword(String password) {
34 | this.password = password;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/publish/Listen.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.publish;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.stereotype.Component;
6 |
7 | import java.util.concurrent.CountDownLatch;
8 |
9 | /**
10 | * 消息订阅者
11 | * @author Niu Li
12 | * @since 2017/3/29
13 | */
14 | @Component
15 | public class Listen {
16 |
17 | private static Logger logger = LoggerFactory.getLogger(Listen.class);
18 |
19 | private CountDownLatch latch = new CountDownLatch(1);
20 |
21 | public void handleMsg(String message) {
22 | logger.info("reciver msg :" + message);
23 | latch.countDown();
24 | }
25 |
26 | public CountDownLatch getLatch() {
27 | return latch;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/publish/PublishConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.publish;
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.listener.PatternTopic;
7 | import org.springframework.data.redis.listener.RedisMessageListenerContainer;
8 | import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
9 |
10 | /**
11 | * @author Niu Li
12 | * @since 2017/3/29
13 | */
14 | @Configuration
15 | public class PublishConfig {
16 | /**
17 | * 注入消息容器
18 | * @param jedisConnectionFactory jedis连接池
19 | * @param listenerAdapter 监听适配器
20 | * @return bean
21 | */
22 | @Bean
23 | public RedisMessageListenerContainer container(RedisConnectionFactory jedisConnectionFactory,
24 | MessageListenerAdapter listenerAdapter){
25 | RedisMessageListenerContainer container = new RedisMessageListenerContainer();
26 | container.setConnectionFactory(jedisConnectionFactory);
27 | //绑定监听者与信道的管理
28 | container.addMessageListener(listenerAdapter,new PatternTopic("java"));
29 | return container;
30 | }
31 |
32 | @Bean
33 | public MessageListenerAdapter adapter(Listen listen){
34 | //指定监听者和监听方法
35 | return new MessageListenerAdapter(listen,"handleMsg");
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/java/cn/mrdear/util/MockUserUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Random;
6 | import java.util.UUID;
7 |
8 | import cn.mrdear.model.User;
9 |
10 | /**
11 | * mock虚拟用户
12 | * @author Niu Li
13 | * @since 2017/3/30
14 | */
15 | public class MockUserUtil {
16 |
17 | //mock数据来源
18 | private static String[] namePrefix = {"赵","钱","孙","李","周","吴","郑","王"};
19 | private static String[] nameSuffix = {"一","二","三","四","五","六","七","八"};
20 |
21 | private static Random random = new Random();
22 |
23 | /**
24 | * mock用户
25 | * @return 用户实体
26 | */
27 | public static User mockSignle(){
28 | User user = new User();
29 | int x = random.nextInt(namePrefix.length);
30 | String userName = namePrefix[x]+nameSuffix[x];
31 | user.setId((long) x);
32 | user.setUsername(userName);
33 | user.setPassword(UUID.randomUUID().toString());
34 | return user;
35 | }
36 |
37 | /**
38 | * mock集合
39 | * @param num 集合数量
40 | * @return 集合
41 | */
42 | public static List mockList(int num){
43 | List users = new ArrayList<>();
44 | for (int i = 0; i < num; i++) {
45 | users.add(mockSignle());
46 | }
47 | return users;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Spring-Data-Redis/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #logger start
2 | logging.path = logs/loging.log
3 | logging.level.cn.mrdear = debug
4 | #logger end
5 |
6 | # spring date redis start
7 | # Redis数据库索引(默认为0)
8 | spring.redis.database=0
9 | # Redis服务器地址
10 | spring.redis.host=115.159.185.14
11 | # Redis服务器连接端口
12 | spring.redis.port=6379
13 | # Redis服务器连接密码(默认为空)
14 | spring.redis.password=
15 | # 连接池最大连接数(使用负值表示没有限制)
16 | spring.redis.pool.max-active=8
17 | # 连接池最大阻塞等待时间(使用负值表示没有限制)
18 | spring.redis.pool.max-wait=-1
19 | # 连接池中的最大空闲连接
20 | spring.redis.pool.max-idle=8
21 | # 连接池中的最小空闲连接
22 | spring.redis.pool.min-idle=0
23 | # 连接超时时间(毫秒)
24 | spring.redis.timeout=2000
25 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | cn.mrdear.security
8 | Spring-Security-Demo
9 | 1.0-SNAPSHOT
10 |
11 |
12 | org.springframework.boot
13 | spring-boot-starter-parent
14 | 1.5.4.RELEASE
15 |
16 |
17 |
18 |
19 | org.springframework.boot
20 | spring-boot-starter-security
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-web
25 |
26 |
27 |
28 | io.jsonwebtoken
29 | jjwt
30 | 0.7.0
31 |
32 |
33 | org.projectlombok
34 | lombok
35 |
36 |
37 | org.apache.commons
38 | commons-lang3
39 | 3.5
40 |
41 |
42 | com.google.guava
43 | guava
44 | 21.0
45 |
46 |
47 |
48 |
49 |
50 |
51 | org.apache.maven.plugins
52 | maven-compiler-plugin
53 |
54 | 1.8
55 | 1.8
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/Application.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | /**
7 | * @author Niu Li
8 | * @since 2017/6/16
9 | */
10 | @SpringBootApplication
11 | public class Application {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(Application.class, args);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/config/CommonBeanConfig.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | import cn.mrdear.security.util.JwtTokenUtil;
7 |
8 | /**
9 | * 配置一些线程安全的工具类
10 | * @author Niu Li
11 | * @since 2017/6/28
12 | */
13 | @Configuration
14 | public class CommonBeanConfig {
15 |
16 | /**
17 | * 配置jwt token
18 | */
19 | @Bean
20 | public JwtTokenUtil configToken() {
21 | return new JwtTokenUtil();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/config/CorsFilter.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.config;
2 |
3 | import javax.servlet.FilterChain;
4 | import javax.servlet.FilterConfig;
5 | import javax.servlet.ServletException;
6 | import javax.servlet.ServletRequest;
7 | import javax.servlet.ServletResponse;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | import java.io.IOException;
12 |
13 |
14 | public class CorsFilter implements javax.servlet.Filter {
15 | @Override
16 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
17 | System.err.println("CorsFilter");
18 | HttpServletResponse res = (HttpServletResponse) response;
19 | HttpServletRequest req = (HttpServletRequest) request;
20 |
21 | res.setHeader("Access-Control-Allow-Origin", "*");
22 | res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
23 | res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, Connection, User-Agent, authorization, sw-useragent, sw-version");
24 |
25 | // Just REPLY OK if request method is OPTIONS for CORS (pre-flight)
26 | if (req.getMethod().equals("OPTIONS")) {
27 | res.setStatus(HttpServletResponse.SC_OK);
28 | return;
29 | }
30 | chain.doFilter(request, response);
31 | }
32 |
33 | @Override
34 | public void destroy() {
35 | }
36 |
37 | @Override
38 | public void init(FilterConfig filterConfig) throws ServletException {
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/config/VerifyTokenFilter.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.config;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 |
5 | import org.springframework.security.core.Authentication;
6 | import org.springframework.security.core.context.SecurityContextHolder;
7 | import org.springframework.web.filter.OncePerRequestFilter;
8 |
9 | import cn.mrdear.security.util.JwtTokenUtil;
10 | import io.jsonwebtoken.JwtException;
11 |
12 | import javax.servlet.FilterChain;
13 | import javax.servlet.ServletException;
14 | import javax.servlet.http.HttpServletRequest;
15 | import javax.servlet.http.HttpServletResponse;
16 |
17 | import java.io.IOException;
18 | import java.util.Optional;
19 |
20 | /**
21 | * jwt token验证类,验证成功后设置进去SecurityContext中
22 | * @author Niu Li
23 | * @since 2017/6/28
24 | */
25 | @Slf4j
26 | public class VerifyTokenFilter extends OncePerRequestFilter {
27 |
28 | private JwtTokenUtil jwtTokenUtil;
29 |
30 | public VerifyTokenFilter(JwtTokenUtil jwtTokenUtil) {
31 | this.jwtTokenUtil = jwtTokenUtil;
32 | }
33 |
34 | @Override
35 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
36 | try {
37 | Optional authentication = jwtTokenUtil.verifyToken(request);
38 | log.debug("VerifyTokenFilter result: {}",authentication.orElse(null));
39 | SecurityContextHolder.getContext().setAuthentication(authentication.orElse(null));
40 | filterChain.doFilter(request,response);
41 | } catch (JwtException e) {
42 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
43 | //可以在这里指定重定向还是返回错误接口示例
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/controller/LoginCntroller.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.controller;
2 |
3 | import com.google.common.collect.Lists;
4 |
5 | import org.apache.commons.lang3.StringUtils;
6 | import org.springframework.security.core.Authentication;
7 | import org.springframework.security.core.context.SecurityContextHolder;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import cn.mrdear.security.dto.TokenUserDTO;
12 | import cn.mrdear.security.util.JwtTokenUtil;
13 |
14 | import javax.annotation.Resource;
15 |
16 | import java.util.HashMap;
17 | import java.util.Map;
18 | import java.util.Objects;
19 |
20 | /**
21 | * @author Niu Li
22 | * @since 2017/6/19
23 | */
24 | @RestController
25 | public class LoginCntroller {
26 |
27 | @Resource
28 | private JwtTokenUtil jwtTokenUtil;
29 |
30 | /**
31 | * 该链接获取token
32 | */
33 | @GetMapping("/login")
34 | public Map login(String username, String password) {
35 | Map map = new HashMap<>();
36 | if (!StringUtils.equals(username, "demo") || !StringUtils.equals(password, "demo")) {
37 | map.put("status", 4);
38 | map.put("msg", "登录失败,用户名密码错误");
39 | return map;
40 | }
41 | TokenUserDTO userDTO = new TokenUserDTO();
42 | userDTO.setUsername(username);
43 | userDTO.setRoles(Lists.newArrayList("ROLE_ADMIN"));
44 | userDTO.setId(1L);
45 | userDTO.setEmail("1015315668@qq.com");
46 | userDTO.setAvatar("ahahhahahhaha");
47 | map.put("status", 1);
48 | map.put("msg", "Success");
49 | map.put("token", jwtTokenUtil.create(userDTO));
50 | return map;
51 | }
52 |
53 | /**
54 | * 该链接尝试获取登录用户,返回该认证用户的信息,请求该链接需要在header中放入x-authorization: token
55 | */
56 | @GetMapping("/detail")
57 | public TokenUserDTO userDetail() {
58 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
59 | if (Objects.isNull(authentication)) {
60 | return null;
61 | }
62 | return (TokenUserDTO) authentication.getDetails();
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/dto/TokenUserAuthentication.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.dto;
2 |
3 | import org.springframework.security.core.Authentication;
4 | import org.springframework.security.core.GrantedAuthority;
5 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
6 |
7 | import java.util.Collection;
8 | import java.util.stream.Collectors;
9 |
10 | /**
11 | * Spring Security中存放的认证用户
12 | * @author Niu Li
13 | * @since 2017/6/28
14 | */
15 | public class TokenUserAuthentication implements Authentication {
16 |
17 | private static final long serialVersionUID = 3730332217518791533L;
18 |
19 | private TokenUserDTO userDTO;
20 |
21 | private Boolean authentication = false;
22 |
23 | public TokenUserAuthentication(TokenUserDTO userDTO, Boolean authentication) {
24 | this.userDTO = userDTO;
25 | this.authentication = authentication;
26 | }
27 |
28 | @Override
29 | public Collection extends GrantedAuthority> getAuthorities() {
30 | return userDTO.getRoles().stream()
31 | .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
32 | }
33 |
34 | @Override
35 | public Object getCredentials() {
36 | return "";
37 | }
38 |
39 | @Override
40 | public Object getDetails() {
41 | return userDTO;
42 | }
43 |
44 | @Override
45 | public Object getPrincipal() {
46 | return userDTO.getUsername();
47 | }
48 |
49 | @Override
50 | public boolean isAuthenticated() {
51 | return authentication;
52 | }
53 |
54 | @Override
55 | public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
56 | this.authentication = isAuthenticated;
57 | }
58 |
59 | @Override
60 | public String getName() {
61 | return userDTO.getUsername();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/java/cn/mrdear/security/dto/TokenUserDTO.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.security.dto;
2 |
3 | import lombok.Data;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * @author Niu Li
9 | * @since 2017/6/28
10 | */
11 | @Data
12 | public class TokenUserDTO {
13 |
14 | private Long id;
15 |
16 | private String username;
17 |
18 | private String email;
19 |
20 | private String avatar;
21 |
22 | private List roles;
23 | }
24 |
--------------------------------------------------------------------------------
/Spring-Security-Demo/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8080
2 |
3 | logging.level.root=info
4 | logging.level.org.springframework.security=debug
5 |
6 |
7 | # jwt token签名密钥
8 | jwt.token.secret=quding2017
--------------------------------------------------------------------------------
/Util-Demo/src/main/java/cn/mrdear/util/jniUtil/NativeLibraryLoader.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util.jniUtil;
2 |
3 | import java.io.*;
4 |
5 | /**
6 | * Contains helper methods for loading native libraries, particularly JNI.
7 | *
8 | * @author gkubisa
9 | */
10 | public class NativeLibraryLoader {
11 | /**
12 | * Utility classes should not have a public constructor.
13 | */
14 | private NativeLibraryLoader() { }
15 |
16 | /**
17 | * Loads a native shared library. It tries the standard System.loadLibrary
18 | * method first and if it fails, it looks for the library in the current
19 | * class path. It will handle libraries packed within jar files, too.
20 | *
21 | * @param libraryName - name of the library to load
22 | * @throws IOException if the library cannot be extracted from a jar file
23 | * into a temporary file
24 | */
25 | public static void loadLibrary(String libraryName) throws IOException {
26 | try {
27 | System.loadLibrary(libraryName);
28 | } catch (UnsatisfiedLinkError e) {
29 | String fileName = System.mapLibraryName(libraryName);
30 |
31 | int dotPosition = fileName.lastIndexOf('.');
32 | File file = File.createTempFile(fileName.substring(0, dotPosition), fileName.substring(dotPosition));
33 | file.deleteOnExit();
34 |
35 | byte[] buffer = new byte[4096];
36 | InputStream inputStream = NativeLibraryLoader.class.getClassLoader().getResourceAsStream(fileName);
37 | OutputStream outputStream = new FileOutputStream(file);
38 |
39 | try {
40 | while ( inputStream.available() > 0 ) {
41 | int StreamLength = inputStream.read(buffer);
42 | if ( StreamLength >= 0 ) {
43 | outputStream.write(buffer, 0, StreamLength);
44 | }
45 | }
46 | } finally {
47 | outputStream.close();
48 | inputStream.close();
49 | }
50 |
51 | System.load(file.getAbsolutePath());
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Util-Demo/src/main/java/cn/mrdear/util/moneyUtil/MoneyUtil.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util.moneyUtil;
2 |
3 | import org.apache.commons.lang3.math.NumberUtils;
4 |
5 | import java.math.BigDecimal;
6 | import java.text.DecimalFormat;
7 | import java.text.NumberFormat;
8 | import java.text.ParseException;
9 | import java.util.HashMap;
10 | import java.util.Map;
11 |
12 | /**
13 | * 关于金钱操作的工具类
14 | * @author Niu Li
15 | * @since 2017/3/2
16 | */
17 | public class MoneyUtil {
18 |
19 | private static final Map> moneyMap = new HashMap<>();
20 |
21 | private static final double CENT_RATE = 100.0;
22 |
23 | /**
24 | * 获取当前线程的decimalFormat工具类,因为该类是非同步的
25 | * @param pattern 格式
26 | * @return 该实例
27 | */
28 | private static DecimalFormat getDecimal(final String pattern){
29 | ThreadLocal instance = moneyMap.get(pattern);
30 | if (instance == null){
31 | synchronized (MoneyUtil.class){
32 | instance = moneyMap.get(pattern);
33 | if (instance == null){
34 | instance = new ThreadLocal(){
35 | @Override
36 | protected DecimalFormat initialValue() {
37 | return new DecimalFormat(pattern);
38 | }
39 | };
40 | }
41 | moneyMap.put(pattern,instance);
42 | }
43 | }
44 | return instance.get();
45 | }
46 |
47 | /**
48 | * 分转元
49 | * @param cent 分
50 | * @return 元
51 | */
52 | public static String cent2yuan(Long cent){
53 | return getDecimal("0.00").format(cent/CENT_RATE);
54 | }
55 |
56 | /**
57 | * 元转分
58 | * @param yuan 元金额
59 | * @return 分
60 | */
61 | public static Long yuan2cent(double yuan) {
62 | return Math.round(yuan * CENT_RATE);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Util-Demo/src/main/java/cn/mrdear/util/redis/calback/WorkCallback.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util.redis.calback;
2 |
3 | /**
4 | * 模仿Spring ConnectionCallback写的模板接口
5 | * T为操作返回值 E为参数类型
6 | * @author Niu Li
7 | * @date 2016/12/8
8 | */
9 | public interface WorkCallback {
10 | /**
11 | * 具体执行策略
12 | * @param e 传入参数
13 | * @return 结果
14 | */
15 | T doWorkCallback(E e);
16 | }
17 |
--------------------------------------------------------------------------------
/Util-Demo/src/main/java/cn/mrdear/util/redis/service/JedisClient.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util.redis.service;
2 |
3 |
4 | /**
5 | * 定义redis需要的接口
6 | * @author Niu Li
7 | * @date 2016/12/8
8 | */
9 | public interface JedisClient {
10 | /**
11 | * 根据key值获取
12 | * @param key 指定key
13 | * @return 存在返回值,不存在返回null
14 | */
15 | String get(String key);
16 |
17 | /**
18 | * 设置值(String kei)
19 | * @param key key值
20 | * @param value 内容
21 | * @return 成功则 ok
22 | */
23 | String set(String key, String value);
24 |
25 | /**
26 | * 得到key的剩余时间
27 | * @param key 指定key
28 | * @return -2不存在 -1存在但无剩余时间 其他为剩余时间
29 | */
30 | Long ttl(String key);
31 |
32 | /**
33 | * 等价于 set + expire
34 | * @param key 设置的key
35 | * @param seconds 存活时间,到期自动删除
36 | * @param value 对应值
37 | * @return 结果
38 | */
39 | String setex(final String key, final String value, final int seconds);
40 |
41 | /**
42 | * 删除指定key
43 | * @param key 指定key
44 | * @return 不存在返回0 返回删除个数
45 | */
46 | Long del(String key);
47 |
48 | /**
49 | *给指定key设置时间
50 | * @param key 指定key
51 | * @param timeout 超时时间,单位秒
52 | * @return 1成功 0失败
53 | */
54 | Long expire(String key, int timeout);
55 |
56 | /**
57 | * 检测key是否存在
58 | * @param key 指定key
59 | * @return true存在
60 | */
61 | Boolean exists(String key);
62 |
63 | /**
64 | * 不存在则设置,并延时,存在则什么都不做
65 | * @param key key值
66 | * @param value 值
67 | * @param seconds 超时时间
68 | * @return true成功
69 | */
70 | Boolean setNxAndExpire(final String key, final String value, final int seconds);
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/Util-Demo/src/main/java/cn/mrdear/util/vo/ResultWrapper.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.util.vo;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * 用于包装接口返回
7 | * @author Niu Li
8 | * @since 2017/4/19
9 | */
10 | public class ResultWrapper {
11 | /**
12 | * 状态码
13 | */
14 | private Integer status;
15 | /**
16 | * 状态信息
17 | */
18 | private String msg;
19 | /**
20 | * 数据data
21 | */
22 | private T data;
23 |
24 |
25 | public ResultWrapper OK(){
26 | //todo 自己根据错误码填充
27 | this.status = 1;
28 | this.msg = "Success";
29 | return this;
30 | }
31 |
32 | public ResultWrapper OKWithData(T data) {
33 | this.OK();
34 | this.data = data;
35 | return this;
36 | }
37 |
38 | public ResultWrapper CustomStatus(Integer status, String msg) {
39 | this.status = status;
40 | this.msg = msg;
41 | return this;
42 | }
43 |
44 |
45 | /**
46 | * 用于滚动数据的返回,举例瀑布流
47 | * @param
48 | */
49 | public static class ScrollData{
50 | private Integer hasMore;
51 |
52 | private Integer nextSatrt;
53 |
54 | private List objectList;
55 |
56 | public ScrollData(boolean hasMore, Integer nextSatrt, List objectList) {
57 | this.hasMore = hasMore?1:0;
58 | this.nextSatrt = nextSatrt;
59 | this.objectList = objectList;
60 | }
61 | }
62 |
63 | /**
64 | * 用于分页数据返回
65 | * @param
66 | */
67 | private static class PaginationData{
68 | private Integer total;
69 | private Integer limit;
70 | private List objectList;
71 |
72 | public PaginationData(Integer limit, Integer total, List objectList) {
73 | this.limit = limit;
74 | this.total = total;
75 | this.objectList = objectList;
76 | }
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/AESUtilTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 |
3 | import cn.mrdear.util.SecurityUtil.AESUtil;
4 |
5 | /**
6 | * @author Niu Li
7 | * @date 2016/12/11
8 | */
9 | public class AESUtilTest {
10 | @Test
11 | public void testAES() {
12 | String str = "hello world";
13 | String en = AESUtil.base64AndEncrypt(str, "123456");
14 | System.out.println(en);
15 | System.out.println(AESUtil.base64AndDecrypt(en,"123456"));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/DataUtilTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 |
3 | import java.util.Date;
4 |
5 | import cn.mrdear.util.dateutil.DateUtil;
6 |
7 | /**
8 | * @author Niu Li
9 | * @date 2016/12/11
10 | */
11 | public class DataUtilTest {
12 | @Test
13 | public void testParse(){
14 | String str = "2016-12-11 09:38:19";
15 | System.out.println(DateUtil.parse(str,DateUtil.YMDHMS_));
16 | }
17 |
18 | @Test
19 | public void testFormat(){
20 | String str = DateUtil.format(new Date(),DateUtil.YMDHMS_);
21 | System.out.println(str);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/DigestUtilTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 |
3 | import cn.mrdear.util.SecurityUtil.DigestUtil;
4 |
5 | /**
6 | * @author Niu Li
7 | * @date 2016/12/11
8 | */
9 | public class DigestUtilTest {
10 |
11 | @Test
12 | public void testMD5() {
13 | String str = "hello world";
14 | System.out.println(DigestUtil.digest(DigestUtil.SecurityEnum.MD5,str));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/RedisTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 |
3 | import cn.mrdear.util.redis.service.JedisClientSingle;
4 | import redis.clients.jedis.JedisPool;
5 |
6 | /**
7 | * @author Niu Li
8 | * @date 2016/12/11
9 | */
10 | public class RedisTest {
11 |
12 | @Test
13 | public void testGet() {
14 | //比较推荐依赖注入
15 | JedisPool jedisPool = new JedisPool("172.18.1.1",6636);
16 | JedisClientSingle clientSingle = new JedisClientSingle(jedisPool);
17 | String result = clientSingle.get("foo");
18 | System.out.println(result);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/XmlTest.java:
--------------------------------------------------------------------------------
1 | import org.dom4j.DocumentException;
2 | import org.junit.Test;
3 |
4 | import java.io.InputStream;
5 | import java.io.InputStreamReader;
6 |
7 | import javax.xml.bind.annotation.XmlRootElement;
8 |
9 | import cn.mrdear.util.xml.XmlUtil;
10 |
11 | /**
12 | * @author Niu Li
13 | * @date 2016/12/11
14 | */
15 | public class XmlTest
16 | {
17 | @Test
18 | public void testXmlReder() throws DocumentException {
19 | InputStream stream = XmlTest.class.getResourceAsStream("message.xml");
20 | String result = XmlUtil.reader(new InputStreamReader(stream),"content","gift");
21 | System.out.println(result);
22 | }
23 |
24 | @Test
25 | public void testBeanToXml() {
26 | User user = new User();
27 | user.setUsername("zhangsan");
28 | user.setPassword("123456");
29 | System.out.println(XmlUtil.beanToXml(user));
30 | //123456zhangsan
31 | //需要手动去除前面头部
32 | }
33 |
34 | @XmlRootElement(name = "xml")
35 | static class User{
36 | private String username;
37 | private String password;
38 |
39 | public String getUsername() {
40 | return username;
41 | }
42 |
43 | public void setUsername(String username) {
44 | this.username = username;
45 | }
46 |
47 | public String getPassword() {
48 | return password;
49 | }
50 |
51 | public void setPassword(String password) {
52 | this.password = password;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/java/httpUtilTest.java:
--------------------------------------------------------------------------------
1 | import org.junit.Test;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import cn.mrdear.util.httpUtil.WebUtils;
7 |
8 | /**
9 | * @author Niu Li
10 | * @date 2016/12/11
11 | */
12 | public class httpUtilTest {
13 |
14 | @Test
15 | public void testGet() {
16 | String url = "http://php.weather.sina.com.cn/iframe/index/w_cl.php";
17 | Map params = new HashMap<>();
18 | params.put("code","js");
19 | params.put("day",0);
20 | params.put("city","上海");
21 | params.put("dfc",1);
22 | params.put("charset","utf-8");
23 | String result = WebUtils.get(url,params);
24 | System.out.println(result);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Util-Demo/src/test/resources/message.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 尊敬的会员,这是您的验证码{code_set}(有效时间{minute_set}分钟),感谢您的关注!
6 |
7 |
8 | 您的朋友{giver_mobile}赠送给您{card_num}张"{card_name}",请及时关注微信"融信科技"公众号,进行查收。
9 |
10 | 尊敬的会员,这是您的支付密码已重置为{passwd_set},登录后请立即修改密码。
11 |
12 |
13 | 尊敬的会员,您当前账户余额{bal_amt},您尾号{end_code}的卡号消费了{amt_cuy}元,如果不是本人消费,请立即联系管理员处理。
14 |
15 |
16 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/ServerInterruptImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess;
2 |
3 | import io.grpc.ForwardingServerCall;
4 | import io.grpc.Metadata;
5 | import io.grpc.ServerCall;
6 | import io.grpc.ServerCallHandler;
7 | import io.grpc.ServerInterceptor;
8 | import io.grpc.Status;
9 | import io.netty.util.internal.StringUtil;
10 |
11 | /**
12 | * 服务端拦截器
13 | * @author Niu Li
14 | * @date 2017/2/4
15 | */
16 | public class ServerInterruptImpl implements ServerInterceptor{
17 | @Override
18 | public ServerCall.Listener interceptCall(ServerCall call,
19 | Metadata headers, ServerCallHandler next) {
20 | System.out.println("执行server拦截器1,获取token");
21 | //获取客户端参数
22 | Metadata.Key token = Metadata.Key.of("token", Metadata.ASCII_STRING_MARSHALLER);
23 | String tokenStr = headers.get(token);
24 | if (StringUtil.isNullOrEmpty(tokenStr)){
25 | System.out.println("未收到客户端token,关闭此连接");
26 | call.close(Status.DATA_LOSS,headers);
27 | }
28 | //服务端写回参数
29 | ServerCall serverCall = new ForwardingServerCall.SimpleForwardingServerCall(call) {
30 | @Override
31 | public void sendHeaders(Metadata headers) {
32 | System.out.println("执行server拦截器2,写入token");
33 | headers.put(token,tokenStr);
34 | super.sendHeaders(headers);
35 | }
36 | };
37 | return next.startCall(serverCall,headers);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/forwardExample/Client.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess.forwardExample;
2 |
3 | /**
4 | * 主调用接口
5 | * @author Niu Li
6 | * @date 2017/2/4
7 | */
8 | public abstract class Client {
9 | public abstract void start(String say);
10 | }
11 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/forwardExample/ClientImp.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess.forwardExample;
2 |
3 | /**
4 | * @author Niu Li
5 | * @date 2017/2/4
6 | */
7 | public class ClientImp extends Client {
8 | @Override
9 | public void start(String say) {
10 | System.out.println(say);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/forwardExample/ForwardingClient.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess.forwardExample;
2 |
3 | /**
4 | * 用于包装Client到另一个Client
5 | * @author Niu Li
6 | * @date 2017/2/4
7 | */
8 | public abstract class ForwardingClient extends Client{
9 | //要包装的对象
10 | protected abstract Client delegate();
11 |
12 | @Override
13 | public void start(String say) {
14 | delegate().start(say);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/forwardExample/ForwardingClientImpl.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess.forwardExample;
2 |
3 | /**
4 | * 一个简单的包装示例,必须要传入要包装的对象
5 | * @author Niu Li
6 | * @date 2017/2/4
7 | */
8 | public class ForwardingClientImpl extends ForwardingClient{
9 |
10 | //被委托对象
11 | private final Client client;
12 |
13 | public ForwardingClientImpl(Client client) {
14 | this.client = client;
15 | }
16 |
17 | @Override
18 | protected Client delegate() {
19 | return client;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/clientProcess/forwardExample/InterceptTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.clientProcess.forwardExample;
2 |
3 | /**
4 | * 一个简单的委托模式.
5 | * @author Niu Li
6 | * @date 2017/2/4
7 | */
8 | public class InterceptTest {
9 |
10 | public static void main(String[] args) {
11 | Client client = new ClientImp();//主要想执行的方法
12 | //构造第一个拦截器
13 | Client intercept1 = new ForwardingClientImpl(client){
14 | @Override
15 | public void start(String say) {
16 | System.out.println("拦截器1");
17 | super.start(say);
18 | }
19 | };
20 | //构造第二个拦截器
21 | Client intercept2 = new ForwardingClientImpl(intercept1){
22 | @Override
23 | public void start(String say) {
24 | System.out.println("拦截器2");
25 | super.start(say);
26 | }
27 | };
28 | //执行主方法
29 | intercept2.start("这是要执行的方法");
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/common/WorkCallBack.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.common;
2 |
3 | /**
4 | * 给模板类使用的接口
5 | * @author Niu Li
6 | * @since 17-2-8
7 | */
8 | public interface WorkCallBack {
9 |
10 | void callback(S s);
11 | }
12 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/hellopool/HelloWorldClientPool.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.hellopool;
2 |
3 | import org.apache.commons.pool2.impl.GenericObjectPool;
4 | import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
5 |
6 | import cn.mrdear.grpc.common.WorkCallBack;
7 |
8 | /**
9 | * @author Niu Li
10 | * @since 17-2-8
11 | */
12 | public class HelloWorldClientPool {
13 |
14 | private static GenericObjectPool objectPool = null;
15 |
16 | static {
17 | // 连接池的配置
18 | GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
19 | // 池中的最大连接数
20 | poolConfig.setMaxTotal(8);
21 | // 最少的空闲连接数
22 | poolConfig.setMinIdle(0);
23 | // 最多的空闲连接数
24 | poolConfig.setMaxIdle(8);
25 | // 当连接池资源耗尽时,调用者最大阻塞的时间,超时时抛出异常 单位:毫秒数
26 | poolConfig.setMaxWaitMillis(-1);
27 | // 连接池存放池化对象方式,true放在空闲队列最前面,false放在空闲队列最后
28 | poolConfig.setLifo(true);
29 | // 连接空闲的最小时间,达到此值后空闲连接可能会被移除,默认即为30分钟
30 | poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L);
31 | // 连接耗尽时是否阻塞,默认为true
32 | poolConfig.setBlockWhenExhausted(true);
33 | // 连接池创建
34 | objectPool = new GenericObjectPool<>(new HelloWorldFactory(), poolConfig);
35 | }
36 |
37 | /**
38 | * 从连接池获取对象
39 | */
40 | private static HelloWorldClientSingle borrowObject(){
41 | try {
42 | HelloWorldClientSingle clientSingle = objectPool.borrowObject();
43 | System.out.println("总创建线程数"+objectPool.getCreatedCount());
44 | return clientSingle;
45 | } catch (Exception e) {
46 | e.printStackTrace();
47 | }
48 | //连接池失败则主动创建
49 | return createClient();
50 | }
51 |
52 | /**
53 | * 当连接池异常,则主动创建对象
54 | */
55 | private static HelloWorldClientSingle createClient(){
56 | return new HelloWorldClientSingle("127.0.0.1", 55001);
57 | }
58 |
59 | /**
60 | * 执行器
61 | * @param workCallBack 主要服务内容
62 | */
63 | public static Runnable execute(WorkCallBack workCallBack){
64 | return () -> {
65 | HelloWorldClientSingle client = borrowObject();
66 | try {
67 | workCallBack.callback(client);
68 | } finally {
69 | /** 将连接对象返回给连接池 */
70 | objectPool.returnObject(client);
71 | }
72 | };
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/hellopool/HelloWorldClientSingle.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.hellopool;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import io.grpc.ManagedChannel;
6 | import io.grpc.ManagedChannelBuilder;
7 | import io.grpc.StatusRuntimeException;
8 | import io.grpc.examples.helloworld.GreeterGrpc;
9 | import io.grpc.examples.helloworld.HelloReply;
10 | import io.grpc.examples.helloworld.HelloRequest;
11 |
12 | /**
13 | * @author Niu Li
14 | * @date 2017/1/28
15 | */
16 | public class HelloWorldClientSingle {
17 |
18 | private final ManagedChannel channel; //一个gRPC信道
19 | private GreeterGrpc.GreeterBlockingStub greeterBlockingStub;//阻塞/同步 存根
20 |
21 | //初始化信道和存根
22 | public HelloWorldClientSingle(String host,int port){
23 | channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
24 | }
25 |
26 | public void shutdown() throws InterruptedException {
27 | channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
28 | }
29 |
30 | //客户端方法
31 | public void greet(String name){
32 | //需要用到存根时创建,不可复用
33 | greeterBlockingStub = GreeterGrpc.newBlockingStub(channel).withCompression("gzip");
34 | HelloRequest request = HelloRequest.newBuilder().setName(name).build();
35 | HelloReply response;
36 | try {
37 | response = greeterBlockingStub.sayHello(request);
38 | } catch (StatusRuntimeException e) {
39 | System.out.println("RPC调用失败:"+e.getMessage());
40 | return;
41 | }
42 | System.out.println("服务器返回信息:"+response.getMessage());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/hellopool/HelloWorldClientTest.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.hellopool;
2 |
3 | /**
4 | * @author Niu Li
5 | * @since 17-2-8
6 | */
7 | public class HelloWorldClientTest {
8 |
9 | public static void main(String[] args) {
10 | for (int i = 0; i < 100; i++) {
11 | new Thread( HelloWorldClientPool.execute(clientSingle -> {
12 | clientSingle.greet("world");
13 | })).start();
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/hellopool/HelloWorldFactory.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.hellopool;
2 |
3 | import org.apache.commons.pool2.BasePooledObjectFactory;
4 | import org.apache.commons.pool2.PooledObject;
5 | import org.apache.commons.pool2.impl.DefaultPooledObject;
6 |
7 | /**
8 | * 连接池所需工厂
9 | * @author Niu Li
10 | * @since 17-2-8
11 | */
12 | public class HelloWorldFactory extends BasePooledObjectFactory {
13 |
14 | private String host = "127.0.0.1";
15 |
16 | private int port = 50051;
17 |
18 | @Override
19 | public HelloWorldClientSingle create() throws Exception {
20 | return new HelloWorldClientSingle(this.host,this.port);
21 | }
22 |
23 | @Override
24 | public PooledObject wrap(HelloWorldClientSingle helloWorldClientSingle) {
25 | return new DefaultPooledObject<>(helloWorldClientSingle);
26 | }
27 |
28 | @Override
29 | public void destroyObject(PooledObject p) throws Exception {
30 | p.getObject().shutdown();
31 | super.destroyObject(p);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/route/RouteGuideServer.java:
--------------------------------------------------------------------------------
1 | package cn.mrdear.grpc.route;
2 |
3 | import java.io.IOException;
4 | import java.util.List;
5 |
6 | import cn.mrdear.route.Feature;
7 | import io.grpc.Server;
8 | import io.grpc.ServerBuilder;
9 |
10 | /**
11 | * @author Niu Li
12 | * @date 2017/2/2
13 | */
14 | public class RouteGuideServer {
15 | private final int port;//服务端端口
16 | private final Server server;//服务器
17 |
18 | public RouteGuideServer(int port) throws IOException {
19 | this.port = port;
20 | //获取初始化数据
21 | List features = RouteGuideUtil.parseFeatures(RouteGuideUtil.getDefaultFeaturesFile());
22 | //初始化Server参数
23 | server = ServerBuilder.forPort(port)
24 | //添加指定服务
25 | .addService(new RouteGuideService(features))
26 | .build();
27 | }
28 |
29 | /**
30 | * 启动服务
31 | */
32 | public void start() throws IOException {
33 | server.start();
34 | System.out.println("Server started, listening on " + port);
35 | //程序退出时关闭资源
36 | Runtime.getRuntime().addShutdownHook(new Thread(() -> {
37 | System.err.println("*** shutting down gRPC server since JVM is shutting down");
38 | RouteGuideServer.this.stop();
39 | System.err.println("*** server shut down");
40 | }));
41 | }
42 |
43 | /**
44 | * 关闭服务
45 | */
46 | public void stop() {
47 | if (server != null) {
48 | server.shutdown();
49 | }
50 | }
51 |
52 | /**
53 | * 使得server一直处于运行状态
54 | */
55 | private void blockUntilShutdown() throws InterruptedException {
56 | if (server != null) {
57 | server.awaitTermination();
58 | }
59 | }
60 |
61 | public static void main(String[] args) throws IOException, InterruptedException {
62 | RouteGuideServer server = new RouteGuideServer(50051);
63 | server.start();
64 | server.blockUntilShutdown();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/java/cn/mrdear/grpc/route/RouteGuideUtil.java:
--------------------------------------------------------------------------------
1 |
2 | package cn.mrdear.grpc.route;
3 |
4 | import com.google.protobuf.util.JsonFormat;
5 |
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.io.InputStreamReader;
9 | import java.io.Reader;
10 | import java.net.URL;
11 | import java.util.List;
12 |
13 | import cn.mrdear.route.Feature;
14 | import cn.mrdear.route.FeatureDatabase;
15 | import cn.mrdear.route.Point;
16 |
17 | /**
18 | * 为该Demo提供数据
19 | */
20 | public class RouteGuideUtil {
21 | private static final double COORD_FACTOR = 1e7;
22 |
23 | public static void main(String[] args) throws IOException {
24 | URL featuresFile = getDefaultFeaturesFile();
25 | List list = parseFeatures(featuresFile);
26 | System.out.println(list);
27 | }
28 | /**
29 | * Gets the latitude for the given point.
30 | */
31 | public static double getLatitude(Point location) {
32 | return location.getLatitude() / COORD_FACTOR;
33 | }
34 |
35 | /**
36 | * Gets the longitude for the given point.
37 | */
38 | public static double getLongitude(Point location) {
39 | return location.getLongitude() / COORD_FACTOR;
40 | }
41 |
42 | /**
43 | * Gets the default features file from classpath.
44 | */
45 | public static URL getDefaultFeaturesFile() {
46 | return RouteGuideServer.class.getClassLoader().getResource("route_guide_db.json");
47 | }
48 |
49 | /**
50 | * Parses the JSON input file containing the list of features.
51 | */
52 | public static List parseFeatures(URL file) throws IOException {
53 | InputStream input = file.openStream();
54 | try {
55 | Reader reader = new InputStreamReader(input);
56 | try {
57 | FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
58 | JsonFormat.parser().merge(reader, database);
59 | return database.getFeatureList();
60 | } finally {
61 | reader.close();
62 | }
63 | } finally {
64 | input.close();
65 | }
66 | }
67 |
68 | /**
69 | * Indicates whether the given feature exists (i.e. has a valid name).
70 | */
71 | public static boolean exists(Feature feature) {
72 | return feature != null && !feature.getName().isEmpty();
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/proto/hello.proto:
--------------------------------------------------------------------------------
1 | //指定proto3格式
2 | syntax = "proto3";
3 | //一些生成代码的设置
4 | option java_multiple_files = true;//以外部类模式生成
5 | option java_package = "io.grpc.examples.helloworld";//所在包名
6 | option java_outer_classname = "HelloWorldProto";//最外层类名称
7 |
8 | package helloworld;
9 |
10 | //定义了一个service
11 | service Greeter {
12 | rpc SayHello (HelloRequest) returns (HelloReply) {}
13 | }
14 |
15 | //定义了一个消息请求体
16 | message HelloRequest {
17 | string name = 1;
18 | }
19 |
20 | //定义了一个消息回复体
21 | message HelloReply {
22 | string message = 1;
23 | }
24 |
--------------------------------------------------------------------------------
/gRPC-Demo/src/main/proto/route.proto:
--------------------------------------------------------------------------------
1 | //指定proto3格式
2 | syntax = "proto3";
3 | //一些生成代码的设置
4 | option java_multiple_files = true;//以外部类模式生成
5 | option java_package = "cn.mrdear.route";//所在包名
6 | option java_outer_classname = "RouteProto";//最外层类名称
7 |
8 |
9 | //定义服务
10 | service RouteGuide{
11 | //得到指定点的feature
12 | //一个 简单 RPC , 客户端使用存根发送请求到服务器并等待响应返回,就像平常的函数调用一样。
13 | rpc GetFeature(Point) returns (Feature) {}
14 | //获取一个矩形内的点
15 | //一个 服务器端流式 RPC , 客户端发送请求到服务器,拿到一个流去读取返回的消息序列。 客户端读取返回的流,
16 | //直到里面没有任何消息。从例子中可以看出,通过在 响应 类型前插入 stream 关键字,可以指定一个服务器端的流方法。
17 | rpc ListFeatures(Rectangle) returns (stream Feature){}
18 | //记录该点
19 | //一个 客户端流式 RPC , 客户端写入一个消息序列并将其发送到服务器,同样也是使用流。一旦客户端完成写入消息,
20 | //它等待服务器完成读取返回它的响应。通过在 请求 类型前指定 stream 关键字来指定一个客户端的流方法。
21 | rpc RecordRoute(stream Point) returns (RouteSummary){}
22 | //路由交流
23 | //一个 双向流式 RPC 是双方使用读写流去发送一个消息序列。两个流独立操作,因此客户端和服务器
24 | //可以以任意喜欢的顺序读写:比如, 服务器可以在写入响应前等待接收所有的客户端消息,或者可以交替 的读取和写入消息,
25 | //或者其他读写的组合。每个流中的消息顺序被预留。你可以通过在请求和响应前加 stream 关键字去制定方法的类型。
26 | rpc RouteChat(stream RouteNote) returns (stream RouteNote){}
27 | }
28 |
29 |
30 | //代表经纬度
31 | message Point {
32 | int32 latitude = 1;
33 | int32 longitude = 2;
34 | }
35 | //由两个点确定的一个方块
36 | message Rectangle{
37 | Point lo = 1;
38 | Point hi = 2;
39 | }
40 | //某一位置的名称
41 | message Feature {
42 |
43 | string name = 1;
44 |
45 | Point location = 2;
46 | }
47 |
48 | // Not used in the RPC. Instead, this is here for the form serialized to disk.
49 | message FeatureDatabase {
50 | repeated Feature feature = 1;
51 | }
52 | //给某一点发送消息
53 | message RouteNote{
54 | Point location = 1;
55 | string message = 2;
56 | }
57 |
58 | //记录收到的信息
59 | message RouteSummary{
60 | int32 point_count = 1;
61 | int32 feture_count = 2;
62 | int32 distance = 3;
63 | int32 elapsed_time = 4;
64 | }
--------------------------------------------------------------------------------