Skip to content

Commit

Permalink
1.日志改为异步保存
Browse files Browse the repository at this point in the history
2.优化ajax遮挡层
3.日志按天输出
  • Loading branch information
lcg0124 committed Feb 4, 2018
1 parent e4a5ba4 commit d846290
Show file tree
Hide file tree
Showing 15 changed files with 242 additions and 183 deletions.
6 changes: 1 addition & 5 deletions bootdo/src/main/java/com/bootdo/BootdoApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.bootdo.*.dao")
Expand All @@ -21,8 +21,4 @@ public static void main(String[] args) {
" _| |__) || \\__. || \\__. || |, _| |_.' /| \\__. | \n" +
"|_______/ '.__.' '.__.' \\__/|______.' '.__.' ");
}




}
125 changes: 64 additions & 61 deletions bootdo/src/main/java/com/bootdo/common/aspect/LogAspect.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@

import javax.servlet.http.HttpServletRequest;

import com.bootdo.common.service.LogService;
import com.bootdo.system.domain.UserToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.bootdo.common.annotation.Log;
Expand All @@ -29,70 +31,71 @@
@Aspect
@Component
public class LogAspect {
@Autowired
LogDao logMapper;

@Pointcut("@annotation(com.bootdo.common.annotation.Log)")
public void logPointCut() {
}
@Autowired
LogService logService;

@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point, time);
@Pointcut("@annotation(com.bootdo.common.annotation.Log)")
public void logPointCut() {
}

return result;
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point, time);
return result;
}

private void saveLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogDO sysLog = new LogDO();
Log syslog = method.getAnnotation(Log.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {
@Async
void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogDO sysLog = new LogDO();
Log syslog = method.getAnnotation(Log.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) {

}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 用户名
UserDO currUser = ShiroUtils.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserId(-1L);
sysLog.setUsername(sysLog.getParams());
} else {
sysLog.setUserId(-1L);
sysLog.setUsername("获取用户信息为空");
}
} else {
sysLog.setUserId(ShiroUtils.getUserId());
sysLog.setUsername(ShiroUtils.getUser().getUsername());
}
sysLog.setTime((int) time);
// 系统当前时间
Date date = new Date();
sysLog.setGmtCreate(date);
// 保存系统日志
logMapper.save(sysLog);
}
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 用户名
UserDO currUser = ShiroUtils.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserId(-1L);
sysLog.setUsername(sysLog.getParams());
} else {
sysLog.setUserId(-1L);
sysLog.setUsername("获取用户信息为空");
}
} else {
sysLog.setUserId(ShiroUtils.getUserId());
sysLog.setUsername(ShiroUtils.getUser().getUsername());
}
sysLog.setTime((int) time);
// 系统当前时间
Date date = new Date();
sysLog.setGmtCreate(date);
// 保存系统日志
logService.save(sysLog);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.bootdo.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableAsync
public class SpringAsyncConfig {
@Bean
public AsyncTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(10);
return executor;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ public R handleDuplicateKeyException(DuplicateKeyException e) {
@ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class)
public R noHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException e) {
logger.error(e.getMessage(), e);
return R.error("没找找到页面");
return R.error(404,"没找找到页面");
}

@ExceptionHandler(AuthorizationException.class)
public R handleAuthorizationException(AuthorizationException e) {
logger.error(e.getMessage(), e);
return R.error("未授权");
return R.error(403,"未授权");
}

@ExceptionHandler(Exception.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class MainsiteErrorController implements ErrorController {

@RequestMapping(value = ERROR_PATH)
public String handleError() {
return "error/404";
return "error/500";
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.bootdo.common.utils.Query;
@Service
public interface LogService {
void save(LogDO logDO);
PageDO<LogDO> queryList(Query query);
int remove(Long id);
int batchRemove(Long[] ids);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.bootdo.common.dao.LogDao;
Expand All @@ -10,12 +11,17 @@
import com.bootdo.common.service.LogService;
import com.bootdo.common.utils.Query;

@SuppressWarnings("AlibabaRemoveCommentedCode")
@Service
public class LogServiceImpl implements LogService {
@Autowired
LogDao logMapper;

@Async
@Override
public void save(LogDO logDO) {
logMapper.save(logDO);
}

@Override
public PageDO<LogDO> queryList(Query query) {
int total = logMapper.count(query);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,20 @@ public int save(NotifyDO notify) {
}
recordDao.batchSave(records);
//给在线用户发送通知
// ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,0, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>());
// executor.execute(new Runnable() {
// @Override
// public void run() {
// for (UserDO userDO : sessionService.listOnlineUser()) {
// for (Long userId : userIds) {
// if (userId.equals(userDO.getUserId())) {
// template.convertAndSendToUser(userDO.toString(), "/queue/notifications", "新消息:" + notify.getTitle());
// }
// }
// }
// }
// });
// executor.shutdown();
ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,0, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>());
executor.execute(new Runnable() {
@Override
public void run() {
for (UserDO userDO : sessionService.listOnlineUser()) {
for (Long userId : userIds) {
if (userId.equals(userDO.getUserId())) {
template.convertAndSendToUser(userDO.toString(), "/queue/notifications", "新消息:" + notify.getTitle());
}
}
}
}
});
executor.shutdown();
return r;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public class ShiroConfig {
@Value("${cacheType}")
private String cacheType;

@Value("${server.session-timeout}")
private int tomcatTimeout;

@Bean
public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
Expand Down Expand Up @@ -168,6 +171,7 @@ public SessionDAO sessionDAO(){
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setGlobalSessionTimeout(tomcatTimeout*1000);
sessionManager.setSessionDAO(sessionDAO());
Collection<SessionListener> listeners = new ArrayList<SessionListener>();
listeners.add(new BDSessionListener());
Expand Down
31 changes: 31 additions & 0 deletions bootdo/src/main/resources/logback-spring.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>logback</contextName>
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<!--按天生成日志-->
<appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<Prudent>true</Prudent>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>
applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log
</FileNamePattern>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} -%msg%n
</Pattern>
</layout>
</appender>

<logger name="com.bootdo" additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="logFile" />
</logger>

</configuration>
30 changes: 0 additions & 30 deletions bootdo/src/main/resources/restart_boot.sh

This file was deleted.

Loading

0 comments on commit d846290

Please sign in to comment.