# 包含了lettuce jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
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){
RedisURI redisUri = getRedisUri();
RedisClient client = RedisClient.create(redisUri);
StatefulRedisConnection<String, String> connect = client.connect();
RedisCommands<String, String> commands = connect.sync();
String s = commands.get(key);
connect.close();
client.shutdown();
return s;
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章