zoukankan      html  css  js  c++  java
  • ThreadLocal的妙用

    ThreadLocal对于工作了多年的老程序员来说,并不陌生。但我想说对于平时做业务代码的人来说,用ThreadLocal的机会并不多。

    最近刚接到一个需求,获取HttpRequest中的请求头里的一个参数,并用这个参数作为加密的入参。

    考虑到不想大幅度的修改代码,怎么办呢?

    强大的组合 ThreadLocal加AOP

    @Around("execution(* com.ymm.trade.om.web.rest.OrderDetailController.orderDetailDriver(..))")
        public Object doAroundAdviceOrderDetail(ProceedingJoinPoint pjp) throws Throwable{
            Object[] args = pjp.getArgs();
            Object requestParameter = args[0];
            Object request = args[1];
            if (requestParameter == null) {
                return InternalResult.buildFailResult("请求参数为空");
            }
            if (request instanceof HttpServletRequest) {
                String basic = ((HttpServletRequest) request).getHeader("authorization");
    //            basic = basic.replaceAll("/", "-");
                ThreadLocalUtil.basicLocal.set(basic);
    
                String clientInfoStr = ((HttpServletRequest) request).getHeader("Client-Info");
                ClientInfo clientInfo = new ClientInfo(clientInfoStr );
    
                ThreadLocalUtil.appIdThreadLocal.set(clientInfo.getAppID());
            }

    先写切面类,然后把两个参数写到两个threadlocal里

    之后在原有逻辑里会执行DTO到VO转换的地方取出来这两个ThreadLocal中的变量

    private String encodePicPath(String ossPath) {
    
            if (StringUtils.isEmpty(ossPath)) {
                return ossPath;
            }
    
            String url ;
            String authorization = ThreadLocalUtil.basicLocal.get();
            String appid = ThreadLocalUtil.appIdThreadLocal.get();

    只要保证之后的流程代码和rest接口是处于同一个线程中,就一定能取到ThreadLocal里的值。

    其实ThreadLocal最常见的使用场景就是传递参数。

  • 相关阅读:
    六大设计原则之依赖倒置原则
    六大设计原则之里氏替换原则
    六大设计原则之单一设计原则
    六、Spring之DI的Bean的作用域
    五、spring之DI循环依赖
    四、spring之DI
    十二 NIO和IO
    十一 Pipe
    十 DatagramChannel
    九 ServerSocketChannel
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15054430.html
Copyright © 2011-2022 走看看