# novaframe
**Repository Path**: locki/novaframe
## Basic Information
- **Project Name**: novaframe
- **Description**: No description available
- **Primary Language**: Java
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2017-05-14
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 目录
- Web层
- Thymeleaf
- 统一异常处理
- Swagger2 RESTful API
- LoggingAspect
- 服务层
- Scheduled和Async
- Mail
- 数据访问层
- 整合Mybatis
- 整合Mybatis Mapper
- 整合Mybatis PageHelper
- Cache
- 安全管理
- Spring Security
- JWT
# Spring Boot集成
配置文件文档:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#appendix
## LOGGING
```
spring.output.ansi.enabled=DETECT
logging.pattern.console=
logging.pattern.file=
```
## Redis
- starter: spring-boot-starter-data-redis
- optional: true
- autoconfig: RedisAutoConfiguration
- usage: https://docs.spring.io/spring-data/redis/docs/1.6.2.RELEASE/reference/html/
## MongoDB
- starter: spring-boot-starter-data-mongodb
- optional: true
- autoconfig: MongoAutoConfiguration
- usage: https://docs.spring.io/spring-data/data-mongodb/docs/1.6.x/reference/html/
## Thymeleaf
- starter: spring-boot-starter-thymeleaf
- optional: true
- autoconfig: ThymeleafAutoConfiguration
## Scheduled和Async
- config: AsyncConfiguration
- Scheduled
- @Scheduled(fixedRate = 5000): 上一次开始执行时间点之后5秒再执行
- @Scheduled(fixedDelay = 5000): 上一次执行完毕时间点之后5秒再执行
- @Scheduled(initialDelay=1000, fixedRate=5000): 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
- @Scheduled(cron="*/5 * * * * *"): 通过cron表达式定义规则
- Async
- 异步调用
- 异步回调: 使用Future
## Spring Security
使用Spring Security进行安全控制。
集成步骤:
- 导入依赖
```
org.springframework.boot
spring-boot-starter-security
```
- 配置Spring Security配置类`WebSecurityConfiguration`
使用说明:
- 可以使用注解@PreAuthorize来设置权限,利用内建的SPEL表达式:比如'hasRole()'来决定哪些角色有权访问,'hasAuthority()'来决定哪些权限有权访问。
- 在Spring Security中,默认有Role(角色)和Authority(权限)两种授权方式,实现的接口都是GrantedAuthority,角色仅仅是具有命名约定的权限,该命名约定说Role是以前缀ROLE_开头的Authority。
- 二者区别就是如果是hasAuthority判断,就是判断整个字符串,判断hasRole时,系统自动加上ROLE_到判断的Role字符串上,也就是说hasRole("CREATE")和hasAuthority('ROLE_CREATE')是相同的。
## Java Mail
- starter: spring-boot-starter-mail
- optional: true
- autoconfig: MailSenderAutoConfiguration
- example: MailService
## Cache
- starter: spring-boot-starter-cache
- optional: true
- config: @EnableCaching
Cache注解详解
- @CacheConfig: 主要用于配置该类中会用到的一些共用的缓存配置
- @Cacheable:
- @CachePut: 配置于函数上,能够根据参数定义条件来进行缓存,它与@Cacheable不同的是,它每次都会真是调用函数,所以主要用于数据新增和修改操作上。
- @CacheEvict: 配置于函数上,通常用在删除方法上,用来从缓存中移除相应数据。除了同@Cacheable一样的参数之外,它还有下面两个参数:
- allEntries: 非必需,默认为false。当为true时,会移除所有数据
- beforeInvocation: 非必需,默认为false,会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。
## Spring Session
- starter: none
- optional: true
- autoconfig: SessionAutoConfiguration
## 统一异常处理
Spring Boot原生错误处理接口ErrorController,默认使用BasicErrorController这个实现类来根据Accept头的内容,输出不同格式的错误响应。
## File upload
- autoconfig: MultipartAutoConfiguration
## Actuator(监控端点)
应用集成Actuator通过在应用maven中引入:
```
org.springframework.boot
spring-boot-starter-actuator
```
访问地址前缀根据`management.context-path`配置
下面介绍一下spring-boot-starter-actuator模块中已经实现的一些原生端点,原生端点分为三大类
- 应用配置类:获取应用程序中加载的应用配置、环境变量、自动化配置报告等与Spring Boot应用密切相关的配置类信息。
- 度量指标类:获取应用程序运行过程中用于监控的度量指标,比如:内存信息、线程池信息、HTTP请求统计等。
- 操作控制类:提供了对应用的关闭等操作类功能。
### 应用配置类
- /autoconfig:该端点用来获取应用的自动化配置报告,其中包括所有自动化配置的候选项。同时还列出了每个候选项自动化配置的各个先决条件是否满足。所以,该端点可以帮助我们方便的找到一些自动化配置为什么没有生效的具体原因。该报告内容将自动化配置内容分为两部分:
- positiveMatches中返回的是条件匹配成功的自动化配置
- negativeMatches中返回的是条件匹配不成功的自动化配置
- /beans:该端点用来获取应用上下文中创建的所有Bean。
- /configprops:该端点用来获取应用中配置的属性信息报告。
- /env:该端点与/configprops不同,它用来获取应用所有可用的环境属性报告。
- /mappings:该端点用来返回所有Spring MVC的控制器映射关系报告。
- /info:该端点用来返回一些应用自定义的信息。默认为空,在application.yml文件中通过info前缀设置,如info.app.version=v1.0.0
### 度量指标类
- /metrics:该端点用来返回当前应用的各类重要度量指标
- /health:该端点在一开始的示例中我们已经使用过了,它用来获取应用的各类健康指标信息。
- /dump:该端点用来暴露程序运行中的线程信息。
- /trace:该端点用来返回基本的HTTP跟踪信息。
### 操作控制类
在原生端点中,只提供了一个用来关闭应用的端点:/shutdown。
参考
- [Spring Boot Actuator监控端点小结](http://blog.didispace.com/spring-boot-actuator-1/)
---
# 第三方集成
## Swagger2
Swagger2是通用的接口文档方案,默认提供API的形式,通过集成`springfox-swagger-ui`可提供页面形式的接口文档。
集成步骤:
- swagger2 API:集成swagger2 API要在应用中配置spring.profiles.include包含swagger自动集成,通过`NovaframeProperties.Swagger`进行配置,集成后通过`/v2/api-docs`访问Swagger2 API
- swagger2 UI:集成swagger2 UI需要在应用的maven中引入如下依赖,访问地址为:`/swagger-ui.html`
```
io.springfox
springfox-swagger-ui
```
- optional: false
## Mybatis
集成Mybatis
- mybatis-spring-boot-starter
- mapper-spring-boot-starter
- pagehelper-spring-boot-starter
- optional: true
注解配置
```sql
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map map);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);
@Results({
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
@Select("SELECT name, age FROM user")
List findAll();
```
## AOP统一处理Web请求日志
引入AOP,使用@EnableAspectJAutoProxy来启用,其实默认已经启用:spring.aop.auto=true
```
org.springframework.boot
spring-boot-starter-aop
```
而当我们需要使用CGLIB来实现AOP的时候,需要配置spring.aop.proxy-target-class=true,不然默认使用的是标准Java的实现。
## Quartz
由于需要考虑任务的分布式调度,所以框架集成Quartz使用集群模式,使用数据库持久化任务。
集成步骤:
- 导入依赖
```
org.quartz-scheduler
quartz
```
- 使用[初始化脚本](https://github.com/elventear/quartz-scheduler/blob/master/distribution/src/main/assembly/root/docs/dbTables/tables_mysql.sql)初始化数据库
- 导入并修改配置文件`examples/quartz.properties`到`classpath:/quartz.properties`
- 实例化配置类`QuartzSchedulerConfiguration`
使用时提供rest接口来进行任务的查看和管理:
- 查看所有任务:/api/quartz/getAllJobs
- 添加任务:/api/quartz/addJob
- 暂停任务:/api/quartz/pauseJob
- 恢复任务:/api/quartz/resumeJob
- 删除任务:/api/quartz/deleteJob
- 立即执行任务:/api/quartz/runJob
添加任务:
- 写任务类
```java
@Component("schedulerManager")
public class SchedulerManager {
public void testSchedule() {
log.info("test Scheduler running...");
}
}
```
- 添加任务时的必填属性
- jobName: 任务名称
- jobGroup: 任务分组,任务名称+组名称应该是唯一的
- cronExpression: 调度表达式
- springId: 任务类的springId
- jobClass: 任务类类名,包含包
- methodName: 任务类的方法名
- optional: true
## JWT
### 单点登录流程
1. 使用用户名密码到认证系统登录并生成token
2. 把token以cookie的形式写回浏览器,此cookie是目标系统都可以公用的
3. 对资源系统进行请求,请求首先经过token filter检查是否已经单点登录
4. 已登录直接取出登录主体,未登录重定向到认证服务器的并带跳转地址
5. 认证服务器认证后跳回跳转地址
6. 登出处理:任意系统清除cookie
## Toolkit
- commons-lang3
- commons-beanutils
- commons-fileupload
- httpclient
- lombok
- mapstruct
---
# Properties
## Spring Boot properties
```
# see https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#appendix
# Redis
# spring-boot-starter-data-redis
Mybatis Reference Docs
- Mapper: https://github.com/abel533/Mapper
- Mybatis-PageHelper: https://github.com/pagehelper/Mybatis-PageHelper
```
## Novaframe properties
```
novaframe:
# Thread pool that will be used for asynchronous method calls
async:
core-pool-size: 2
max-pool-size: 50
queue-capacity: 10000
# HTTP configuration
http:
# V_1_1 for HTTP/1.1 or V_2_0 for HTTP/2.
# To use HTTP/2 you will need SSL support (see the Spring Boot "server.ssl" configuration)
version: V_1_1
cache: # Used by io.github.novaframe.web.filter.CachingHttpHeadersFilter
timeToLiveInDays: 1461 # Static assets are cached for 4 years by default
# By default CORS is disabled. Uncomment to enable.
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
# E-mail properties
mail:
from: jhipster@localhost # The default "from" address for e-mails
base-url: http://127.0.0.1:8080 # URL to the application, used inside e-mails
# Spring Security specific configuration
security:
remember-me: # JHipster secure implementation of the remember-me mechanism, for session-based authentication
# security key (this key should be unique for your application, and kept secret)
key: 0b32a651e6a65d5731e869dc136fb301b0a8c0e4
client-authorization: # Used with JHipster UAA authentication
access-token-uri: # URL of the JHipster UAA server OAuth tokens
token-service-id: # ID of the current application
client-id: # OAuth client ID
client-secret: # OAuth client secret
authentication:
jwt: # JHipster specific JWT implementation
secret: # JWT secret key
token-validity-in-seconds: 86400 # Token is valid 24 hours
token-validity-in-seconds-for-remember-me: 2592000 # Remember me token is valid 30 days
oauth: # Used by the JHipster OAuth 2 MongoDB specific implementation
client-id: # OAuth client ID
client-secret: # OAuth client secret
token-validity-in-seconds: 1800 # Token is valid 30 minutes
# Swagger configuration
swagger:
default-include-pattern: /api/.*
title: app API
description: app API documentation
version: 0.0.1
terms-of-service-url:
contact-name:
contact-url:
contact-email:
license:
license-url:
# Druid config
# before DruidAutoConfiguration, use DataSourceAutoConfiguration
druid:
url: jdbc:mysql://119.23.62.30:3306/test001
username: root
password: Root@123
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
# DropWizard Metrics configuration, used by MetricsConfiguration
metrics:
jmx: # Export metrics as JMX beans
enabled: true # JMX is enabled by default
# Send metrics to a Graphite server
# Use the "graphite" Maven profile to have the Graphite dependencies
graphite:
enabled: false # Graphite is disabled by default
host: localhost
port: 2003
prefix: jhipster
# Send metrics to a Prometheus server
# Use the "prometheus" Maven profile to have the Prometheus dependencies
prometheus:
enabled: false # Prometheus is disabled by default
endpoint: /prometheusMetrics
logs: # Reports Dropwizard metrics in the logs
enabled: false
reportFrequency: 60 # frequency of reports in seconds
# Logging configuration, used by LoggingConfiguration
logging:
logstash: # Forward logs to Logstash over a socket
enabled: false # Logstash is disabled by default
host: localhost # Logstash server URL
port: 5000 # Logstash server port
queue-size: 512 # Queue for buffering logs
spectator-metrics: # Reports Netflix Spectator metrics in the logs
enabled: false # Spectator is disabled by default
```