Guava 經常使用工具類

引入guava包:git

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>11.0.2</version>
</dependency>
一、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;
    }
}

二、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

緩存

相關文章
相關標籤/搜索