guava SimpleTimeLImiter進行方法超時呼叫控制
阿新 • • 發佈:2018-12-12
1、基於類級別的呼叫
(1)編寫介面類UserInfoService.java
public interface UserInfoService {
String getUserName() throws InterruptedException;
}
(2)編寫對應的實現類UserInfoServiceImpl.java
public class UserInfoServiceImpl implements UserInfoService { @Override public String getUserName() throws InterruptedException { System.out.println("123"); Thread.sleep(500); System.out.println("456"); return "tim"; } }
(3) 測試程式碼
public static void main(String[] args) { TimeLimiter timeLimiter = new SimpleTimeLimiter(); UserInfoService userInfoService = new UserInfoServiceImpl(); UserInfoService userInfoService1 = timeLimiter.newProxy(userInfoService, UserInfoService.class, 20, TimeUnit.MILLISECONDS); try { String userName = userInfoService1.getUserName(); System.out.println("userName:" + userName); } catch (Exception e) { e.printStackTrace(); } }
(4)綜合上述可以寫成更通用的
/** * @author chenjintian * @email [email protected] * @date 2018/9/29 * Description: */ public class UserInfoServiceImpl implements UserInfoService { private static final TimeLimiter TIME_LIMITER = new SimpleTimeLimiter(); // 設定為可配置 private static final long TIME_OUT_DURATION = 200; private static UserInfoService userInfoServiceProxy; static { UserInfoService userInfoService = new UserInfoServiceImpl(); userInfoServiceProxy = TIME_LIMITER.newProxy(userInfoService, UserInfoService.class, TIME_OUT_DURATION, TimeUnit.MILLISECONDS); } @Override public String getUserName(String info) throws InterruptedException { System.out.println("123"); Thread.sleep(500); System.out.println("456"); return info; } @Override public String getUserNameWithTimeout(String info) throws InterruptedException { return userInfoServiceProxy.getUserName(info); } @Override public String getSex(String txt) { return ""; } @Override public String getSexWithTimeout(String txt) { return userInfoServiceProxy.getSex(txt); } public static void main(String[] args) throws InterruptedException { UserInfoService userInfoService = new UserInfoServiceImpl(); String result = userInfoService.getUserNameWithTimeout("tim"); System.out.println("result is:" + result); } }
2、基於方法級別的呼叫
public class SimpleTimeLimiterDemo {
public static void main(String[] args) {
SimpleTimeLimiter simpleTimeLimiter = new SimpleTimeLimiter();
final AtomicBoolean isInterrupted = new AtomicBoolean();
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
isInterrupted.set(true);
Thread.sleep(200);
isInterrupted.set(false);
return "success";
}
};
try {
String result = simpleTimeLimiter.callWithTimeout(task, 20, TimeUnit.MILLISECONDS, true);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
分析:
上述程式碼實現呼叫方法超時後會報錯。
檢視原始碼本質上,Google的SimpleTimeLimiter是對Executor的future的包裝。