1. 程式人生 > >Guava 常用工具類

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工具包中實現的本地快取工具類,能夠有效的控制快取的策略。