在使用dubbo的时候,发现隐式传参只会使用一次
消费者-->生产者-->生产者
在最后生产者接收不到消费者传递的参数,所以只能在filter中将参数先存到线程变量中,离开当前服务时在取出传递下去
分享一个线程局部变量操作类,当然需要配合线程结束事件使用,在结束后清空当前线程所有变量
importorg.apache.commons.lang3.StringUtils; importorg.springframework.web.context.request.RequestAttributes; importorg.springframework.web.context.request.RequestContextHolder; importjava.util.HashMap; importjava.util.Map; /*** 线程局部变量*/publicclassContextUtil { /*** 创建线程局部变量,并初始化值*/privatestaticThreadLocal<Map<String, String>>contextThreadLocal=ThreadLocal.withInitial(() ->newHashMap<>()); /*** 提供线程局部变量set方法** @param key* @param value*/publicstaticvoidsetValue(Stringkey, Stringvalue) { Map<String, String>map=getValues(); if (map.containsKey(key)) { map.replace(key, value); } else { map.put(key, value); } contextThreadLocal.set(map); } /*** 提供线程局部变量get方法** @param key* @return*/publicstaticStringgetValue(Stringkey) { Map<String, String>map=contextThreadLocal.get(); returnmap.get(key); } /*** 获取所有变量** @return*/publicstaticMap<String, String>getValues() { returncontextThreadLocal.get(); } /*** 删除key** @param key*/publicstaticvoidremove(Stringkey) { Map<String, String>map=contextThreadLocal.get(); if (map.containsKey(key)) { map.remove(key); contextThreadLocal.set(map); } } /*** 清除所有变量*/publicstaticvoidclear() { contextThreadLocal.set(newHashMap<>()); contextThreadLocal.remove(); } /*** 设置 RequestContextHolder Attributes** @param key* @param value*/publicstaticvoidsetRequestValue(Stringkey, Stringvalue) { try { RequestContextHolder.currentRequestAttributes().setAttribute( key, value, RequestAttributes.SCOPE_REQUEST); } catch (Exceptionex) { } } /*** 获取 RequestContextHolder Attributes** @param key* @return*/publicstaticStringgetRequestValue(Stringkey) { try { if (!StringUtils.isNotBlank(key)) { return""; } Object_namespace_obj=RequestContextHolder.currentRequestAttributes().getAttribute(key, RequestAttributes.SCOPE_REQUEST); if (_namespace_obj!=null) { return_namespace_obj.toString(); } } finally { return""; } } }