springcloud線上發佈超時方案之終極殺招:預熱(測試用例)

springcloud線上發佈超時系列文章:
springcloud線上發佈超時方案之feign優化(ribbon飢餓加載)
springcloud線上發佈超時方案之grpc優化
springcloud線上發佈超時方案之終極殺招:預熱(測試用例)

前言

經過上面兩章的優化,超時報錯有所減少,但是隻是得到了緩解但是當流量切換時還是會有大量超時。

方案

這裏又增加了一個啓動後預熱,即在程序啓動後執行測試用例n次,讓hystrix、web容器線程池等資源初始化。在測試用例執行完成之前,爲了保證服務不對外提供服務,這裏可以分兩種。

延遲註冊到註冊中心

如果時使用註冊中心來進行服務發現等,這裏可以採用延遲註冊來保證測試用例的成功執行,
如果時eureka爲註冊中心可以配置initial-instance-info-replication-interval-seconds參數,默認是40s,可以將其改爲1分鐘

如果是consul或者zk,可以修改響應的延時註冊時間,或者修改服務端有效時間

kubernetes中增加服務ready延時時間

這裏再deploy.yml中配置如下:

spec:
  replicas: 1
  template:
    spec:
      containers:
      - args:
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60  //延遲時間s

案例

這裏測試用例不建議使用spring的 @PostConstruct註解,最好是等web容器啓動就緒後再執行測試用例,這裏給一個我的demo

@Slf4j
public class WebContextInit {

    private RestTemplate restTemplate = new RestTemplate();
    private static WebContextInit webContextInit = new WebContextInit();
    private WebContextInit(){}
    public static WebContextInit getInstance() {
        return webContextInit;
    }

    public void init() {
        if (isTestEnabled()) {
            for(int i=0;i<10;i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String url = "http://localhost:8080/srch-recommend-plt/re-sort";
                    log.warn("WebContextInit.testResort start");
                    String body = "xxxbody";
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("Content-Type", "application/json");
                    HttpEntity<String> entity = new HttpEntity<>(body, headers);
                    for (int i = 0; i < appConfig.getTestCount(); i++) {
                        try {
                            restTemplate.postForObject(url, entity, String.class);
                        } catch (Exception e) {
                            log.error("WebContextInit.testDemo error" + e.getMessage());
                        }
                    }
                    log.warn("WebContextInit.testDemo  end");
                }
            });
            thread.start();
        }
        }

    }



然後在啓動類中初始化:

public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        WebContextInit.getInstance().init();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章