Skip to content

Commit

Permalink
Merge branch '3.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
keray committed Aug 19, 2020
2 parents f1ce219 + db7a0b5 commit 29774bc
Show file tree
Hide file tree
Showing 40 changed files with 1,454 additions and 643 deletions.
4 changes: 2 additions & 2 deletions common.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ create table sys_config
type int default 1 null comment '配置类型',
config_desc varchar(256) null comment '描述'
)
comment '系统配置(v3)' charset = utf8;
comment '系统配置(v3)' charset = utf8mb4;

create index sys_config__index_key
on sys_config (`key`);
Expand All @@ -40,7 +40,7 @@ create table sys_schedule
plat_exec_time datetime null comment '计划执行时间',
schedule_desc varchar(256) null comment '任务描述'
)
comment '系统分布式任务(v3)';
comment '系统分布式任务(v3)' charset = utf8mb4;

create index index_status
on sys_schedule (status);
Expand Down
3 changes: 2 additions & 1 deletion common/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ keray:
global-switch: # 全局开启json解析
data: true # 接口qps配置
time: true # 接口时长统计

log:
all: true #api日志
```
## cache使用
Expand Down
11 changes: 11 additions & 0 deletions common/src/main/java/com/keray/common/BEntity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.keray.common;

import com.baomidou.mybatisplus.extension.activerecord.Model;

/**
* @author by keray
* date:2020/7/15 9:38 上午
*/
public class BEntity<B extends BEntity<B>> extends Model<B> implements IBEntity<B>{

}
9 changes: 9 additions & 0 deletions common/src/main/java/com/keray/common/IBEntity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.keray.common;

/**
* @author by keray
* date:2020/7/15 9:38 上午
*/
public interface IBEntity<B extends IBEntity<B>> {

}
117 changes: 117 additions & 0 deletions common/src/main/java/com/keray/common/IBMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.keray.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.TypeUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author by keray
* date:2019/7/25 16:56
*/
public interface IBMapper<B extends IBEntity<B>> extends BaseMapper<B> {

/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
* @return
*/
@Override
int update(@Param(Constants.ENTITY) B entity, @Param(Constants.WRAPPER) Wrapper<B> updateWrapper);

/**
* <p>
* <h3>作者 keray</h3>
* <h3>时间: 2019/10/24 17:43</h3>
* 查询sum
* </p>
*
* @param wrapper
* @return <p> {@link String} </p>
* @throws
*/
Double selectSum(@Param(Constants.WRAPPER) Wrapper<B> wrapper);

/**
* 插入一条记录
*
* @param entity 实体对象
* @return
*/
@Override
int insert(B entity);


/**
* <p>
* 插入(批量)
* </p>
*
* @param entityList 实体对象列表
* @param batchSize 插入批次数量
* @return boolean
*/
@Transactional(rollbackFor = Exception.class)
default boolean insertBatch(List<B> entityList, int batchSize) {
if (CollUtil.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
for (int i = 0; i < size; i++) {
batchSqlSession.insert(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
}
return true;
}


default boolean exits(Wrapper<B> wrapper) {
return selectCount(wrapper) > 0;
}
/**
* <p>
* 批量操作 SqlSession
* </p>
*/
default SqlSession sqlSessionBatch() {
return SqlHelper.sqlSessionBatch(currentModelClass());
}
/**
* 获取SqlStatement
*
* @param sqlMethod 方法
* @return String
*/
default String sqlStatement(SqlMethod sqlMethod) {
return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
}

/**
* <p>
* 获取当前class
* </p>
*/
default Class<B> currentModelClass() {
return (Class<B>) TypeUtil.getTypeArgument(this.getClass().getInterfaces()[0].getGenericInterfaces()[0]);
}

}
13 changes: 13 additions & 0 deletions common/src/main/java/com/keray/common/IBSEntity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.keray.common;

import java.io.Serializable;

/**
* @author by keray
* date:2020/7/15 9:39 上午
*/
public interface IBSEntity<BS extends IBSEntity<BS, ID>, ID extends Serializable> extends IBEntity<BS> {
ID getId();

void setId(ID id);
}
65 changes: 65 additions & 0 deletions common/src/main/java/com/keray/common/IBSMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.keray.common;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.ibatis.annotations.Param;

import java.io.Serializable;
import java.util.Collection;

/**
* @author by keray
* date:2020/7/15 9:39 上午
*/
public interface IBSMapper<BS extends IBSEntity<BS, ID>, ID extends Serializable> extends IBMapper<BS> {

/**
* 插入一条记录
*
* @param entity 实体对象
* @return
*/
@Override
int insert(BS entity);

/**
* 根据 ID 修改
*
* @param entity 实体对象
* @return
*/
@Override
int updateById(@Param(Constants.ENTITY) BS entity);


@Override
BS selectById(Serializable id);

default boolean contains(String id) {
return selectCount(Wrappers.<BS>query().eq("id", id)) == 1;
}

/**
* 删除(根据ID 批量删除)
*
* @param id 主键ID列表(不能为 null 以及 empty)
*/
@Override
default int deleteById(Serializable id) {
return this.delete(Wrappers.<BS>update().eq("id", id));
}

/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
@Override
default int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList) {
return this.delete(Wrappers.<BS>update().in("id", idList));
}

default Boolean canDelete(@Param("ids") Collection<? extends Serializable> ids) {
return true;
}
}
2 changes: 1 addition & 1 deletion common/src/main/java/com/keray/common/SysThreadPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* date:2019/9/16 11:49
*/
public class SysThreadPool {
private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 1000, 10,
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 1000, 10,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10000000),
r -> {
Thread t = new Thread(r);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.keray.common.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.keray.common.IBaseEntity;
import com.keray.common.Result;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Consumer;

/**
* @author by keray
* date:2020/6/3 10:08 上午
*/
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "api.log")
public class ApiLogServletInvocableHandlerMethodHandler implements ServletInvocableHandlerMethodHandler {

@Getter
@Setter
private Boolean all = false;

@Override
public Integer order() {
return 0;
}

@Override
public Object work(HandlerMethod handlerMethod, Object[] args, NativeWebRequest request, ServletInvocableHandlerMethodCallback callback) throws Exception {
long start = System.nanoTime();
for (Object o : args) {
if (o instanceof IBaseEntity) {
((IBaseEntity) o).clearBaseField();
}
}
Consumer<Object> logFail = result -> {
try {
if (result instanceof Result.FailResult || result instanceof Exception || all) {
String url = null;
String flag = null;
try {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
if (servletRequest != null) {
url = servletRequest.getRequestURL().toString();
if (StrUtil.isBlank(url)) {
url = "错误";
}
flag = servletRequest.getHeader("X-User-Agent");
if (StrUtil.isBlank(flag)) {
flag = servletRequest.getHeader("User-Agent");
}
if (StrUtil.isBlank(flag)) {
flag = "未知";
}
}
} catch (Exception e) {
e.printStackTrace();
}
apiLog(result instanceof Result.FailResult || result instanceof Exception, result, url, flag, args, handlerMethod.getMethodParameters(), start);
}
} catch (Exception e) {
e.printStackTrace();
}
};
try {
Object result = callback.get();
logFail.accept(result);
return result;
} catch (Exception e) {
logFail.accept(e);
throw e;
}
}

private void apiLog(boolean fail, Object result, String url, String flag, Object[] args, MethodParameter[] parameters, long start) {
StringBuilder builder = new StringBuilder();
if (fail) {
builder.append(System.lineSeparator()).append("============接口异常============").append(System.lineSeparator());
} else {
builder.append(System.lineSeparator()).append("============api start============").append(System.lineSeparator());
}
builder.append(" flag:").append(flag).append(System.lineSeparator());
builder.append(" url:").append(url).append(System.lineSeparator());
builder.append(" args:").append(System.lineSeparator());
for (int i = 0; i < parameters.length; i++) {
String json = "json解析失败";
try {
json = args[i] == null ? null : JSON.toJSONString(args[i]);
} catch (Exception ignore) {
}
builder.append(parameters[i].getParameterName()).append("=").append(json).append(System.lineSeparator());
}
if (result instanceof Result.FailResult) {
builder.append("result:").append(StrUtil.format("code={},message={}", ((Result) result).getCode(), ((Result.FailResult) result).getMessage())).append(System.lineSeparator());
} else if (result instanceof Result.SuccessResult){
builder.append("result:").append(JSON.toJSONString(((Result.SuccessResult) result).getData())).append(System.lineSeparator());
} else {
builder.append("result:").append(result.getClass()).append(System.lineSeparator());
}
builder.append(String.format("============end time=ns:%s ============",System.nanoTime() - start));
builder.append(System.lineSeparator());
if (fail) {
log.error(builder.toString());
} else {
log.info(builder.toString());
}
}
}
Loading

0 comments on commit 29774bc

Please sign in to comment.