Google guava 使用
时间: 2025-06-16 16:23:30 浏览: 17
### Google Guava 库使用教程与示例代码
Google Guava 是一个功能强大的 Java 工具库,提供了许多简化开发的实用工具和方法。以下将详细介绍其核心功能以及相关的示例代码。
#### 1. Guava Cache 使用示例
Guava 提供了本地缓存的支持,可以通过 `CacheBuilder` 来构建缓存实例[^2]。下面是一个简单的缓存示例:
```java
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class GuavaCacheExample {
public static void main(String[] args) {
// 创建缓存实例,设置缓存过期时间为10秒
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100) // 最大缓存条目数为100
.expireAfterWrite(10, TimeUnit.SECONDS) // 缓存写入后10秒过期
.build();
// 添加缓存条目
cache.put("key1", "value1");
// 获取缓存条目
System.out.println("缓存中的值:" + cache.getIfPresent("key1")); // 输出 value1
try {
Thread.sleep(11000); // 等待11秒
} catch (InterruptedException e) {
e.printStackTrace();
}
// 再次获取缓存条目,由于已过期,返回 null
System.out.println("缓存中的值:" + cache.getIfPresent("key1")); // 输出 null
}
}
```
#### 2. Optional 的使用
Guava 提供了 `Optional` 类型来避免空指针异常。以下是使用 `Optional` 的示例代码:
```java
import com.google.common.base.Optional;
public class GuavaOptionalExample {
public static void main(String[] args) {
Optional<String> optional = Optional.of("Hello Guava");
if (optional.isPresent()) {
System.out.println("Optional 值存在:" + optional.get()); // 输出 Hello Guava
} else {
System.out.println("Optional 值不存在");
}
}
}
```
#### 3. Lists 和 Sets 工具类
Guava 提供了许多集合操作的工具类,例如 `Lists` 和 `Sets`,可以方便地进行集合操作[^3]。以下是一个集合过滤的示例:
```java
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class GuavaCollectionsExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("1", "", "2", "3", null);
// 过滤掉空字符串和 null 值
List<String> filteredList = list.stream()
.filter(x -> StringUtils.isNotEmpty(x))
.collect(Collectors.toList());
// 将列表转换为逗号分隔的字符串
String result = Lists.newArrayList(filteredList).stream()
.collect(Collectors.joining(","));
System.out.println("过滤后的结果:" + result); // 输出 1,2,3
}
}
```
#### 4. Retryer 示例
Guava 提供了 `Retryer` 类用于实现重试机制。以下是一个简单的重试示例[^1]:
```java
import com.google.common.util.concurrent.Retryer;
import com.google.common.util.concurrent.RetryerBuilder;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class GuavaRetryerExample {
public static void main(String[] args) throws Exception {
// 构建 Retryer 实例
Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
.retryIfResult(result -> "failure".equals(result)) // 如果结果为 failure 则重试
.retryIfException() // 如果抛出异常则重试
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) // 每次重试等待1秒
.withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 最多重试3次
.build();
try {
String result = retryer.call(() -> {
System.out.println("尝试执行任务...");
return "success"; // 返回 success 表示任务成功
});
System.out.println("任务执行结果:" + result);
} catch (ExecutionException | UncheckedTimeoutException e) {
e.printStackTrace();
}
}
}
```
### 总结
Google Guava 库提供了丰富的工具类和方法,能够显著提升开发效率。上述示例展示了缓存、Optional、集合工具类以及重试机制的使用方法。开发者可以根据具体需求选择合适的工具类进行集成。
阅读全文
相关推荐

















