spring boot的hystrix组件出现首次调用慢的问题
2022-10-31 本文已影响0人
天草二十六_简村人
一、hystrix调用内部服务慢
image.png image.png二、解决问题
因为我们项目默认使用的是spring懒汉加载模式,导致首次会去做类加载和初始化。这里可以看到耗时长达2100毫秒,所以建议我们对调用量大的依赖服务,修改ribbon为饿汉模式。
这方面的文章比较多,仅收集几个,供参考:
- https://blog.csdn.net/qq_29323645/article/details/105512014
- http://t.zoukankan.com/shaolixin-p-11491791.html
三、配置参考
# feign-client 使用okHttp,开启hystrix熔断
feign:
hystrix:
enabled: true
okhttp:
enabled: true
httpclient:
enabled: false
# ribbon配置
ribbon:
ReadTimeout: 5000
ConnectTimeout: 1000
eager-load:
enabled: true
clients: user-service
# hystrix配置
hystrix:
threadpool:
default:
maximumSize: 500
coreSize: 50
maxQueueSize: 500
keepAliveTimeMinutes: 5
queueSizeRejectionThreshold: 3001
command:
default:
execution:
isolation:
strategy: THREAD
semaphore:
maxConcurrentRequests: 2000
thread:
timeoutInMilliseconds: 15000
四、其他超时时间
4.1、RestTemplate
不能直接new实例,一定要配置RestTemplateConfig。
// 错误实现
private final static RestTemplate restTemplate = new RestTemplate();
- 正确的做法
@Autowired
private RestTemplate restTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate getRestTemplate() {
//配置HTTP超时时间
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(10000);
httpRequestFactory.setReadTimeout(5000);
return new RestTemplate(httpRequestFactory);
}
}
4.2、hutool http
别忘记了设置连接超时和读写超时。
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;
@Service
@Slf4j
@RequiredArgsConstructor
public class MessagePushService {
private final CommonConfig commonConfig;
/**
* 连接超时
*/
private static final int connectionTimeout = 10000;
/**
* 读取超时
*/
private static final int readTimeout = 5000;
private HttpRequest httpRequest;
@PostConstruct
public void init() {
httpRequest = HttpUtil.createPost(commonConfig.getMessagePushUrl() + "/message/send");
}
public void send(String userIds, String payload) {
List<PushMessageRequest> bodyList = Lists.newArrayList();
// TODO 给bodyList赋值
HttpResponse httpResponse = httpRequest.body(JSON.toJSONString(bodyList),
ContentType.build(ContentType.JSON.getValue(), Charset.defaultCharset()))
.setConnectionTimeout(connectionTimeout)
.setReadTimeout(readTimeout).execute();
if (httpResponse.isOk()) {
log.info("调用XX服务成功, userIds={}, payload={}, 请求报文:{}, 响应报文:{}",
userIds, payload, JSON.toJSONString(bodyList), httpResponse.body());
} else {
log.error("调用XX服务失败,userIds={}, payload={}, 请求报文:{}",
userIds, payload, JSON.toJSONString(bodyList));
}
}
}