引入guava包:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.2</version>
</dependency>
public class PreconditionsExample {
public static void main(String[] args) {
/**
* 對象判空處理
*/
UserInfo userInfo = null;
Preconditions.checkNotNull(userInfo, "userInfo不能爲null");
/**
* List對象判空處理
*/
List<String> list = Lists.newArrayList();
Preconditions.checkNotNull(list, "傳入的list不能爲null");
/**
* 數值類型判斷處理
*/
Long projectId = -12L;
Preconditions.checkNotNull(projectId, "projectId不能爲null");
Preconditions.checkArgument(projectId > 0, "輸入projectId必須大於0", projectId);
}
class UserInfo{
private String name;
}
}
@Slf4j
public class OptionalExample {
public static void main(String[] args) {
Optional<UserInfo> userInfo = Optional.ofNullable(getUserInfo());
if (!userInfo.isPresent()){
log.info("userInfo is null");
}
Optional<Long> projectIdOptional = Optional.ofNullable(getProjectId());
Long projectId = projectIdOptional.orElse(0L); // 如果projectId爲null時,這值爲0
}
public static UserInfo getUserInfo() {
return null;
}
public static Long getProjectId() {
return null;
}
@Getter
@Setter
class UserInfo{
private String userName;
}
}
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
@Slf4j
public class RetryerExample {
public static void main(String[] args) throws Exception {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Predicates.<Boolean>isNull()) // 設置自定義段元重試源
.retryIfExceptionOfType(Exception.class) // 設置異常重試源
.retryIfRuntimeException() // 設置異常重試源
.withStopStrategy(StopStrategies.stopAfterAttempt(5)) // 設置重試次數 設置重試超時時間????
.withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS)) // 設置每次重試間隔
.build();
Callable<Boolean> task = new Callable<Boolean>() {
int i = 0;
@Override
public Boolean call() throws Exception {
i++;
log.info("第{}次執行!", i);
if (i<3) {
log.info("模擬執行失敗");
throw new IOException("異常");
}
return true;
}
};
try {
retryer.call(task);
} catch (ExecutionException e) {
log.error("error", e);
} catch (RetryException e) {
log.error("error", e);
}
Boolean result = task.call();
log.info("成功輸出結果:{}", result);
}
}