国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Spring AOP實現(xiàn)后臺管理系統(tǒng)日志管理

設(shè)計原則和思路:

  • 元注解方式結(jié)合AOP,靈活記錄操作日志
  • 能夠記錄詳細錯誤日志為運維提供支持
  • 日志記錄盡可能減少性能影響

1.定義日志記錄元注解

package com.myron.ims.annotation;import java.lang.annotation.*;/** * 自定義注解 攔截Controller *  * @author lin.r.x * */@Target({ ElementType.PARAMETER, ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)public @interface SystemControllerLog {    /**     * 描述業(yè)務(wù)操作 例:Xxx管理-執(zhí)行Xxx操作     * @return     */    String description() default "";}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

2.定義用于記錄日志的實體類

package com.myron.ims.bean;import java.io.Serializable;import com.myron.common.util.StringUtils;import com.myron.common.util.UuidUtils;import com.fasterxml.jackson.annotation.JsonFormat;import java.util.Date;import java.util.Map;/** * 日志類-記錄用戶操作行為 * @author lin.r.x * */public class Log implements Serializable{    private static final long serialVersionUID = 1L;    private String logId;           //日志主鍵      private String type;            //日志類型      private String title;           //日志標題      private String remoteAddr;          //請求地址      private String requestUri;          //URI       private String method;          //請求方式      private String params;          //提交參數(shù)      private String exception;           //異常        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")    private Date operateDate;           //開始時間      private String timeout;         //結(jié)束時間      private String userId;          //用戶ID      public String getLogId() {        return StringUtils.isBlank(logId) ? logId : logId.trim();    }    public void setLogId(String logId) {        this.logId = logId;    }    public String getType() {        return StringUtils.isBlank(type) ? type : type.trim();    }    public void setType(String type) {        this.type = type;    }    public String getTitle() {        return StringUtils.isBlank(title) ? title : title.trim();    }    public void setTitle(String title) {        this.title = title;    }    public String getRemoteAddr() {        return StringUtils.isBlank(remoteAddr) ? remoteAddr : remoteAddr.trim();    }    public void setRemoteAddr(String remoteAddr) {        this.remoteAddr = remoteAddr;    }    public String getRequestUri() {        return StringUtils.isBlank(requestUri) ? requestUri : requestUri.trim();    }    public void setRequestUri(String requestUri) {        this.requestUri = requestUri;    }    public String getMethod() {        return StringUtils.isBlank(method) ? method : method.trim();    }    public void setMethod(String method) {        this.method = method;    }    public String getParams() {        return StringUtils.isBlank(params) ? params : params.trim();    }    public void setParams(String params) {        this.params = params;    }    /**     * 設(shè)置請求參數(shù)     * @param paramMap     */    public void setMapToParams(Map<String, String[]> paramMap) {        if (paramMap == null){            return;        }        StringBuilder params = new StringBuilder();        for (Map.Entry<String, String[]> param : ((Map<String, String[]>)paramMap).entrySet()){            params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");            String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");            params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "" : paramValue, 100));        }        this.params = params.toString();    }    public String getException() {        return StringUtils.isBlank(exception) ? exception : exception.trim();    }    public void setException(String exception) {        this.exception = exception;    }    public Date getOperateDate() {        return operateDate;    }    public void setOperateDate(Date operateDate) {        this.operateDate = operateDate;    }    public String getTimeout() {        return StringUtils.isBlank(timeout) ? timeout : timeout.trim();    }    public void setTimeout(String timeout) {        this.timeout = timeout;    }    public String getUserId() {        return StringUtils.isBlank(userId) ? userId : userId.trim();    }    public void setUserId(String userId) {        this.userId = userId;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135

3.定義日志AOP切面類

package com.myron.ims.aop;import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.NamedThreadLocal;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import org.springframework.stereotype.Component;import com.myron.common.util.DateUtils;import com.myron.common.util.UuidUtils;import com.myron.ims.annotation.SystemControllerLog;import com.myron.ims.annotation.SystemServiceLog;import com.myron.ims.bean.Log;import com.myron.ims.bean.User;import com.myron.ims.service.LogService;/** * 系統(tǒng)日志切面類 * @author lin.r.x * */@Aspect@Componentpublic class SystemLogAspect {    private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);    private static final ThreadLocal<Date> beginTimeThreadLocal =            new NamedThreadLocal<Date>("ThreadLocal beginTime");    private static final ThreadLocal<Log> logThreadLocal =             new NamedThreadLocal<Log>("ThreadLocal log");    private static final ThreadLocal<User> currentUser=new NamedThreadLocal<>("ThreadLocal user");    @Autowired(required=false)    private HttpServletRequest request;    @Autowired    private ThreadPoolTaskExecutor threadPoolTaskExecutor;    @Autowired    private LogService logService;    /**     * Controller層切點 注解攔截     */    @Pointcut("@annotation(com.myron.ims.annotation.SystemControllerLog)")    public void controllerAspect(){}    /**     * 前置通知 用于攔截Controller層記錄用戶的操作的開始時間     * @param joinPoint 切點     * @throws InterruptedException      */    @Before("controllerAspect()")    public void doBefore(JoinPoint joinPoint) throws InterruptedException{        Date beginTime=new Date();        beginTimeThreadLocal.set(beginTime);//線程綁定變量(該數(shù)據(jù)只有當前請求的線程可見)          if (logger.isDebugEnabled()){//這里日志級別為debug            logger.debug("開始計時: {}  URI: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")                .format(beginTime), request.getRequestURI());        }        //讀取session中的用戶         HttpSession session = request.getSession();               User user = (User) session.getAttribute("ims_user");            currentUser.set(user);    }    /**     * 后置通知 用于攔截Controller層記錄用戶的操作     * @param joinPoint 切點     */    @SuppressWarnings("unchecked")    @After("controllerAspect()")    public void doAfter(JoinPoint joinPoint) {        User user = currentUser.get();        if(user !=null){            String title="";            String type="info";                       //日志類型(info:入庫,error:錯誤)            String remoteAddr=request.getRemoteAddr();//請求的IP            String requestUri=request.getRequestURI();//請求的Uri            String method=request.getMethod();        //請求的方法類型(post/get)            Map<String,String[]> params=request.getParameterMap(); //請求提交的參數(shù)            try {                title=getControllerMethodDescription2(joinPoint);            } catch (Exception e) {                e.printStackTrace();            }                // 打印JVM信息。            long beginTime = beginTimeThreadLocal.get().getTime();//得到線程綁定的局部變量(開始時間)              long endTime = System.currentTimeMillis();  //2、結(jié)束時間              if (logger.isDebugEnabled()){                logger.debug("計時結(jié)束:{}  URI: {}  耗時: {}   最大內(nèi)存: {}m  已分配內(nèi)存: {}m  已分配內(nèi)存中的剩余空間: {}m  最大可用內(nèi)存: {}m",                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(endTime),                         request.getRequestURI(),                         DateUtils.formatDateTime(endTime - beginTime),                        Runtime.getRuntime().maxMemory()/1024/1024,                         Runtime.getRuntime().totalMemory()/1024/1024,                         Runtime.getRuntime().freeMemory()/1024/1024,                         (Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024);             }            Log log=new Log();            log.setLogId(UuidUtils.creatUUID());            log.setTitle(title);            log.setType(type);            log.setRemoteAddr(remoteAddr);            log.setRequestUri(requestUri);            log.setMethod(method);            log.setMapToParams(params);            log.setUserId(user.getId());            Date operateDate=beginTimeThreadLocal.get();            log.setOperateDate(operateDate);            log.setTimeout(DateUtils.formatDateTime(endTime - beginTime));            //1.直接執(zhí)行保存操作            //this.logService.createSystemLog(log);            //2.優(yōu)化:異步保存日志            //new SaveLogThread(log, logService).start();            //3.再優(yōu)化:通過線程池來執(zhí)行日志保存            threadPoolTaskExecutor.execute(new SaveLogThread(log, logService));            logThreadLocal.set(log);        }    }    /**     *  異常通知 記錄操作報錯日志     * @param joinPoint     * @param e     */    @AfterThrowing(pointcut = "controllerAspect()", throwing = "e")      public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {        Log log = logThreadLocal.get();        log.setType("error");        log.setException(e.toString());        new UpdateLogThread(log, logService).start();    }    /**     * 獲取注解中對方法的描述信息 用于service層注解     * @param joinPoint切點     * @return discription     */    public static String getServiceMthodDescription2(JoinPoint joinPoint) {        MethodSignature signature = (MethodSignature) joinPoint.getSignature();        Method method = signature.getMethod();        SystemServiceLog serviceLog = method                .getAnnotation(SystemServiceLog.class);        String discription = serviceLog.description();        return discription;    }    /**     * 獲取注解中對方法的描述信息 用于Controller層注解     *      * @param joinPoint 切點     * @return discription     */    public static String getControllerMethodDescription2(JoinPoint joinPoint) {        MethodSignature signature = (MethodSignature) joinPoint.getSignature();        Method method = signature.getMethod();        SystemControllerLog controllerLog = method                .getAnnotation(SystemControllerLog.class);        String discription = controllerLog.description();        return discription;    }    /**     * 保存日志線程     */    private static class SaveLogThread implements Runnable {        private Log log;        private LogService logService;        public SaveLogThread(Log log, LogService logService) {            this.log = log;            this.logService = logService;        }        @Override        public void run() {            logService.createLog(log);        }    }    /**     * 日志更新線程     */    private static class UpdateLogThread extends Thread {        private Log log;        private LogService logService;        public UpdateLogThread(Log log, LogService logService) {            super(UpdateLogThread.class.getSimpleName());            this.log = log;            this.logService = logService;        }        @Override        public void run() {            this.logService.updateLog(log);        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226

4.spring 配置掃描切面,開啟@AspectJ注解的支持

    <!-- 啟動對@AspectJ注解的支持 -->      <aop:aspectj-autoproxy/>     <!-- 掃描切點類組件 -->    <context:component-scan base-package="com.myron.ims.aop" />    <context:component-scan base-package="com.myron.ims.service"/>    <bean id="taskExecutor"   class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">          <property name="corePoolSize" value="5" />          <property name="maxPoolSize" value="10" />          <property name="WaitForTasksToCompleteOnShutdown" value="true" />      </bean>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

5.使用范例LoginController方法中添加日志注解

    /**    *系統(tǒng)登入    */    @RequestMapping("/login.do")    @SystemControllerLog(description="登入系統(tǒng)")    @ResponseBody    public Map<String, Object> login(String username, String password, Boolean rememberMe, HttpServletRequest req){    //業(yè)務(wù)代碼省略...}       /**     * 安全退出登入     * @return     */    @SystemControllerLog(description="安全退出系統(tǒng)")    @RequestMapping("logout.do")    public String logout(){        Subject subject=SecurityUtils.getSubject();        if(subject.isAuthenticated()){            subject.logout(); // session 會銷毀,在SessionListener監(jiān)聽session銷毀,清理權(quán)限緩存        }        return "/login.jsp";    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

6.運行效果

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Java AOP 日志記錄
java注解日志記錄到數(shù)據(jù)庫
SpringBoot使用AOP(環(huán)繞通知)完成對用戶操作的日志記錄
Spring MVC通過AOP切面編程 來攔截controller 實現(xiàn)日志的寫入
JDK動態(tài)代理和CGLIB代理的使用
AOP2
更多類似文章 >>
生活服務(wù)
分享 收藏 導長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服