通过fastjson对对象进行序列化和反序列化
public class RedisUtil {
private static final String host = "localhost";
private static final int port = 6379;
public static final RedisClient redisClient = RedisClient.create(RedisURI.builder().withHost(host).withPort(port)
.build());
public static RedisClient getRedisClient() {
return redisClient;
}
public static <T> T get(String key, Class<T> clazz) {
return JSONObject.parseObject(get(key), clazz);
}
public static String get(String key) {
return execute(o -> o.get(key));
}
public static <T> String set(String key, T value) {
return set(key, JSON.toJSONString(value));
}
public static <T> String set(String key, String value) {
return execute(o -> o.set(key, value));
}
public static <T> T execute(Function<RedisCommands<String, String>, T> function) {
return execute(getRedisClient(), function);
}
public static <T> T execute(RedisClient redisClient, Function<RedisCommands<String, String>, T> function) {
try (StatefulRedisConnection<String, String> connect = redisClient.connect()) {
return execute(connect, function);
}
}
public static <T> T execute(StatefulRedisConnection<String, String> connect, Function<RedisCommands<String, String>, T> function) {
return function.apply(connect.sync());
}
}
该代码示例展示了如何利用Fastjson库进行对象的序列化和反序列化,并结合RedisClient与Redis进行数据的存取操作。主要方法包括获取Redis客户端、从Redis中获取和设置键值对,以及执行Redis命令。
654

被折叠的 条评论
为什么被折叠?



