Java使用Lettuce操作redis
maven 包
# 包含了lettuce jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
LettuceRedisUtils
package com.meeno.chemical.common.redis;
import com.alibaba.fastjson.JSONObject;
import com.meeno.chemical.common.constants.Constants;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import java.util.List;
/**
-
@description: lettuceRedis 工具类
-
@author: Wzq
-
@create: 2020-08-05 19:34
*/
public class LettuceRedisUtils {
/**
-
获取 command
-
@return
*/
private static RedisURI getRedisUri(){
String host = RedisConfig.host;
Integer port = RedisConfig.port;
String password = RedisConfig.password;
Integer database = RedisConfig.database;
RedisURI redisUri = RedisURI.Builder.redis(host)
.withPort(port)
.withPassword(password)
.withDatabase(database)
.build();
return redisUri;
}
/**
-
匹配 key 返回匹配的 key 列表
-
@param keys
-
@return
*/
public static List<String> keys(String keys){
RedisURI redisUri = getRedisUri();
RedisClient client = RedisClient.create(redisUri);
StatefulRedisConnection<String, String> connect = client.connect();
RedisCommands<String, String> commands = connect.sync();
List<String> keyList = commands.keys(keys);
connect.close();
client.shutdown();
return keyList;
}
/**
-
设置 key, 和 value 失效时间为一天
-
@param key
-
@param value
*/
public static void set(String key,String value){
RedisURI redisUri = getRedisUri();
RedisClient client = RedisClient.create(redisUri);
StatefulRedisConnection<String, String> connect = client.connect();
RedisCommands<String, String> commands = connect.sync();
commands.setex(key, Constants.DAY_SECOND ,value);
connect.close();
client.shutdown();
}
/**
- 设置 key, 和 value 失效时间为一天
- @param key
- @param value
*/
public static void set(String key, Object value){
String valueStr = null;
if(value != null){
valueStr = JSONObject.toJSONString(value);
}
set(key, valueStr);
}
public static String get(String key){
<span class="hljs-type">RedisURI</span> <span class="hljs-variable">redisUri</span> <span class="hljs-operator">=</span> getRedisUri();
<span class="hljs-type">RedisClient</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> RedisClient.create(redisUri);
StatefulRedisConnection<String, String> connect = client.connect();
RedisCommands<String, String> commands = connect.sync();
<span class="hljs-type">String</span> <span class="hljs-variable">s</span> <span class="hljs-operator">=</span> commands.get(key);
connect.close();
client.shutdown();
<span class="hljs-keyword">return</span> s;
}
}