Commit 600d4ff0 authored by yanzg's avatar yanzg

修改实例化关系

parent e1f8e676
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
<fastjson.version>1.2.62</fastjson.version> <fastjson.version>1.2.62</fastjson.version>
<mysql.version>6.0.6</mysql.version> <mysql.version>6.0.6</mysql.version>
<poi.version>3.9</poi.version> <poi.version>3.9</poi.version>
<yzg.version>1.0-SNAPSHOT</yzg.version> <yzg.version>1.1-SNAPSHOT</yzg.version>
<swagger.version>2.9.2</swagger.version> <swagger.version>2.9.2</swagger.version>
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>
<!--<jetcache.version>2.6.0</jetcache.version>--> <!--<jetcache.version>2.6.0</jetcache.version>-->
......
package com.yanzuoguang.cloud;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.StringHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 整个模块的所有配置信息
*
* @author 颜佐光
*/
@Component
public class CloudConfig {
@Value("${spring.application.name}")
protected String applicationName;
@Value("${yzg.logCommon:false}")
protected boolean logCommon;
@Value("${yzg.logAll:false}")
protected boolean logAll = false;
@Value("${yzg.log.base:false}")
private boolean logBase;
@Value("${yzg.cacheTime:120}")
protected int cacheTime = 120;
@Value("${yzg.reqSize:5000}")
private int reqSize = 5000;
/**
* 1个请求最长时间(毫秒)
*/
@Value("${yzg.log.time.max:10000}")
private int logTimeMax;
/**
* 1个请求间隔记录时间(毫秒)
*/
@Value("${yzg.log.time.split:5000}")
private int logTimeSplit;
/**
* 日志不需要过滤的地址
*/
@Value("${yzg.log.logNotFilter:^.*login.*$}")
private String logNotFilter;
/**
* 日志需要过滤的地址
*/
@Value("${yzg.log.logFilter:^.*(log|yzg).*$}")
private String logFilter;
/**
* 服务器存储地址,注意权限
*/
@Value("${yzg.upload.server:}")
private String serverUrl;
/**
* 外网地址
*/
@Value("${yzg.upload.display:}")
private String displayUrl;
@Value("${yzg.gateway:^.*gateway.*$}")
private String gateWay;
public String getApplicationName() {
return applicationName;
}
public boolean isLogCommon() {
return logCommon;
}
public boolean isLogAll() {
return logAll;
}
public boolean isLogBase() {
return logBase;
}
public int getCacheTime() {
return cacheTime;
}
public int getReqSize() {
return reqSize;
}
public int getLogTimeMax() {
return logTimeMax;
}
public int getLogTimeSplit() {
return logTimeSplit;
}
public String getLogNotFilter() {
return logNotFilter;
}
public String getLogFilter() {
return logFilter;
}
public String getGateWay() {
return gateWay;
}
public String getServerUrl() {
if (StringHelper.isEmpty(this.serverUrl)) {
throw new CodeException("请配置yzg.upload.server");
}
return serverUrl;
}
public String getDisplayUrl() {
if (StringHelper.isEmpty(this.serverUrl)) {
throw new CodeException("请配置yzg.upload.display");
}
return displayUrl;
}
/**
* 是否属于网关服务,网关服务不进行监控
*
* @return
*/
public boolean isGateWay() {
return this.applicationName.toLowerCase().matches(this.gateWay);
}
}
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop;
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Channel;
import com.yanzuoguang.cloud.CloudConfig;
import com.yanzuoguang.cloud.aop.log.LogLocal;
import com.yanzuoguang.cloud.vo.YzgFileUploadReqVo; import com.yanzuoguang.cloud.vo.YzgFileUploadReqVo;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.ArrayHelper; import com.yanzuoguang.util.helper.ArrayHelper;
...@@ -13,9 +15,11 @@ import org.aspectj.lang.ProceedingJoinPoint; ...@@ -13,9 +15,11 @@ import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature; import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.core.Message; import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.*;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -34,28 +38,34 @@ import java.util.List; ...@@ -34,28 +38,34 @@ import java.util.List;
* *
* @author 颜佐光 * @author 颜佐光
*/ */
public class BaseRequestAspect { public class BaseRequestAspect implements ApplicationContextAware {
@Value("${spring.application.name}") protected LogLocal logLocal;
protected String applicationName;
@Value("${yzg.logCommon:false}") protected CloudConfig cloudConfig;
protected boolean logCommon;
@Value("${yzg.logAll:false}")
protected boolean logAll = false;
@Value("${yzg.cacheTime:120}")
protected int cacheTime = 120;
@Value("${yzg.reqSize:5000}")
private int reqSize = 5000;
@Autowired
private LogLocal logLocal;
private ResponseResult responseDefault = new ResponseResult(); private ResponseResult responseDefault = new ResponseResult();
/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.logLocal = applicationContext.getBean(LogLocal.class);
this.cloudConfig = applicationContext.getBean(CloudConfig.class);
}
/** /**
* 开始记录日志对象 * 开始记录日志对象
* *
...@@ -65,7 +75,7 @@ public class BaseRequestAspect { ...@@ -65,7 +75,7 @@ public class BaseRequestAspect {
* @return * @return
*/ */
protected LogVo startLog(String actionKey, String url, String body) { protected LogVo startLog(String actionKey, String url, String body) {
return this.logLocal.startLog(actionKey, String.format("%s:%s", this.applicationName, url), body); return this.logLocal.startLog(actionKey, String.format("%s:%s", this.cloudConfig.getApplicationName(), url), body);
} }
/** /**
...@@ -144,8 +154,8 @@ public class BaseRequestAspect { ...@@ -144,8 +154,8 @@ public class BaseRequestAspect {
* @return * @return
*/ */
private String getMaxString(String paraJson) { private String getMaxString(String paraJson) {
if (paraJson != null && paraJson.length() > reqSize) { if (paraJson != null && paraJson.length() > this.cloudConfig.getReqSize()) {
paraJson = paraJson.substring(0, reqSize); paraJson = paraJson.substring(0, this.cloudConfig.getReqSize());
} }
return paraJson; return paraJson;
} }
...@@ -175,7 +185,7 @@ public class BaseRequestAspect { ...@@ -175,7 +185,7 @@ public class BaseRequestAspect {
protected long requestLog(Class<?> cls, String tag, String url, String requestBody, boolean logFlag) { protected long requestLog(Class<?> cls, String tag, String url, String requestBody, boolean logFlag) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
boolean isLog = logFlag && logCommon; boolean isLog = logFlag && this.cloudConfig.isLogCommon();
if (isLog) { if (isLog) {
Log.info(cls, " %s [ %s ] request: %s", tag, url, this.getMaxString(requestBody)); Log.info(cls, " %s [ %s ] request: %s", tag, url, this.getMaxString(requestBody));
} }
...@@ -209,7 +219,7 @@ public class BaseRequestAspect { ...@@ -209,7 +219,7 @@ public class BaseRequestAspect {
log.setContentTo(requestBody); log.setContentTo(requestBody);
} }
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
boolean isLogDisplay = (logFlag && logCommon) || resultEx != null; boolean isLogDisplay = (logFlag && this.cloudConfig.isLogCommon()) || resultEx != null;
boolean isLogDatabase = log != null || resultEx != null; boolean isLogDatabase = log != null || resultEx != null;
// 处理结果 // 处理结果
ResponseResult responseResult = responseDefault; ResponseResult responseResult = responseDefault;
......
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.util.vo.LogVo; import com.yanzuoguang.cloud.aop.log.LogFeignBase;
import com.yanzuoguang.util.vo.ResponseResult;
/** /**
* 调用外置服务保存日志对象 * 调用外置服务保存日志对象
* *
* @author 颜佐光 * @author 颜佐光
*/ */
public interface LogFeign { public interface LogFeign extends LogFeignBase {
/**
* 保存日志对象
*
* @param log 需要保存的日志对象
* @return 日志服务返回结果
*/
ResponseResult<String> save(LogVo log);
} }
...@@ -14,9 +14,10 @@ import org.aspectj.lang.annotation.Around; ...@@ -14,9 +14,10 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.context.ApplicationContext; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.lang.reflect.Method; import java.lang.reflect.Method;
...@@ -34,19 +35,42 @@ public class WebAspect extends BaseRequestAspect { ...@@ -34,19 +35,42 @@ public class WebAspect extends BaseRequestAspect {
private static final String TAG = WebAspect.class.getSimpleName(); private static final String TAG = WebAspect.class.getSimpleName();
@Autowired
private TokenServiceCall tokenServiceCall; private TokenServiceCall tokenServiceCall;
@Value("${yzg.gateway:^.*gateway.*$}")
private String gateWay;
@Autowired
private ApplicationContext context;
/** /**
* 是否存在初始化方法 * 是否存在初始化方法
*/ */
private WebAssecptInit webAssecptInit; private WebAspectInit webAspectInit;
/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
super.setApplicationContext(applicationContext);
this.tokenServiceCall = applicationContext.getBean(TokenServiceCall.class);
try {
this.webAspectInit = applicationContext.getBean(WebAspectInit.class);
} catch (Exception ex) {
webAspectInit = new WebAspectInit() {
@Override
public void init(Object req) {
}
};
Log.error(WebAspect.class, "请设置登录默认处理函数");
Log.error(WebAspect.class, ex);
}
}
/** /**
* exec aop point aspect * exec aop point aspect
...@@ -55,7 +79,6 @@ public class WebAspect extends BaseRequestAspect { ...@@ -55,7 +79,6 @@ public class WebAspect extends BaseRequestAspect {
public void webAspect() { public void webAspect() {
} }
/** /**
* 执行环形切面 * 执行环形切面
* *
...@@ -65,7 +88,7 @@ public class WebAspect extends BaseRequestAspect { ...@@ -65,7 +88,7 @@ public class WebAspect extends BaseRequestAspect {
@Around(value = "webAspect()") @Around(value = "webAspect()")
public Object requestWebAround(ProceedingJoinPoint joinPoint) throws Throwable { public Object requestWebAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null; Object result = null;
boolean isGateWay = isGateWay(); boolean isGateWay = cloudConfig.isGateWay();
if (isGateWay) { if (isGateWay) {
result = executeMethod(joinPoint); result = executeMethod(joinPoint);
return result; return result;
...@@ -82,24 +105,11 @@ public class WebAspect extends BaseRequestAspect { ...@@ -82,24 +105,11 @@ public class WebAspect extends BaseRequestAspect {
Exception ex = null; Exception ex = null;
boolean isInit = false; boolean isInit = false;
try { try {
// 请求登录服务初始化
isInit = tokenServiceCall.tokenInit(); isInit = tokenServiceCall.tokenInit();
if (webAssecptInit == null) { // 初始化请求参数
try {
webAssecptInit = context.getBean(WebAssecptInit.class);
} catch (Exception e) {
webAssecptInit = new WebAssecptInit() {
@Override
public void init(Object req) {
}
};
Log.error(WebAspect.class, "请设置登录默认处理函数");
Log.error(WebAspect.class, e);
}
}
if (webAssecptInit != null) {
for (Object arg : joinPoint.getArgs()) { for (Object arg : joinPoint.getArgs()) {
webAssecptInit.init(arg); webAspectInit.init(arg);
}
} }
result = executeMethod(joinPoint); result = executeMethod(joinPoint);
return result; return result;
...@@ -116,10 +126,13 @@ public class WebAspect extends BaseRequestAspect { ...@@ -116,10 +126,13 @@ public class WebAspect extends BaseRequestAspect {
throw e; throw e;
} }
} finally { } finally {
// 登录服务最终处理
tokenServiceCall.tokenFinish(); tokenServiceCall.tokenFinish();
// 登录服务已经初始化则删除登录日志
if (isInit) { if (isInit) {
TokenHelper.remove(); TokenHelper.remove();
} }
// 获取最终的处理结果,写入到日志
try { try {
requestBody = getRequestBody(joinPoint); requestBody = getRequestBody(joinPoint);
} catch (Exception e) { } catch (Exception e) {
...@@ -128,15 +141,6 @@ public class WebAspect extends BaseRequestAspect { ...@@ -128,15 +141,6 @@ public class WebAspect extends BaseRequestAspect {
} }
} }
/**
* 是否属于网关服务,网关服务不进行监控
*
* @return
*/
private boolean isGateWay() {
return this.applicationName.toLowerCase().matches(this.gateWay);
}
/** /**
* 获取返回的至类型 * 获取返回的至类型
......
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop;
public interface WebAssecptInit { /**
*
* @author 颜佐光
*/
public interface WebAspectInit {
/** /**
* 对请求的数据初始化 * 对请求的数据初始化
......
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop.log;
import com.yanzuoguang.cloud.CloudConfig;
import com.yanzuoguang.cloud.aop.LogFeign;
import com.yanzuoguang.util.thread.ThreadNext; import com.yanzuoguang.util.thread.ThreadNext;
import com.yanzuoguang.util.vo.LogVo; import com.yanzuoguang.util.vo.LogVo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
/** /**
...@@ -16,19 +18,44 @@ import java.util.concurrent.LinkedBlockingQueue; ...@@ -16,19 +18,44 @@ import java.util.concurrent.LinkedBlockingQueue;
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
public class LogBase implements ThreadNext.Next, InitializingBean { public class LogBase implements ThreadNext.Next, InitializingBean, ApplicationContextAware {
/** /**
* 缓存队列 * 缓存队列
*/ */
protected volatile LinkedBlockingQueue<LogVo> cache = new LinkedBlockingQueue<>(); protected volatile LinkedBlockingQueue<LogVo> cache = new LinkedBlockingQueue<>();
@Autowired private CloudConfig cloudConfig;
protected List<LogFeign> logFeigns;
private LogFeign logFeign; private LogFeignBase logFeign;
@Value("${yzg.log.base:false}") /**
private boolean logBase; * Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.cloudConfig = applicationContext.getBean(CloudConfig.class);
// 获取个人实例话的对象
try {
this.logFeign = applicationContext.getBean(LogFeign.class);
} catch (Exception ex) {
System.err.println("请添加处理日志服务,实现LogFeign接口!");
}
// 默认实例话对象
if (this.logFeign == null) {
this.logFeign = applicationContext.getBean(LogFeignBase.class);
}
}
/** /**
* Invoked by a BeanFactory after it has set all bean properties supplied * Invoked by a BeanFactory after it has set all bean properties supplied
...@@ -42,8 +69,11 @@ public class LogBase implements ThreadNext.Next, InitializingBean { ...@@ -42,8 +69,11 @@ public class LogBase implements ThreadNext.Next, InitializingBean {
*/ */
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
// 判断是否要记录日志
if (cloudConfig.isLogBase()) {
ThreadNext.start(this, "save log error"); ThreadNext.start(this, "save log error");
} }
}
/** /**
* 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响 * 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响
...@@ -51,6 +81,10 @@ public class LogBase implements ThreadNext.Next, InitializingBean { ...@@ -51,6 +81,10 @@ public class LogBase implements ThreadNext.Next, InitializingBean {
* @param logVo * @param logVo
*/ */
public void addLog(LogVo logVo) { public void addLog(LogVo logVo) {
// 当不记录日志时,则直接忽略
if (!cloudConfig.isLogBase()) {
return;
}
cache.add(logVo); cache.add(logVo);
} }
...@@ -61,35 +95,25 @@ public class LogBase implements ThreadNext.Next, InitializingBean { ...@@ -61,35 +95,25 @@ public class LogBase implements ThreadNext.Next, InitializingBean {
* @throws Exception 异常信息 * @throws Exception 异常信息
*/ */
@Override @Override
public boolean next() throws Exception { public boolean next() {
if (!logBase) { if (cache.isEmpty()) {
cache.clear();
return true; return true;
} }
// 循环处理日志信息
if (logFeign == null) {
for (LogFeign log : logFeigns) {
if (log instanceof LogFeignDefault) {
if (logFeign == null) {
logFeign = log;
}
} else {
logFeign = log;
}
}
}
while (cache.size() > 0) { while (cache.size() > 0) {
// 取出一条日志
LogVo item = cache.poll(); LogVo item = cache.poll();
if (item != null) { // 判断日志信息是否为空
if (item == null) {
continue;
}
// 保存日志
try { try {
logFeign.save(item); logFeign.save(item);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
}
return true; return true;
} }
......
package com.yanzuoguang.cloud.aop.log;
import com.yanzuoguang.util.vo.LogVo;
import com.yanzuoguang.util.vo.ResponseResult;
/**
* 调用外置服务保存日志对象
*
* @author 颜佐光
*/
public interface LogFeignBase {
/**
* 保存日志对象
*
* @param log 需要保存的日志对象
* @return 日志服务返回结果
*/
ResponseResult<String> save(LogVo log);
}
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop.log;
import com.yanzuoguang.util.vo.LogVo; import com.yanzuoguang.util.vo.LogVo;
import com.yanzuoguang.util.vo.ResponseResult; import com.yanzuoguang.util.vo.ResponseResult;
...@@ -10,9 +10,7 @@ import org.springframework.stereotype.Component; ...@@ -10,9 +10,7 @@ import org.springframework.stereotype.Component;
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
public class LogFeignDefault implements LogFeign { public class LogFeignDefault implements LogFeignBase {
private boolean init = false;
/** /**
* 保存日志对象 * 保存日志对象
...@@ -22,10 +20,6 @@ public class LogFeignDefault implements LogFeign { ...@@ -22,10 +20,6 @@ public class LogFeignDefault implements LogFeign {
*/ */
@Override @Override
public ResponseResult<String> save(LogVo log) { public ResponseResult<String> save(LogVo log) {
if (!init) {
init = true;
System.err.println("请添加处理日志服务,实现LogFeign接口!");
}
return ResponseResult.result("处理成功"); return ResponseResult.result("处理成功");
} }
} }
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop.log;
import com.yanzuoguang.cloud.CloudConfig;
import com.yanzuoguang.cloud.aop.Timeout;
import com.yanzuoguang.util.helper.DateHelper; import com.yanzuoguang.util.helper.DateHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.thread.ThreadNext; import com.yanzuoguang.util.thread.ThreadNext;
import com.yanzuoguang.util.vo.LogVo; import com.yanzuoguang.util.vo.LogVo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.*; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* 当前线程日志编写 * 当前线程日志编写
...@@ -17,41 +24,42 @@ import java.util.*; ...@@ -17,41 +24,42 @@ import java.util.*;
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
public class LogLocal implements ThreadNext.Next, InitializingBean { public class LogLocal implements ThreadNext.Next, InitializingBean, ApplicationContextAware {
/**
* 超时状态
*/
public static final String MAX_TIME = "MAX_TIME";
public static final String MAX_TIME_NAME = "执行超时";
/** /**
* 缓存队列 * 缓存队列
*/ */
protected volatile Map<String, Timeout<LogVo>> cache = new Hashtable<>(); protected volatile Map<String, Timeout<LogVo>> cache = new ConcurrentHashMap<>();
/** /**
* 日志基础 * 日志基础
*/ */
@Autowired
private LogBase logBase; private LogBase logBase;
@Value("${spring.application.name}") private CloudConfig cloudConfig;
protected String applicationName;
/**
* 1个请求最长时间(毫秒)
*/
@Value("${yzg.log.time.max:10000}")
private int logTimeMax;
/**
* 1个请求间隔记录时间(毫秒)
*/
@Value("${yzg.log.time.split:5000}")
private int logTimeSplit;
@Value("${yzg.log.notFilter:^.*login.*$}")
private String notFilter;
@Value("${yzg.log.filter:^.*(log|yzg).*$}")
private String filter;
/** /**
* 超时状态 * Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/ */
public static final String MAX_TIME = "MAX_TIME"; @Override
public static final String MAX_TIME_NAME = "执行超时"; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
logBase = applicationContext.getBean(LogBase.class);
cloudConfig = applicationContext.getBean(CloudConfig.class);
}
/** /**
* Invoked by a BeanFactory after it has set all bean properties supplied * Invoked by a BeanFactory after it has set all bean properties supplied
...@@ -163,7 +171,7 @@ public class LogLocal implements ThreadNext.Next, InitializingBean { ...@@ -163,7 +171,7 @@ public class LogLocal implements ThreadNext.Next, InitializingBean {
*/ */
public boolean isLog(String... keys) { public boolean isLog(String... keys) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add(this.applicationName); list.add(this.cloudConfig.getApplicationName());
for (String item : keys) { for (String item : keys) {
list.add(item); list.add(item);
} }
...@@ -173,8 +181,8 @@ public class LogLocal implements ThreadNext.Next, InitializingBean { ...@@ -173,8 +181,8 @@ public class LogLocal implements ThreadNext.Next, InitializingBean {
boolean filter = false; boolean filter = false;
for (String item : list) { for (String item : list) {
String lower = item.toLowerCase(); String lower = item.toLowerCase();
notFilter = notFilter || lower.matches(this.notFilter); notFilter = notFilter || lower.matches(this.cloudConfig.getLogNotFilter());
filter = filter || lower.matches(this.filter); filter = filter || lower.matches(this.cloudConfig.getLogFilter());
} }
if (notFilter) { if (notFilter) {
return false; return false;
...@@ -194,7 +202,7 @@ public class LogLocal implements ThreadNext.Next, InitializingBean { ...@@ -194,7 +202,7 @@ public class LogLocal implements ThreadNext.Next, InitializingBean {
keys.addAll(cache.keySet()); keys.addAll(cache.keySet());
for (String key : keys) { for (String key : keys) {
Timeout<LogVo> timeout = cache.get(key); Timeout<LogVo> timeout = cache.get(key);
if (timeout == null || !timeout.isMaxTime(this.logTimeMax, this.logTimeSplit)) { if (timeout == null || !timeout.isMaxTime(this.cloudConfig.getLogTimeMax(), this.cloudConfig.getLogTimeSplit())) {
continue; continue;
} }
writeTimeout(timeout); writeTimeout(timeout);
......
package com.yanzuoguang.cloud.file; package com.yanzuoguang.cloud.file;
import com.yanzuoguang.util.vo.file.YzgFileBaseVo; import com.yanzuoguang.cloud.CloudConfig;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.FileHelper; import com.yanzuoguang.util.helper.FileHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import org.springframework.beans.factory.annotation.Value; import com.yanzuoguang.util.vo.file.YzgFileBaseVo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.File; import java.io.File;
/** /**
* 文件配置对象 * 颜佐光上传文件服务文件配置对象
*
* @author 颜佐光
*/ */
@Component @Component
public class YzgFileConfig { public class YzgFileConfig implements ApplicationContextAware {
/** private CloudConfig cloudConfig;
* 服务器存储地址,注意权限
*/
@Value("${yzg.upload.server:}")
private String serverUrl;
/** /**
* 外网地址 * Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/ */
@Value("${yzg.upload.display:}") @Override
private String displayUrl; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.cloudConfig = applicationContext.getBean(CloudConfig.class);
public String getServerUrl() {
if (StringHelper.isEmpty(this.serverUrl)) {
throw new CodeException("请配置yzg.upload.server");
}
return serverUrl;
}
public String getDisplayUrl() {
if (StringHelper.isEmpty(this.serverUrl)) {
throw new CodeException("请配置yzg.upload.display");
}
return displayUrl;
} }
/** /**
...@@ -49,7 +49,7 @@ public class YzgFileConfig { ...@@ -49,7 +49,7 @@ public class YzgFileConfig {
*/ */
public YzgFileBaseVo init(String serverFile) { public YzgFileBaseVo init(String serverFile) {
YzgFileBaseVo item = new YzgFileBaseVo(); YzgFileBaseVo item = new YzgFileBaseVo();
if(!StringHelper.isEmpty(serverFile)){ if (!StringHelper.isEmpty(serverFile)) {
init(item, serverFile); init(item, serverFile);
} }
return item; return item;
...@@ -66,9 +66,9 @@ public class YzgFileConfig { ...@@ -66,9 +66,9 @@ public class YzgFileConfig {
// 服务器相对路径 // 服务器相对路径
item.setServer(fromUrl); item.setServer(fromUrl);
// 对外显示全路径 // 对外显示全路径
item.setDisplay(getUrl(this.getDisplayUrl(), fromUrl)); item.setDisplay(getUrl(this.cloudConfig.getDisplayUrl(), fromUrl));
// 文件全路径 // 文件全路径
String serverFullPath = getUrl(this.getServerUrl(), fromUrl); String serverFullPath = getUrl(this.cloudConfig.getServerUrl(), fromUrl);
// 获取文件大小 // 获取文件大小
File file = new File(serverFullPath); File file = new File(serverFullPath);
if (file.exists()) { if (file.exists()) {
...@@ -86,8 +86,8 @@ public class YzgFileConfig { ...@@ -86,8 +86,8 @@ public class YzgFileConfig {
* @return * @return
*/ */
public String getServerPath(String fromUrl) { public String getServerPath(String fromUrl) {
String serverUrl = this.getServerUrl(); String serverUrl = this.cloudConfig.getServerUrl();
String displayUrl = this.getDisplayUrl(); String displayUrl = this.cloudConfig.getDisplayUrl();
// 处理serverFile为简写 // 处理serverFile为简写
if (fromUrl.startsWith(serverUrl)) { if (fromUrl.startsWith(serverUrl)) {
fromUrl = fromUrl.substring(serverUrl.length()); fromUrl = fromUrl.substring(serverUrl.length());
...@@ -106,7 +106,7 @@ public class YzgFileConfig { ...@@ -106,7 +106,7 @@ public class YzgFileConfig {
*/ */
public String getServerFullPath(String fromUrl) { public String getServerFullPath(String fromUrl) {
fromUrl = getServerPath(fromUrl); fromUrl = getServerPath(fromUrl);
return getUrl(this.getServerUrl(), fromUrl); return getUrl(this.cloudConfig.getServerUrl(), fromUrl);
} }
/** /**
...@@ -117,7 +117,7 @@ public class YzgFileConfig { ...@@ -117,7 +117,7 @@ public class YzgFileConfig {
*/ */
public String getDisplayPath(String fromUrl) { public String getDisplayPath(String fromUrl) {
fromUrl = getServerPath(fromUrl); fromUrl = getServerPath(fromUrl);
return getUrl(this.getDisplayUrl(), fromUrl); return getUrl(this.cloudConfig.getDisplayUrl(), fromUrl);
} }
private String getUrl(String folder, String fromUrl) { private String getUrl(String folder, String fromUrl) {
......
...@@ -6,8 +6,10 @@ import com.yanzuoguang.token.TokenLoad; ...@@ -6,8 +6,10 @@ import com.yanzuoguang.token.TokenLoad;
import com.yanzuoguang.util.cache.MemoryCache; import com.yanzuoguang.util.cache.MemoryCache;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log; import com.yanzuoguang.util.log.Log;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
...@@ -16,34 +18,36 @@ import org.springframework.stereotype.Component; ...@@ -16,34 +18,36 @@ import org.springframework.stereotype.Component;
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
public class TokenServiceCall implements TokenLoad { public class TokenServiceCall implements TokenLoad, ApplicationContextAware {
@Autowired
private ApplicationContext context;
private TokenService tokenService = null; private TokenService tokenService = null;
private int flagCount = 1;
private MemoryCache<Integer> countCache = new MemoryCache<>(); private MemoryCache<Integer> countCache = new MemoryCache<>();
public TokenServiceCall() { public TokenServiceCall() {
TokenHelper.setTokenLoad(this); TokenHelper.setTokenLoad(this);
} }
private void init() { /**
if (tokenService != null) { * Set the ApplicationContext that this object runs in.
return; * Normally this call will be used to initialize the object.
} * <p>Invoked after population of normal bean properties but before an init callback such
if (flagCount < 1) { * as {@link InitializingBean#afterPropertiesSet()}
return; * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
} * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
try { try {
tokenService = context.getBean(TokenService.class); tokenService = applicationContext.getBean(TokenService.class);
} catch (Exception ex) { } catch (Exception ex) {
Log.error(TokenServiceCall.class, "获取登录服务失败:" + ex.getMessage(), ex); Log.error(TokenServiceCall.class, "获取登录服务失败:" + ex.getMessage(), ex);
} finally {
flagCount--;
} }
} }
...@@ -51,7 +55,6 @@ public class TokenServiceCall implements TokenLoad { ...@@ -51,7 +55,6 @@ public class TokenServiceCall implements TokenLoad {
* 请求时初始化token * 请求时初始化token
*/ */
public boolean tokenInit() { public boolean tokenInit() {
init();
if (tokenService == null) { if (tokenService == null) {
return false; return false;
} }
...@@ -66,7 +69,6 @@ public class TokenServiceCall implements TokenLoad { ...@@ -66,7 +69,6 @@ public class TokenServiceCall implements TokenLoad {
* 请求时结束token * 请求时结束token
*/ */
public void tokenFinish() { public void tokenFinish() {
init();
if (tokenService == null) { if (tokenService == null) {
return; return;
} }
...@@ -83,7 +85,6 @@ public class TokenServiceCall implements TokenLoad { ...@@ -83,7 +85,6 @@ public class TokenServiceCall implements TokenLoad {
*/ */
@Override @Override
public TokenData load(String token) { public TokenData load(String token) {
init();
if (tokenService == null) { if (tokenService == null) {
return null; return null;
} }
......
...@@ -2,6 +2,7 @@ package com.yanzuoguang.code; ...@@ -2,6 +2,7 @@ package com.yanzuoguang.code;
import com.yanzuoguang.dao.DaoConst; import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.util.helper.ByteHelper; import com.yanzuoguang.util.helper.ByteHelper;
import org.springframework.stereotype.Component;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
...@@ -13,6 +14,7 @@ import java.util.Random; ...@@ -13,6 +14,7 @@ import java.util.Random;
* *
* @author 颜佐光 * @author 颜佐光
*/ */
@Component
public class CodePwdImpl implements CodePwd { public class CodePwdImpl implements CodePwd {
/** /**
......
...@@ -28,11 +28,4 @@ public @interface TableAnnotation { ...@@ -28,11 +28,4 @@ public @interface TableAnnotation {
* @return * @return
*/ */
int type() default DaoConst.FIELD_NONE; int type() default DaoConst.FIELD_NONE;
/**
* 包含的Sql语句,会根据SQL语句名称替换默认的SQL语句
*
* @return
*/
Class[] sql() default {};
} }
package com.yanzuoguang.extend; package com.yanzuoguang.db;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/** /**
* 打印SQL日志 * 打印SQL日志
*
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
...@@ -19,7 +24,6 @@ public class ConfigDb { ...@@ -19,7 +24,6 @@ public class ConfigDb {
*/ */
@Value("${yzg.PrintSql:false}") @Value("${yzg.PrintSql:false}")
private boolean printSql; private boolean printSql;
/** /**
* 判断是否匹配过滤 * 判断是否匹配过滤
*/ */
...@@ -29,6 +33,10 @@ public class ConfigDb { ...@@ -29,6 +33,10 @@ public class ConfigDb {
@Value("${yzg.row.name.type:0}") @Value("${yzg.row.name.type:0}")
private int rowNameType; private int rowNameType;
@Resource
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbc;
public boolean isPrintMapper() { public boolean isPrintMapper() {
return printMapper; return printMapper;
} }
...@@ -44,4 +52,8 @@ public class ConfigDb { ...@@ -44,4 +52,8 @@ public class ConfigDb {
public int getRowNameType() { public int getRowNameType() {
return rowNameType; return rowNameType;
} }
public JdbcTemplate getJdbc() {
return jdbc;
}
} }
...@@ -2,7 +2,7 @@ package com.yanzuoguang.db.impl; ...@@ -2,7 +2,7 @@ package com.yanzuoguang.db.impl;
import com.yanzuoguang.dao.DaoConst; import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.TableAnnotation; import com.yanzuoguang.dao.TableAnnotation;
import com.yanzuoguang.extend.ConfigDb; import com.yanzuoguang.db.ConfigDb;
import com.yanzuoguang.util.base.MethodField; import com.yanzuoguang.util.base.MethodField;
import com.yanzuoguang.util.base.ObjectHelper; import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
......
package com.yanzuoguang.db.impl; package com.yanzuoguang.db.impl;
import com.yanzuoguang.db.ConfigDb;
import com.yanzuoguang.db.DbExecute; import com.yanzuoguang.db.DbExecute;
import com.yanzuoguang.extend.ConfigDb;
import com.yanzuoguang.util.vo.MapRow; import com.yanzuoguang.util.vo.MapRow;
import com.yanzuoguang.util.vo.Ref; import com.yanzuoguang.util.vo.Ref;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -22,18 +24,32 @@ import java.util.List; ...@@ -22,18 +24,32 @@ import java.util.List;
* @author 颜佐光 * @author 颜佐光
*/ */
@Component @Component
public class DbExecuteImpl implements DbExecute { public class DbExecuteImpl implements DbExecute, ApplicationContextAware {
@Resource
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbc;
@Resource
private DbPrintSql printSql; private DbPrintSql printSql;
@Resource
private ConfigDb configDb; private ConfigDb configDb;
/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
*
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see BeanInitializationException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.printSql = applicationContext.getBean(DbPrintSql.class);
this.configDb = applicationContext.getBean(ConfigDb.class);
}
/** /**
* 更新SQL语句的执行 * 更新SQL语句的执行
* *
...@@ -49,7 +65,7 @@ public class DbExecuteImpl implements DbExecute { ...@@ -49,7 +65,7 @@ public class DbExecuteImpl implements DbExecute {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
sql = this.handleParas(sql, paras); sql = this.handleParas(sql, paras);
row = jdbc.update(sql, paras); row = this.getJdbc().update(sql, paras);
return row; return row;
} finally { } finally {
printSql.print(targetClass, sqlName, start, row, sql, paras); printSql.print(targetClass, sqlName, start, row, sql, paras);
...@@ -83,8 +99,7 @@ public class DbExecuteImpl implements DbExecute { ...@@ -83,8 +99,7 @@ public class DbExecuteImpl implements DbExecute {
row.value++; row.value++;
} }
}; };
this.getJdbc().query(sql, rowCallbackHandler, paras);
jdbc.query(sql, rowCallbackHandler, paras);
} finally { } finally {
printSql.print(targetClass, sqlName, start, row.value, sql, paras); printSql.print(targetClass, sqlName, start, row.value, sql, paras);
} }
...@@ -108,7 +123,7 @@ public class DbExecuteImpl implements DbExecute { ...@@ -108,7 +123,7 @@ public class DbExecuteImpl implements DbExecute {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
sql = this.handleParas(sql, paras); sql = this.handleParas(sql, paras);
List<T> ret = jdbc.query(sql, paras, AllBeanRowMapper.getInstance(cls, configDb)); List<T> ret = this.getJdbc().query(sql, paras, AllBeanRowMapper.getInstance(cls, configDb));
if (ret == null) { if (ret == null) {
ret = new ArrayList<T>(); ret = new ArrayList<T>();
} }
...@@ -148,7 +163,7 @@ public class DbExecuteImpl implements DbExecute { ...@@ -148,7 +163,7 @@ public class DbExecuteImpl implements DbExecute {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
sql = this.handleParas(sql, paras); sql = this.handleParas(sql, paras);
SqlRowSet rowSet = jdbc.queryForRowSet(sql, paras); SqlRowSet rowSet = this.getJdbc().queryForRowSet(sql, paras);
while (rowSet.next()) { while (rowSet.next()) {
row = 1; row = 1;
return rowSet.getObject(1); return rowSet.getObject(1);
...@@ -175,4 +190,7 @@ public class DbExecuteImpl implements DbExecute { ...@@ -175,4 +190,7 @@ public class DbExecuteImpl implements DbExecute {
.replaceAll("(?i)GROUP\\s*?(?i)BY\\s*?1\\s*?", ""); .replaceAll("(?i)GROUP\\s*?(?i)BY\\s*?1\\s*?", "");
} }
private JdbcTemplate getJdbc() {
return configDb.getJdbc();
}
} }
package com.yanzuoguang.db.impl; package com.yanzuoguang.db.impl;
import com.yanzuoguang.extend.ConfigDb; import com.yanzuoguang.db.ConfigDb;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log; import com.yanzuoguang.util.log.Log;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment