通过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());
}
}