zoukankan      html  css  js  c++  java
  • Guava 常用工具类

    引入guava包:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>11.0.2</version>
    </dependency>
    1、Preconditions 前置校验
    前置条件适用于当判断与设置的条件不符合时,抛出异常的操作。(注意:是抛出异常,对于那些想在判空时做相应的处理可以用jdk8中的Optional)
    下面给出:
    1)对象判空,抛出异常
    2)List对象判空,抛出异常
    3)数字类型条件判断,抛出异常
    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;
        }
    }
    利用Otpinal来对返回的单个对象进行包装(注意:所有的对象都要封装)
    下面的例子中,判断UserInfo是否为null,以及对于Long类型如果为null,比如,前段没有传递该参数则,此时可以将其设置为0。
    @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;
        }
    }

    2、retryer实现接口重试机制
    在日常开发中,经常会遇到需要调用外部服务和接口的场景。外部服务对于调用者来说一般是不靠谱的,尤其是在网络环境比较差的情况下,网络抖动很容易导致请求超时等异常情况,这时候需要使用失败重试调用API接口来获取。
    (1)需要再引入guava-retrying包:

    <dependency>
        <groupId>com.github.rholder</groupId>
        <artifactId>guava-retrying</artifactId>
        <version>2.0.0</version>
    </dependency>

    (2)实现代码示例如下:

    @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次之后,成功返回数据。

    3、本地内存 Guava Cache
    缓存有分布式缓存和本地缓存,这里主要介绍Google中的Guava工具包中实现的本地缓存工具类,能够有效的控制缓存的策略。
    https://segmentfault.com/a/1190000011105644

     

  • 相关阅读:
    hihoCoder#1040 矩形判断
    hihoCoder#1038 01背包
    hihoCoder#1037 数字三角形
    hihoCoder#1120 小Hi小Ho的惊天大作战:扫雷·三
    hihoCoder#1119 小Hi小Ho的惊天大作战:扫雷·二
    Python核心编程读笔 3
    Python核心编程读笔 2
    EC读书笔记系列之12:条款22、23、24
    Linux程序设计 读笔2 Shell脚本
    Linux程序设计 读笔1
  • 原文地址:https://www.cnblogs.com/leeego-123/p/11393258.html
Copyright © 2011-2022 走看看