利用ThreadLocal+AOP切面编程实现RPC日志

文章介绍了如何使用AOP的切面拦截所有请求,通过ThreadLocal存储请求日志信息,包括请求IP、设备号等,在请求开始和结束时记录并打印相关信息。同时讨论了ThreadLocal在用户身份验证中的应用,并提供了具体的Java代码示例。
摘要由CSDN通过智能技术生成

前言

最近在稍微学了一下ThreadLocal以及它的使用场景,同时也学了一下AOP相关的内容,刚好做个很常见的RPC日志来练练手。
主要思想是通过切面来拦截所有的请求,在请求进入切面的时候,可以用ThreadLocal来存储当前请求的线程专属的日志,比如请求的IP,设备号等等。在进入业务代码之后,可以将请求参数打印一部分,最后请求结束的时候再把请求结果存入ThreadLocal,并打印ThreadLocal内存储的日志内容。ThreadLocal的使用贯穿整个请求的过程。

除了这些,ThreadLocal还可以在拦截器校验用户身份的时候把当前登录用户相关的内容存储起来,方便后续使用。拦截器也是AOP思想,不过拦截器所处于更上层的位置。

现在觉得:AOP思想真的太牛逼啦。
在这里插入图片描述

下面是一些具体的实现:

切面类

package com.yumoxuan.annotation.Aspect;

import com.alibaba.fastjson.JSONObject;
import com.yumoxuan.utils.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAnnotationAspect {

    //这个切点代表,方法是public的,并且任意返回类型,在com.yumoxuan.controller包下的任意类的任意方法,任意参数
    @Pointcut(value = "execution(public * com.yumoxuan.controller.*.*(..))")
    public void allCut(){

    @Around(value = "allCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        LogUtil.log("请求方法:"+((MethodSignature) joinPoint.getSignature()).getMethod());
        //请求参数在具体的接口入参处打印
        Object proceed=null;
        //方式一
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        //方式二
        //        Object[] args = joinPoint.getArgs(); // 参数值
		//        String[] paramNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames(); // 参数名


        if (args != null && paramNames != null) {
            for (int i = 0; i < args.length; i++) {
                LogUtil.log("  " + paramNames[i] + ": " + args[i]);
            }
        }
        try {
             proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //其实在公司分布式的datacenter项目挺多是只打印返回的code,因为查询列表的数据量大,而且没必要
        LogUtil.log("请求结果:"+JSONObject.toJSONString(proceed));
        LogUtil.print();
        //环绕通知会把返回结果拦截下来,所以要把结果返回
        return proceed;
    }
}


日志类,采用ThreadLocal存储日志内容

package com.yumoxuan.utils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogUtil {
    private static ThreadLocal<StringBuilder> rpcLog = new ThreadLocal<>();

    public static void log(Object... message) {
        if(message==null||message.length==0){
            return;
        }
        //采用不定参数方式来拼接参数,方便使用
        String mes=String.valueOf(message[0]);
        for(int i=1;i<message.length;i++){
            mes = mes.replaceFirst("\\{\\}", String.valueOf(message[i]));
        }
        StringBuilder sb = rpcLog.get();

        if (sb == null) {
            rpcLog.set(new StringBuilder().append(mes));
        } else {
            sb.append(mes);
            rpcLog.set(sb);
        }
    }

    public static void print() {
        StringBuilder sb = rpcLog.get();
        if(sb!=null){
            log.info(sb.toString());
            //这一步别忘了,不然会内存泄漏
            rpcLog.remove();
        }
    }
}


controller类

import com.yumoxuan.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;


@RestController
public class PubController {
    @Autowired
    PubService pubService;
    @ResponseBody
    @RequestMapping("/getpub")
    public Result<Pub> getPub(String userName,Long userNo){
        Result res=Result.ok();
        Pub pub = pubService.getPub();
        if(Objects.nonNull(pub)){
            res.setData(pub);
        }
        return res;
    }
    
@RequestMapping(value = "/setpub",method = RequestMethod.POST)
    public boolean setPub(@RequestBody Pub pub) {
        return pubService.setPub(pub);
    }

}

最后打印的内容:(两种获取参数的方式是一样的)
2023-06-07 21:36:11.857 INFO 12616 — [nio-8080-exec-1] com.yumoxuan.utils.LogUtil :
请求方法:public com.yumoxuan.pojo.Result com.yumoxuan.controller.PubController.getPub(java.lang.String,java.lang.Long) userName: “你好” userNo: 123456请求结果:{“code”:200,“data”:{“email”:“123456”,“id”:1,“notify”:“在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准…哈哈哈”,“phone”:“321654”,“swiperUrls”:“http://192.168.43.113:8080/images/9f4c887c-2972-4a15-976a-12384f75d090.png,http://192.168.43.113:8080/images/76037e7a-d56d-4a0a-8bd3-3dca5bfe3649.png”},“message”:“成功”}

post请求结果:
请求方法:public boolean com.yumoxuan.controller.PubController.setPub(com.yumoxuan.pojo.Pub) pub: Pub(id=1, swiperUrls=null, notify=null, email=123456, phone=123654)请求结果:true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值