基于Redission 封装的工具类及使用示例1
工具类:
下面是一个简单的 Redisson Java 工具类示例,它包含了批量操作和异步操作的方法。
这个类使用了 Redisson 的 RBucket
和 RBatch
接口来执行同步和异步的批量操作。
import com.google.common.collect.Lists;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.redisson.config.Config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
public class RedissonUtils {
private final RedissonClient redissonClient;
public RedissonUtils(String redisUrl) {
Config config = new Config();
config.useSingleServer().setAddress(redisUrl);
this.redissonClient = Redisson.create(config);
}
// 同步批量设置键值对
public void setBulk(Map<String, Object> keyValueMap) {
RBatch batch = redissonClient.createBatch();
keyValueMap.forEach((key, value) ->
batch.getBucket(key).setAsync(value)
);
batch.execute();
}
// 异步批量获取键值对
public CompletionStage<Map<String, Object>> getBulkAsync(Iterable<String> keys) {
RBatch batch = redissonClient.createBatch();
keys.forEach(key ->
batch.getBucket(key).getAsync()
);
return batch.executeAsync().thenApply(responses -> {
// 处理结果
Map<String, Object> results = new HashMap<>();
int i = 0;
for (String key : keys) {
results.put(key, responses.getResponses().get(i));
i++;
}
return results;
});
}
// 异步设置单个键值对
public CompletionStage<Void> setAsync(String key, Object value) {
RBucket<Object> bucket = redissonClient.getBucket(key);
return bucket.setAsync(value).thenAccept(result -> {
System.out.println("Key " + key + " set successfully");
});
}
// 异步获取单个键值
public RFuture getAsync(String key) throws ExecutionException, InterruptedException {
RBucket<Object> bucket = redissonClient.getBucket(key);
return bucket.getAsync();
}
public <V> List<V> getObject(List<String> keyList) {
List<V> results = new ArrayList<>(keyList.size());
List<List<String>> spilts = Lists.partition(keyList, 1000);
spilts.forEach(
singleKeyList -> {
RBatch batch = redissonClient.createBatch();
singleKeyList.forEach(
key -> batch.getBucket(key).getAsync()
);
BatchResult baseBatchResult = batch.execute();
results.addAll(baseBatchResult.getResponses());
}
);
return results;
}
public <V> List<V> getMap(List<String> keyList, String fieldKey) {
List<V> results = new ArrayList<>(keyList.size());
List<List<String>> spilts = Lists.partition(keyList, 1000);
spilts.forEach(
singleKeyList -> {
RBatch batch = redissonClient.createBatch();
singleKeyList.forEach(
key -> batch.getMap(key).getAsync(fieldKey)
);
BatchResult baseBatchResult = batch.execute();
results.addAll(baseBatchResult.getResponses());
}
);
return results;
}
// 关闭 Redisson 客户端
public void shutdown() {
redissonClient.shutdown();
}
}
在这个工具类中,我们实现了以下方法:
setBulk
: 批量同步设置多个键值对。getBulkAsync
: 异步批量获取多个键的值,并返回一个CompletionStage
对象。setAsync
: 异步设置单个键值对,并在操作完成后打印一条消息。getAsync
: 异步获取单个键的值,并返回一个CompletionStage
对象。shutdown
: 用于关闭 Redisson 客户端。
测试类:
使用这个工具类的示例:
import com.google.common.collect.Lists;
import org.redisson.api.RFuture;
import org.redisson.api.RedissonClient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
public class RedissonManagerExample {
private RedissonClient redissonClient; // 假设这是您的Redisson客户端实例
public RedissonManagerExample(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
// 假设这些是您的RedissonManager类中的方法
// ...(上面提供的方法)
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建 RedissonManager 实例
RedissonUtils redissonManager = new RedissonUtils("IP"); // 使用您的redissonClient实例
// 同步批量设置键值对
Map<String, Object> keyValueMap = new HashMap<>();
keyValueMap.put("key1", "value1");
keyValueMap.put("key2", "value2");
redissonManager.setBulk(keyValueMap);
// 异步批量获取键值对
Iterable<String> keys = keyValueMap.keySet();
CompletionStage<Map<String, Object>> getBulkStage = redissonManager.getBulkAsync(keys);
// 处理异步批量获取结果
getBulkStage.thenAccept(results -> {
results.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
});
// 异步设置单个键值对
String newKey = "key3";
String newValue = "value3";
CompletionStage<Void> setAsyncStage = redissonManager.setAsync(newKey, newValue);
// 处理异步设置单个键值对的结果
setAsyncStage.thenRun(() -> System.out.println("Async set operation completed for key: " + newKey));
// 等待异步操作完成以避免程序过早退出
// 注意:在实际应用中,您可能会有更复杂的流程来管理程序的生命周期
Thread.sleep(1000); // 简单的延时等待异步操作完成
// 异步获取单个键值
String key = "sampleKey";
RFuture<Object> future = redissonManager.getAsync(key);
future.whenComplete((result, exception) -> {
if (exception != null) {
System.err.println("An error occurred: " + exception.getMessage());
} else {
System.out.println("Fetched value: " + result);
}
});
// 同步批量获取多个键的值
List<String> key1 = Lists.newArrayList("key1", "key2", "key3");
List<Object> values = redissonManager.getObject(key1);
System.out.println("Fetched values: " + values);
// 同步批量获取多个键对应的 Map 中特定字段的值
String fieldKey = "field1";
List<Object> fieldValues = redissonManager.getMap(keys, fieldKey);
System.out.println("Fetched field values: " + fieldValues);
// 关闭 Redisson 客户端
redissonManager.shutdown();
}
请注意,这个工具类需要一个运行中的 Redis 服务器,并且你需要将 "redis://127.0.0.1:6379" 替换为你的 Redis 服务器地址。此外,在实际的生产环境中,你可能需要添加更多的错误处理和配置选项。
转载自:https://juejin.cn/post/7360996405580038179