超時(shí)
超時(shí)按照種類來(lái)分充择,有兩種:
- 連接超時(shí):connectiontimeout
- 讀取超時(shí): readtimeout
超時(shí)按照方向來(lái)分取胎,也有兩種:
- 客戶端調(diào)用超時(shí)
- 服務(wù)端超時(shí)
一般發(fā)生超時(shí)的情況都是在涉及到跨系統(tǒng)調(diào)用的場(chǎng)景展哭。有網(wǎng)絡(luò)請(qǐng)求湃窍,所以才會(huì)有超時(shí)。內(nèi)部超時(shí)可能更多的是讀取超時(shí)匪傍。因?yàn)樵谝慌_(tái)服務(wù)器您市,一個(gè)應(yīng)用內(nèi)部,方法阻塞役衡,導(dǎo)致調(diào)用的讀取超時(shí)茵休。
對(duì)于超時(shí)的處理,我們一般如下處理方式:
我們的場(chǎng)景是:A系統(tǒng)調(diào)用B系統(tǒng)映挂。我們需要考慮如下幾種情況:
- A在調(diào)用B的時(shí)候泽篮,網(wǎng)絡(luò)出現(xiàn)異常
- A在調(diào)用B的時(shí)候,B系統(tǒng)收到請(qǐng)求柑船,處理超時(shí)帽撑,A遲遲收不到結(jié)果。
在以上兩種情況下鞍时,我們分別做如下處理
- 對(duì)于第一種情況亏拉,屬于網(wǎng)絡(luò)超時(shí),這個(gè)時(shí)候B系統(tǒng)無(wú)能為力逆巍,A系統(tǒng)需要做一些超時(shí)的處理機(jī)制及塘。即對(duì)connectiontimeout的異常做捕獲處理。
我們?cè)谖⒎?wù)架構(gòu)中锐极,一般會(huì)使用feignclient或者resttemplate來(lái)進(jìn)行請(qǐng)求的發(fā)送笙僚,底層可能用的是httpclient或者OKhttp,http本質(zhì)還是tcp灵再,所以對(duì)于網(wǎng)絡(luò)連接成功與否是有感知的肋层。因此這兩個(gè)通訊組件都封裝了connectiontimetou異常。
對(duì)于調(diào)用方翎迁,你需要去考慮這個(gè)連接超時(shí)的異常栋猖。
- 對(duì)于第二種情況,屬于讀取超時(shí)汪榔。那么和第一種情況一樣蒲拉,通訊組件能感知到這種情況,A系統(tǒng)的通訊組件痴腌,需要對(duì)這種異常做處理雌团。
比較完美的處理方式是B系統(tǒng)也要考慮這種情況。打個(gè)俗氣點(diǎn)的比方士聪,你自己不是傻逼辱姨,但是你不能保證來(lái)調(diào)用你的人不是傻逼。所以戚嗅,你要防止調(diào)用你的人沒(méi)有做超時(shí)處理,他的連接一直和你保持,最后懦胞,他的系統(tǒng)連接無(wú)法釋放替久,你的也是。你們兩個(gè)系統(tǒng)都掛了躏尉。
所以蚯根,比較好的處理方式是B系統(tǒng)在某些可能會(huì)發(fā)生異常的接口層面增加超時(shí)機(jī)制。springcloud的hystrix就是用來(lái)做這個(gè)的胀糜。超時(shí)熔斷颅拦,或者信號(hào)量累計(jì)請(qǐng)求,進(jìn)行錯(cuò)誤比例的熔斷策略教藻。這個(gè)是從被調(diào)用方的角度距帅,來(lái)幫忙防止調(diào)用方未做讀取超時(shí)處理導(dǎo)致兩個(gè)系統(tǒng)都掛掉的一種補(bǔ)償手段。B系統(tǒng)做了這個(gè)控制括堤,那么隨便上游系統(tǒng)是否傻逼碌秸,你都不用怕被上游拖掛了。
最后悄窃,奉上一段代碼讥电,feign-client和hystrix的:
@Service
@DefaultProperties(defaultFallback = "fallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
@Slf4j
public class DemoService {
@Autowired DemoClient demoClient;
public static AtomicInteger number = new AtomicInteger(0);
public Optional<String> demo() {
return Optional.ofNullable(demoClient.callDemo());
}
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000000"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
@HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),
@HystrixProperty(name = "fallback.enabled",value = "true")
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maxQueueSize", value = "101"),
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public String hystrixTest() {
try {
TimeUnit.SECONDS.sleep(6000);//為了測(cè)試execution.isolation.thread.timeoutInMilliseconds參數(shù)
} catch (InterruptedException e) {
// e.printStackTrace();
}
log.info("into service......");
test();
return "hystrix";
}
public String fallback() {
log.info("into fallback....");
return "fallback";
}
public void test() {
int num = number.addAndGet(1);
log.info("into test method,not throw exception...");
if(num>5) {
log.info("throw an exception....");
throw new NullPointerException();
}
}
///////////////////測(cè)試默認(rèn)的超時(shí)//////
@HystrixCommand
public String defaultTimeoutTest() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
return "default timeout...";
}
}
在application.yml文件中,對(duì)feign的重試關(guān)閉:
server:
port: 8086
host: localhost
spring:
application:
name: eureka-client
eureka:
instance:
hostname: eureka-client
prefer-ip-address: true
instance-id: ${spring.cloud.client.ipAddress}:${server.port}
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://${server.host}:8083/eureka/,http://${server.host}:8084/eureka/,http://${server.host}:8085/eureka/
registry-fetch-interval-seconds: 30
eureka-service-url-poll-interval-seconds: 10
ribbon:
MaxAutoRetriesNextServer: -1
feign:
okhttp:
enabled: true
compression:
request:
enabled: true # You may consider enabling the request or response GZIP compression for your Feign requests. You can do this by enabling one of the properties:
response:
enabled: true
在啟動(dòng)類中轧抗,A系統(tǒng)設(shè)置超時(shí)策略
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class,args);
}
@Bean
Request.Options options() {
return new Request.Options(1000*10,40*1000);
}
}