Featured image of post arthas 高级玩法

arthas 高级玩法

高级玩法,值得拥有

[

配置 arthas 实现远程线上 debug

2021-08-03

Image](http://mp.weixin.qq.com/s?__biz=MzI3Njk5ODg4OQ==&mid=2247485202&idx=1&sn=4fbe36afe107a828a936b2fb5e6c0d45&chksm=eb6db894dc1a31820d179afe3bf6516fe2997d3ca2c7af43e22f0c57df91677b6b1dcd029db5&scene=21#wechat_redirect)[

arthas idea 插件的基本玩法(常用)

2021-08-03

Image](http://mp.weixin.qq.com/s?__biz=MzI3Njk5ODg4OQ==&mid=2247485202&idx=2&sn=fa2d85e2101ec3867c5be995f49ffe47&chksm=eb6db894dc1a318233ac598187923d5e8f61f62de3bcc43450845a192571140afb00c2762305&scene=21#wechat_redirect)

获取 spring context 然后为所欲为?

执行 tt 命令来记录 RequestMappingHandlerAdapter#invokeHandlerMethod 的请求

1tt -t org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter invokeHandlerMethod

请求以后将看到

1[arthas@38341]$ tt -t org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter invokeHandlerMethod
2Press Q or Ctrl+C to abort.
3Affect(class count: 1 , method count: 1) cost in 60 ms, listenerId: 2
4 INDEX      TIMESTAMP                  COST(ms)      IS-RET     IS-EXP     OBJECT              CLASS                                    METHOD
5--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
6 1000       2021-08-03 15:34:31        473.709743    true       false      0x545d772e          RequestMappingHandlerAdapter             invokeHandlerMethod

可以用 tt 命令的 -i 参数来指定 index,并且用 -w 参数来执行 ognl 表达式来获取 spring context

 1[arthas@38341]$ tt -i 1000 -w 'target.getApplicationContext()'
 2@AnnotationConfigServletWebServerApplicationContext[
 3    reader=@AnnotatedBeanDefinitionReader[org.springframework.context.annotation.AnnotatedBeanDefinitionReader@28aa9b60],
 4    scanner=@ClassPathBeanDefinitionScanner[org.springframework.context.annotation.ClassPathBeanDefinitionScanner@1c138ae],
 5    annotatedClasses=@LinkedHashSet[isEmpty=true;size=0],
 6    basePackages=null,
 7    logger=@SLF4JLocationAwareLog[org.apache.commons.logging.impl.SLF4JLocationAwareLog@450746b3],
 8    DISPATCHER_SERVLET_NAME=@String[dispatcherServlet],
 9    webServer=@TomcatWebServer[org.springframework.boot.web.embedded.tomcat.TomcatWebServer@c5697fe],
10    servletConfig=null,
11    serverNamespace=null,
12    servletContext=@ApplicationContextFacade[org.apache.catalina.core.ApplicationContextFacade@705b6c8f],
13    themeSource=@ResourceBundleThemeSource[org.springframework.ui.context.support.ResourceBundleThemeSource@78d73e62],
14    beanFactory=@DefaultListableBeanFactory[org.springframework.beans.factory.support.DefaultListableBeanFactory@4277127c: defining beans [org.springframework.context.annotatio
15n.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnno
16tationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,mealBootstrapApplication,bootstr
17apApplicationListener.BootstrapMarkerConfiguration,org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory,glRocketMQConfig,globalConfig,mybatisPlusConfig,o
18kHttpConfiguration,mealQueryBaseDataController,mealAppBannerController,appOrderController,mealBannerController,mealReturnCouponsTipsController,appletsOrderController,h5OrderCon
19troller,thirdNoticeController,aliPayNoticeController,payController,wxPayNoticeController,mealGoodsExclusivePricePcController,mealManagerController,mealOrderManagerController,ba
20seServiceClient,fileServiceClient,userCenterClient,mealGlobalConfigServiceImpl,mealGoodsCostServiceImpl,mealGoodsCostTableServiceImpl,mealGoodsExclusivePriceServiceImpl,mealBan
21nerServiceImpl,mealManagerPcServiceImpl,mealOrderManagerPcServiceImpl,mealQueryBaseDataServiceImpl,mealReturnCouponsTipsServiceImpl,internalOrderMq,glCompensationFuncTM,glRocke
22tMQLocalTM,orderPayResultServiceImpl,orderServiceImpl,orderJobServiceImpl,aliPayConfig,wxAppPayProperties,wxPayConfiguration,aliAppletCyPayServiceImpl,aliPayServiceImpl,mealPay
23FlowServiceImpl,payProfitSharingFlowServiceImpl,payResultServiceImpl,weChatPayServiceImpl,payFlowHandler,payJobServiceImpl,refundServiceImpl,couponsUtil,idUtils,thirdConfig,goo
24dsSyncServiceImpl,okHttpUtil,reqUtil,syncGoodsTaskHandler,costTableHandler,mealOrderHandler,payHandler,statisticTaskHandler,globalExceptionHandler,springWebMvcConfiguration,asy
25ncUtils,feignHystrixConcurrencyStrategy,springSecurityConfiguration,authenticationCustomizeEntryPoint,authAccessDeniedHandler,RBACService,memberExtraInfoClientFallback,memberIn
26foClientFallback,memberRiskClientFallback,memberWalletClientFallback,memberWalletFlowClientFallback,riskEventClientFallback,userCenterMemberInfoClientFallback,userCenterOperato
27rClientFallback,constants,utils,captchaClientFallback,channelIsolationClientFallback,channelPriorityClientFallback,complexMessageClientFallback,JPushClientFallback,messageFeish
28uBotClientFallback,messageFeiShuBotClientV2Fallback,stationLetterClientFallback,idGenerateClientFallback,couponClientFallBack,couponManagerClientFallBack,couponMemberClientFall
29Back,normalFileClientFallback,transactionAutoConfiguration,webAutoConfiguration,authAutoConfiguration,cacheAutoConfiguration,transactionMQProducer,defaultMQPushConsumer,enumCus
30tomizer,paginationInterceptor,okHttpClient,x509TrustManager,sslSocketFactory,pool,aliAppPayProperties,aliAppletPayProperties,appAlipayClient,appletAlipayClient,wxAppletPayServi
31ce,wxAppPayService,org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor,org.springframework.boot.context.internalConfigurationPropertiesBinde
32rFactory,org.springframework.boot.context.internalConfigurationPropertiesBinder,org.springframework.boot.context.properties.BoundConfigurationProperties,org.springframework.boo
33t.context.properties.ConfigurationPropertiesBeanDefinitionValidator,org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata,wx.applet.pay-com.demo.meal.se
34rvice.pay.config.WxAppletPayProperties,errorPageRegistrar,corsFilterRegistrationBean,org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfigurati
35on,objectPostProcessor,org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration,authenticationManagerBuilder,enableGlobalAuthenti
36cationAutowiredConfigurer,initializeUserDetailsBeanManagerConfigurer,initializeAuthenticationProviderBeanManagerConfigurer,org.springframework.security.config.annotation.web.co
37nfiguration.WebSecurityConfiguration,delegatingApplicationListener,webSecurityExpressionHandler,springSecurityFilterChain,privilegeEvaluator,conversionServicePostProcessor,auto
38wiredWebSecurityConfigurersIgnoreParents,org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration,requestDataValueProcessor,org.springframew
39ork.scheduling.annotation.SchedulingConfiguration,org.springframework.context.annotation.internalScheduledAnnotationProcessor,org.springframework.boot.autoconfigure.AutoConfigu
40rationPackages,com.demo.MealBootstrapApplication#MapperScannerRegistrar#0,default.com.demo.MealBootstrapApplication.FeignClientSpecification,memberExtraInfoClient.FeignClient
41Specification,com.demo.user.common.client.MemberExtraInfoClient,MemberInfoClient.FeignClientSpecification,com.demo.user.common.client.MemberInfoClient,MemberRiskClient.FeignC
42lientSpecification,com.demo.user.common.client.MemberRiskClient,MemberWalletClient.FeignClientSpecification,com.demo.user.common.client.MemberWalletClient,memberWalletFlowCli
43ent.FeignClientSpecification,com.demo.user.common.client.MemberWalletFlowClient,riskEventClient.FeignClientSpecification,com.demo.user.common.client.RiskEventClient,userCenterMemberInfoClient.FeignClientSpecification,com.demo.user.common.client.UserCenterMemberInfoClient,userCenterOperatorClient.FeignClientSpecification,com.demo.user.common.client.UserCenterOperatorClient,captchaClient.FeignClientSpecification,com.demo.message.rest.CaptchaClient,channelIsolationClient.FeignClientSpecification,com.demo.message.rest.ChannelIsolationClient,channelPriorityClient.FeignClientSpecification,com.demo.message.rest.ChannelPriorityClient,complexMessageClient.FeignClientSpecification,com.demo.message.rest.ComplexMessageClient,jPushClient.FeignClientSpecification,com.demo.message.rest.JPushClient,messageFeishuBotClient.FeignClientSpecification,com.demo.message.rest.MessageFeishuBotClient,messageFeiShuBotClientV2.FeignClientSpecification,com.demo.message.rest.MessageFeiShuBotClientV2,stationLetterClient.FeignClientSpecification,com.demo.message.rest.StationLetterClient,idGenerateClient.FeignClientSpecification,com.demo.id.client.IdGenerateClient,couponClient.FeignClientSpecification,com.demo.marketing.client.coupon.CouponClient,couponManagerClient.FeignClientSpecification,com.demo.marketing.client.coupon.CouponManagerClient,couponMemberClient.FeignClientSpecification,com.demo.marketing.client.coupon.CouponMemberClient,normalFileClient.FeignClientSpecification,c],
44    resourceLoader=null,
45    customClassLoader=@Boolean[false],
46    refreshed=@AtomicBoolean[true],
47    MESSAGE_SOURCE_BEAN_NAME=@String[messageSource],
48    LIFECYCLE_PROCESSOR_BEAN_NAME=@String[lifecycleProcessor],
49    APPLICATION_EVENT_MULTICASTER_BEAN_NAME=@String[applicationEventMulticaster],
50    logger=@SLF4JLocationAwareLog[org.apache.commons.logging.impl.SLF4JLocationAwareLog@71add15],
51    id=@String[application-1],
52    displayName=@String[org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@58740366],
53    parent=@AnnotationConfigApplicationContext[org.springframework.context.annotation.AnnotationConfigApplicationContext@62d363ab, started on Tue Aug 03 15:13:22 CST 2021],
54    environment=@StandardServletEnvironment[StandardServletEnvironment {activeProfiles=[local, common-local, common], defaultProfiles=[default], propertySources=[MapPropertySource {name='server.ports'}, ConfigurationPropertySourcesPropertySource {name='configurationProperties'}, EncryptablePropertySourceWrapper {name='servletConfigInitParams'}, EncryptablePropertySourceWrapper {name='servletContextInitParams'}, EncryptableMapPropertySourceWrapper {name='systemProperties'}, EncryptableSystemEnvironmentPropertySourceWrapper{name='systemEnvironment'}, EncryptablePropertySourceWrapper {name='random'}, EncryptableMapPropertySourceWrapper {name='springCloudClientHostInfo'}, EncryptableMapPropertySourceWrapper {name='applicationConfig: [classpath:/application-common.yml]'}, EncryptableMapPropertySourceWrapper {name='applicationConfig: [classpath:/application-common-local.yml]'}, EncryptableMapPropertySourceWrapper {name='applicationConfig: [classpath:/application-local.yml]'}, EncryptableMapPropertySourceWrapper {name='applicationConfig: [classpath:/application.yml]'}, EncryptableMapPropertySourceWrapper {name='springCloudDefaultProperties'}, EncryptablePropertySourceWrapper {name='cachedrandom'},  {name='Management Server'}]}],
55    beanFactoryPostProcessors=@ArrayList[isEmpty=false;size=5],
56    startupDate=@Long[1627974802713],
57    active=@AtomicBoolean[true],
58    closed=@AtomicBoolean[false],
59    startupShutdownMonitor=@Object[java.lang.Object@553a67da],
60    shutdownHook=@[Thread[SpringContextShutdownHook,5,main]],
61    resourcePatternResolver=@ServletContextResourcePatternResolver[org.springframework.web.context.support.ServletContextResourcePatternResolver@499ea1d],
62    lifecycleProcessor=@DefaultLifecycleProcessor[org.springframework.context.support.DefaultLifecycleProcessor@61ac01da],
63    messageSource=@DelegatingMessageSource[Empty MessageSource],
64    applicationEventMulticaster=@SimpleApplicationEventMulticaster[org.springframework.context.event.SimpleApplicationEventMulticaster@ee42df5],
65    applicationListeners=@LinkedHashSet[isEmpty=false;size=38],
66    earlyApplicationListeners=@LinkedHashSet[isEmpty=false;size=19],
67    earlyApplicationEvents=null,
68    classLoader=@AppClassLoader[jdk.internal.loader.ClassLoaders$AppClassLoader@9e89d68],
69    protocolResolvers=@LinkedHashSet[isEmpty=true;size=0],
70    resourceCaches=@ConcurrentHashMap[isEmpty=true;size=0],
71]
72Affect(row-cnt:1) cost in 4 ms.

利用 tt 命令通过 1000 这个 index 我们已经可以得到 spring context 了,得到后就可以利用 spring context 进行各种操作了。比如我们 get 一个 controllerbean 并执行一下方法

1tt -i 1000 -w 'target.getApplicationContext().getBean("mealManagerController").listMealByCategoryId(1379999659854008320L)'

查看SQL语句

watch Connection

1watch java.sql.Connection prepareStatement '{params,throwExp}'  -n 5  -x 3 

watch BoundSql (mybatis)

1watch org.apache.ibatis.mapping.BoundSql getSql '{params,returnObj,throwExp}'  -n 5  -x 3 

热修复三板斧(生产慎用!)

反编译输出 .java 源码

1jad --source-only com.demo.meal.pc.MealManagerController > /tmp/MealManagerController.java

修改代码

利用 vim 直接修改上面反编译出的文件内容

编译

搜索到对应类的classloader

1[arthas@38341]$ sc -d *MealManagerController |grep classLoader
2 classLoaderHash   9e89d68

mc(Memory Compiler) 命令来编译

1 mc -c  9e89d68 /tmp/MealManagerController.java -d /tmp

热加载

重新热加载(无需重启服务), 并且非侵入, 只是临时修改

1[arthas@38341]$ redefine /tmp/com/demo/meal/pc/MealManagerController.class
2redefine success, size: 1, classes:
3com.demo.meal.pc.MealManagerController

限制

  • redefine的class不能修改、添加、删除类的field和method,包括方法参数、方法名称及返回值
  • redefine命令和jad/watch/trace/monitor/tt等命令会冲突。执行完redefine之后,如果再执行上面提到的命令,则会把redefine的字节码重置。

远程打断点 Debug?

虽然可以,但不建议 https://github.com/alibaba/arthas/issues/222

参考

位旅人路过 次翻阅 初次见面