1、服務提供者配置文件:
server:
port: 8001
dubbo:
application:
name: site-service-boot-provider
registry:
address: zookeeper://ubu:2181
scan:
base-packages: com.yas.serviceprovider
#指定某一種協議
protocol:
name: dubbo
port: 20882
2、服務提供者代碼:
1 package com.yas.serviceprovider.timeout; 2 3 import com.yas.api.SiteService; 4 import org.apache.dubbo.config.annotation.Service; 5 //1.如果提供方設置了timeout,而消費方沒有設置,表示消費方采用提供方一樣的timeout 6 //2.如果提供方的實際執行時間比設置的timeout要長,那么會打印超時日志,但服務會正常執行 7 @Service(version = "timeout",timeout = 4000) 8 public class TimeoutSiteServiceImpl implements SiteService { 9 @Override 10 public String getName(String name) { 11 try { 12 Thread.sleep(5000); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 return "timeout:"+name; 17 } 18 }
3、服務消費者代碼:
package com.yas.serviceconsumer.controller; import com.yas.api.SiteService; import org.apache.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TimeoutController { //消費方未設置timeout,提供方也未設置timeout,則默認為1000毫秒超時 //消費方未設置timeout,提供方設置了timeout,則消費方以服務方設置為准 //如果消費方timeout的時間到了,提供方還沒有返回數據,則拋出異常 //如果消費方timeout到之前,已經從提供方獲取了響應,則正常執行 @Reference(version = "timeout",timeout = 2000) SiteService siteService; @RequestMapping("/timeout") public String getName(@RequestParam("name") String name){ return siteService.getName(name); } }
解釋:服務提供者設定了timeout是4000ms,但服務提供者的代碼執行,至少需要5000ms。
因此服務提供者方,會打印warn級別的日志(需要配置log4j)。
而服務的消費方,設定了timeout是2000ms,因此會拋出超時異常。
4、測試:
使用postman請求地址:http://localhost:8000/timeout?name=zhangsan
得到響應如下:
如果將客戶端的timeout設置為12000ms,則正常情況下會正確獲得服務提供方的返回結果。