美文网首页
spring-cloud-netflix-core引发的一次内存

spring-cloud-netflix-core引发的一次内存

作者: 王兆阳 | 来源:发表于2019-11-28 16:12 被阅读0次

发现问题

公司线上的服务运行一段时间后就出现某个服务节点无响应,查看内存监控,对应的Jvm的堆耗尽。好在服务是多节点,线上dump运行服务的Jvm快照,下载到本地进行分析。
使用MAT打开快照文件,此处省略掉使用MAT的过程,分析发现有大量的com.netflix.servo.monitor.BasicTimer未释放,且被org.springframework.cloud.netflix.metrics.servo.ServoMonitorCache占用。

分析问题

在工程中查找到ServoMonitorCache类,发现在spring-cloud-netflix-core包下,然后打开该jar包,查看其spring.factories去查看是那里自动配置生成了该类,找到org.springframework.cloud.netflix.metrics.servo.ServoMetricsAutoConfiguration中自动配置,然后再搜索那里使用了该类,在org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration中发现了ServoMonitorCache对象的使用。看到metrics就明白,是对服务的监控对象。代码如下:

@Configuration
@ConditionalOnProperty(value = "spring.cloud.netflix.metrics.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass({ Monitors.class, MetricReader.class })
public class MetricsInterceptorConfiguration {

    @Configuration
    @ConditionalOnWebApplication
    @ConditionalOnClass(WebMvcConfigurerAdapter.class)
    static class MetricsWebResourceConfiguration extends WebMvcConfigurerAdapter {
        @Bean
        MetricsHandlerInterceptor servoMonitoringWebResourceInterceptor() {
            return new MetricsHandlerInterceptor();
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(servoMonitoringWebResourceInterceptor());
        }
    }

    @Configuration
    @ConditionalOnClass({ RestTemplate.class, JoinPoint.class })
    @ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
    static class MetricsRestTemplateAspectConfiguration {

        @Bean
        RestTemplateUrlTemplateCapturingAspect restTemplateUrlTemplateCapturingAspect() {
            return new RestTemplateUrlTemplateCapturingAspect();
        }

    }

    @Configuration
    @ConditionalOnClass({ RestTemplate.class, HttpServletRequest.class })   // HttpServletRequest implicitly required by MetricsTagProvider
    static class MetricsRestTemplateConfiguration {

        @Value("${netflix.metrics.restClient.metricName:restclient}")
        String metricName;
                /*
                  *此处为关键代码
                  *编号1
                  */
        @Bean
        MetricsClientHttpRequestInterceptor spectatorLoggingClientHttpRequestInterceptor(
                Collection<MetricsTagProvider> tagProviders,
                ServoMonitorCache servoMonitorCache) {
            return new MetricsClientHttpRequestInterceptor(tagProviders,
                    servoMonitorCache, this.metricName);
        }

        @Bean
        BeanPostProcessor spectatorRestTemplateInterceptorPostProcessor() {
            return new MetricsInterceptorPostProcessor();
        }
                //编号2
        private static class MetricsInterceptorPostProcessor
                implements BeanPostProcessor, ApplicationContextAware {
            private ApplicationContext context;
            private MetricsClientHttpRequestInterceptor interceptor;

            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) {
                return bean;
            }

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) {
                if (bean instanceof RestTemplate) {
                    if (this.interceptor == null) {
                        this.interceptor = this.context
                                .getBean(MetricsClientHttpRequestInterceptor.class);
                    }
                    RestTemplate restTemplate = (RestTemplate) bean;
                    // create a new list as the old one may be unmodifiable (ie Arrays.asList())
                    ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
                    interceptors.add(interceptor);
                    interceptors.addAll(restTemplate.getInterceptors());
                    restTemplate.setInterceptors(interceptors);
                }
                return bean;
            }

            @Override
            public void setApplicationContext(ApplicationContext context)
                    throws BeansException {
                this.context = context;
            }
        }
    }
}

在上面代码中编号1处,自动配置生成了MetricsClientHttpRequestInterceptor拦截器,然后把ServoMonitorCache采用构造器注入传入了拦截器;然后代码编号2处的postProcessAfterInitialization函数中,把该拦截器赋值给了RestTemplate;很熟悉的对象,Spring的Rest服务访问客户端,公司的微服务采用Restful接口,使用该对象作为客户端。
然后进入MetricsClientHttpRequestInterceptor,核心代码如下:

@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
            ClientHttpRequestExecution execution) throws IOException {
        long startTime = System.nanoTime();

        ClientHttpResponse response = null;
        try {
            response = execution.execute(request, body);
            return response;
        }
        finally {
            SmallTagMap.Builder builder = SmallTagMap.builder();
                        //编号3
            for (MetricsTagProvider tagProvider : tagProviders) {
                for (Map.Entry<String, String> tag : tagProvider
                        .clientHttpRequestTags(request, response).entrySet()) {
                    builder.add(Tags.newTag(tag.getKey(), tag.getValue()));
                }
            }
                        //编号4
            MonitorConfig.Builder monitorConfigBuilder = MonitorConfig
                    .builder(metricName);
            monitorConfigBuilder.withTags(builder);

            servoMonitorCache.getTimer(monitorConfigBuilder.build())
                    .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
        }
    }

编号3处代码,发现对象tagProviders,回过去看代码也是该拦截器构造时传入的参数;现在去看一下这个对象是什么,因为该对象是构造器注入的,说明也是由spring容器配置生成的,所以继续在autoconfig文件中查找,发现在org.springframework.cloud.netflix.metrics.servo.ServoMetricsAutoConfiguration中自动配置生成:

@Configuration
    @ConditionalOnClass(name = "javax.servlet.http.HttpServletRequest")
    protected static class MetricsTagConfiguration {
        @Bean
        public MetricsTagProvider defaultMetricsTagProvider() {
            return new DefaultMetricsTagProvider();
        }
    }

进入DefaultMetricsTagProvider该对象代码,核心代码如下:

public Map<String, String> clientHttpRequestTags(HttpRequest request,
           ClientHttpResponse response) {
       String urlTemplate = RestTemplateUrlTemplateHolder.getRestTemplateUrlTemplate();
       if (urlTemplate == null) {
           urlTemplate = "none";
       }

       String status;
       try {
           status = (response == null) ? "CLIENT_ERROR" : ((Integer) response
                   .getRawStatusCode()).toString();
       }
       catch (IOException e) {
           status = "IO_ERROR";
       }

       String host = request.getURI().getHost();
       if( host == null ) {
           host = "none";
       }
       
       String strippedUrlTemplate = urlTemplate.replaceAll("^https?://[^/]+/", "");
       
       Map<String, String> tags = new HashMap<>();
       tags.put("method",   request.getMethod().name());
       tags.put("uri",     sanitizeUrlTemplate(strippedUrlTemplate));
       tags.put("status",   status);
       tags.put("clientName", host);
       
       return Collections.unmodifiableMap(tags);
   }

发现其就是分解了Http的客户端请求,其中关键就是method(get、post、delete等http方法)、status状态、clientName访问的服务域名、uri访问路径(包含参数)。

然后,返回去看代码编号4处,生成了一个对象com.netflix.servo.monitor.MonitorConfig,主要就是name和tags,name默认的就是restclient(可以在属性文件中修改);tags就是DefaultMetricsTagProvider中那些tag标签。
然后进入ServoMonitorCache.getTimer函数:

public synchronized BasicTimer getTimer(MonitorConfig config) {
        BasicTimer t = this.timerCache.get(config);
        if (t != null)
            return t;

        t = new BasicTimer(config);
        this.timerCache.put(config, t);

        if (this.timerCache.size() > this.config.getCacheWarningThreshold()) {
            log.warn("timerCache is above the warning threshold of " + this.config.getCacheWarningThreshold() + " with size " + this.timerCache.size() + ".");
        }

        this.monitorRegistry.register(t);
        return t;
    }

此处就很简单了,先在缓存中查找该MonitorConfig对象有没有,没有则新增一个BasicTimer,若有就更新该BasicTimer的参数,题外话,BasicTimer就存储了各个接口的访问最大时间、最小时间、平均时间等。
分析到这里就明白了,我们公司的内部服务直接互相访问时,采用了签名校验,即在访问时,都在URL后增加一个签名参数,密钥只有公司的各个服务节点上配置,签名校验通过则允许访问,不通过则直接拒绝访问,这样可提高一下接口的安全等级;签名机制中,明文混入了一个随机数,增强签名的安全性,这样就导致了每次的接口访问url都不一样,然后在DefaultMetricsTagProvider中解析的uri也就都不一样,最终导致了MonitorConfig对象不一样,所以接口调用一次,生成一个BasicTimer对象,久而久之也就打爆Jvm堆内存。

解决方案

  • 改变签名机制,将签名放入PostBody中
  • 去掉该拦截器
    因为公司服务的接口监控已有其他第三方组件服务完成,不需使用netflix-core的监控,所以选择第二种方案。
    实现方法
    回到MetricsInterceptorConfiguration,看到如下代码
@Configuration
@ConditionalOnProperty(value = "spring.cloud.netflix.metrics.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass({ Monitors.class, MetricReader.class })
public class MetricsInterceptorConfiguration {

熟悉springboot的一看就明白,只需要将属性spring.cloud.netflix.metrics.enabled置为false即可关闭该自动配置文件类。

最后

一次隐藏比较深的崩溃经历,springboot和springcloud带来了极大的开发便捷性,由本人极力主张将后端开发栈转为springcloud,但便利的同时,也带来了更多的不透明,随之也就会出现各种各样的问题。
继续提高技术内力、充分学会各种分析工具、掌握正确的代码阅读方法,才能应对未知的问题。
欢迎各位提建议,交流。

相关文章

  • spring-cloud-netflix-core引发的一次内存

    发现问题 公司线上的服务运行一段时间后就出现某个服务节点无响应,查看内存监控,对应的Jvm的堆耗尽。好在服务是多节...

  • Android常见问题之内存泄漏

    一、定义 内存泄漏是指:应该被GC回收的对象无法被回收,这个对象会引发内存泄漏。 二、危害 1、引发内存溢出;2、...

  • JAVA 内存溢出问题总结

    现场内存溢出问题引发的思考

  • 记一次面试

    内存泄漏和内存溢出 概念 内存泄漏:垃圾回收器无法回收原本应该被回收的对象,这个对象就引发了内存泄露。 内存溢出:...

  • Android常见问题之内存溢出(OOM)

    一、原因 1、内存泄漏导致频繁的内存泄漏将会引发内存溢出;2、占用内存较多的对象保存了多个耗用内存较多的对象(如B...

  • 一次"内存泄漏"引发的血案

    2017年末,手Q春节红包项目期间,为保障活动期间服务正常稳定,我对性能不佳的Ark Server进行了改造和重写...

  • RecyclerView引发的内存泄露

    原创 @shhp 转载请注明作者和出处 背景说明 为了使问题更加清晰,我将出现问题的场景进行简化抽象。现在有一个A...

  • NSTimer引发的内存泄露

    接手的项目中短信验证码界面使用了NSTimer做倒计时操作,在登录成功后页面已关闭但未对NSTimer做处理,导致...

  • performSeletor引发的内存泄漏

    performSelector是一个很有用的函数,跟它打过不少交道,经过血与泪的教训,总结一下它的使用如下: 使用...

  • Handler引发的内存泄漏

    在我们写代码的时候,为了实现在子线程更新UI的需要,我们会定义一个Handler属性,并声明一个匿名内部类,重写h...

网友评论

      本文标题:spring-cloud-netflix-core引发的一次内存

      本文链接:https://www.haomeiwen.com/subject/yvebwctx.html