Guava使用
时间: 2023-06-28 15:15:08 浏览: 212
Guava是Google提供的一个Java开发库,提供了许多常用的工具类和方法,可以帮助我们更加方便地进行Java开发。它包含的功能非常丰富,涵盖了集合、缓存、并发、字符串处理、IO、数学等多个领域。
下面是一个简单的示例,展示了如何使用Guava的集合工具类:
```
import com.google.common.collect.Lists;
import java.util.List;
public class GuavaDemo {
public static void main(String[] args) {
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);
}
}
```
这段代码中,我们使用了Guava中的List工具类和partition方法,将原来的List拆分成了多个子List。可以看出,Guava的使用非常简单,只需要引入相应的依赖,就可以轻松地使用其中的工具类和方法。
相关问题
Google guava 使用
### 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、集合工具类以及重试机制的使用方法。开发者可以根据具体需求选择合适的工具类进行集成。
Guava缓存使用
Guava缓存是一个内存缓存框架,它可以帮助我们快速存储和访问数据,提高应用程序的性能。下面是使用Guava缓存的步骤:
1.引入Guava依赖:在pom.xml文件中添加Guava依赖:
```
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
```
2.创建缓存对象:使用CacheBuilder类创建缓存对象。可以设置缓存的最大大小、过期时间、并发级别等。
```
Cache<String, Object> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.concurrencyLevel(4)
.build();
```
3.向缓存中添加数据:使用put方法向缓存中添加数据。
```
cache.put("key", "value");
```
4.从缓存中获取数据:使用get方法从缓存中获取数据。如果缓存中不存在该数据,可以使用Callable对象来获取数据并将其添加到缓存中。
```
Object value = cache.get("key", new Callable<Object>() {
@Override
public Object call() throws Exception {
return "default value";
}
});
```
5.清空缓存:可以使用invalidateAll方法清空缓存中的所有数据。
```
cache.invalidateAll();
```
以上就是使用Guava缓存的基本步骤。通过合理地设置缓存的大小、过期时间等参数,可以有效地提高应用程序的性能。
阅读全文
相关推荐














