切点知识点
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
@Aspect:作用是把当前类标识为一个切面供容器读取
@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
@Around:环绕增强,相当于MethodInterceptor
@AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
@Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
@AfterThrowing:异常抛出增强,相当于ThrowsAdvice
@After: final增强,不管是抛出异常或者正常退出都会执行
/**
* 操作日志记录处理
*
* @author jxmodel
*/
@Aspect
@Component
public class LogAspect {
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
// 配置织入点
@Pointcut("execution(* com.gzjgtymh.core.controller.*.*(..))")
public void logPointCut() {
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
// 获得注解
// ClassDefine classDefine = getAnnotationLog(joinPoint);
// if (classDefine == null) {
// return;
// }
// 获取当前的用户
JPaasUser loginUser = SysUserUtil.getLoginUser();
// *========数据库日志=========*//
SystemLog log = new SystemLog();
SystemAppLog appLog = new SystemAppLog();
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
log.setIp(ip);
// 返回参数
log.setDetail("参数:"+JSON.toJSONString(jsonResult));
log.setAction(ServletUtils.getRequest().getRequestURI());
appLog.setUrl(ServletUtils.getRequest().getRequestURI());
appLog.setAppName("统一门户");
if (loginUser != null) {
log.setUserName(loginUser.getUsername());
log.setCreateBy(loginUser.getUserId());
log.setCreateDepId(loginUser.getDeptId());
appLog.setCreateBy(loginUser.getUserId());
appLog.setCreateDepId(loginUser.getDeptId());
}
if (e != null) {
handleErrorLog(joinPoint,e,jsonResult,loginUser);
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
log.setClassName(className + "." + methodName + "()");
// 设置请求方式
appLog.setMethod(ServletUtils.getRequest().getMethod());
// 处理设置注解上的参数
// 设置标题
// log.setModule(classDefine.title());
// 保存数据库
AsyncManager.me().execute(AsyncFactory.recordLog(log));
AsyncManager.me().execute(AsyncFactory.recordAppLog(appLog));
} catch (Exception exp) {
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
protected void handleErrorLog(final JoinPoint joinPoint, final Exception e, Object jsonResult,JPaasUser loginUser) {
try {
// 获得注解
// ClassDefine classDefine = getAnnotationLog(joinPoint);
// if (classDefine == null) {
// return;
// }
// *========数据库日志=========*//
SystemErrorLog log = new SystemErrorLog();
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
log.setIp(ip);
// 返回参数
log.setAppName("统一门户");
log.setUrl(ServletUtils.getRequest().getRequestURI());
if (loginUser != null) {
log.setCreateBy(loginUser.getUserId());
log.setCreateDepId(loginUser.getDeptId());
}
log.setContent(StringUtils.substring(e.getMessage(), 0, 2000));
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
// 保存数据库
AsyncManager.me().execute(AsyncFactory.recordErrorLog(log));
} catch (Exception exp) {
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 是否存在注解,如果存在就获取
*/
private ClassDefine getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(ClassDefine.class);
}
return null;
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (int i = 0; i < paramsArray.length; i++) {
if (!isFilterObject(paramsArray[i])) {
Object jsonObj = JSON.toJSON(paramsArray[i]);
params += jsonObj.toString() + " ";
}
}
}
return params.trim();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
public boolean isFilterObject(final Object o) {
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
}
}
线程池配置
package com.gzjgtymh.config;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
*
* @author jxmodel
**/
@Configuration
public class ThreadPoolConfig
{
// 核心线程池大小
private int corePoolSize = 50;
// 最大可创建的线程数
private int maxPoolSize = 200;
// 队列最大长度
private int queueCapacity = 1000;
// 线程池维护线程所允许的空闲时间
private int keepAliveSeconds = 300;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(maxPoolSize);
executor.setCorePoolSize(corePoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
// 线程池对拒绝任务(无线程可用)的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService()
{
return new ScheduledThreadPoolExecutor(corePoolSize,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())
{
@Override
protected void afterExecute(Runnable r, Throwable t)
{
super.afterExecute(r, t);
}
};
}
}
异步工厂
package com.gzjgtymh.util;
import com.gzjgtymh.core.entity.SystemAppLog;
import com.gzjgtymh.core.entity.SystemErrorLog;
import com.gzjgtymh.core.entity.SystemLog;
import com.gzjgtymh.core.service.SystemAppLogServiceImpl;
import com.gzjgtymh.core.service.SystemErrorLogServiceImpl;
import com.gzjgtymh.core.service.SystemLogServiceImpl;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.TimerTask;
/**
* 异步工厂(产生任务用)
*
* @author jxmodel
*/
public class AsyncFactory
{
private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");
/**
* 操作日志记录
*
*
* @param log 操作日志信息
* @return 任务task
*/
public static TimerTask recordLog( final SystemLog log)
{
return new TimerTask()
{
@Override
public void run()
{
// 远程查询操作地点
SpringUtils.getBean(SystemLogServiceImpl.class).insertLog( log);
}
};
}
/**
* error记录
*
*
* @param log 操作日志信息
* @return 任务task
*/
public static TimerTask recordErrorLog( final SystemErrorLog log)
{
return new TimerTask()
{
@Override
public void run()
{
// 远程查询操作地点
SpringUtils.getBean(SystemErrorLogServiceImpl.class).insertLog( log);
}
};
}
/**
* app记录
*
*
* @param log 操作日志信息
* @return 任务task
*/
public static TimerTask recordAppLog( final SystemAppLog log)
{
return new TimerTask()
{
@Override
public void run()
{
// 远程查询操作地点
SpringUtils.getBean(SystemAppLogServiceImpl.class).insertLog( log);
}
};
}
}
异步管理器,单例
package com.gzjgtymh.util;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 异步任务管理器
*
* @author jxmodel
*/
public class AsyncManager
{
/**
* 操作延迟10毫秒
*/
private final int OPERATE_DELAY_TIME = 10;
/**
* 异步操作任务调度线程池
*/
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
/**
* 单例模式
*/
private AsyncManager(){}
private static AsyncManager me = new AsyncManager();
public static AsyncManager me()
{
return me;
}
/**
* 执行任务
*
* @param task 任务
*/
public void execute(TimerTask task)
{
executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
}
/**
* 停止任务线程池
*/
public void shutdown()
{
Threads.shutdownAndAwaitTermination(executor);
}
}