记一次spring boot线上项目内存溢出

Scroll Down

问题描述

今天被告知一个线上项目报错跑不通了,两台同样的项目通过负载提供服务,随即查看生产日志,其中一台正常,另一台发现报错信息为内存溢出,报错堆栈信息如下:

2019-09-07 13:37:00,667 ERROR (DirectJDKLog.java:175)- Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null
	at org.springframework.util.LinkedCaseInsensitiveMap.convertKey(LinkedCaseInsensitiveMap.java:283)
	at org.springframework.util.LinkedCaseInsensitiveMap.containsKey(LinkedCaseInsensitiveMap.java:135)
	at org.springframework.util.CollectionUtils$MultiValueMapAdapter.containsKey(CollectionUtils.java:507)
	at org.springframework.http.HttpHeaders.containsKey(HttpHeaders.java:1622)
	at org.springframework.http.client.support.BasicAuthenticationInterceptor.intercept(BasicAuthenticationInterceptor.java:81)
	at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:92)
	at org.springframework.http.client.support.BasicAuthenticationInterceptor.intercept(BasicAuthenticationInterceptor.java:84)
	at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:92)

出错代码

 @Override
    public boolean isOnLine(String clientId){
		restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("admin", "public"));
    }
由于每次请求都会new BasicAuthenticationInterceptor添加到list中,大量请求导致内存溢出。

解决方案

将添加验证信息的方法单独提出来,每次请求执行一次即可。即bean初始化时添加用户名密码。记录代码如下:

#该类实现InitializingBean接口。
/**
     * bean初始化之后动作
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //rest template认证
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("admin", "public"));
    }