引入guava包:git
<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; } }
二、retryer实现接口重试机制
在平常开发中,常常会遇到须要调用外部服务和接口的场景。外部服务对于调用者来讲通常是不靠谱的,尤为是在网络环境比较差的状况下,网络抖动很容易致使请求超时等异常状况,这时候须要使用失败重试调用API接口来获取。
(1)须要再引入guava-retrying包:github
<dependency> <groupId>com.github.rholder</groupId> <artifactId>guava-retrying</artifactId> <version>2.0.0</version> </dependency>
(2)实现代码示例以下:segmentfault
@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); } }
分析:
上述中方法调用失败了三次,在重试第4次以后,成功返回数据。
三、本地内存 Guava Cache
缓存有分布式缓存和本地缓存,这里主要介绍Google中的Guava工具包中实现的本地缓存工具类,可以有效的控制缓存的策略。
http://www.javashuo.com/article/p-avaquyum-ht.html
缓存