【Redis-工具类】自定义Redis工具类并使用其进行简单操作
1)自定义 Redis 工具类 2)工具类的简单使用
1)自定义 Redis 工具类
package gaei. cn. x5l. x5lhive2cos. utils ;
import gaei. cn. x5l. x5lhive2cos. CosDataBackupHistory ;
import gaei. cn. x5l. x5lhive2cos. conf. ConfigTools ;
import lombok. extern. slf4j. Slf4j ;
import redis. clients. jedis. Jedis ;
import redis. clients. jedis. JedisPool ;
import redis. clients. jedis. JedisPoolConfig ;
import java. io. Serializable ;
import java. util. Map ;
@Slf4j
public class JedisPoolUtils implements Serializable {
private static JedisPool pool;
private static void createJedisPool ( Map redisMap) {
JedisPoolConfig config = new JedisPoolConfig ( ) ;
config. setMaxTotal ( ( int ) redisMap. get ( "maxtotal" ) ) ;
System . out. println ( "redis连接池最大值:" + ( int ) redisMap. get ( "maxtotal" ) ) ;
config. setMaxIdle ( ( int ) redisMap. get ( "maxidle" ) ) ;
System . out. println ( "redis连接池默认值:" + ( int ) redisMap. get ( "maxidle" ) ) ;
config. setMaxWaitMillis ( ( Integer . parseInt ( String . valueOf ( redisMap. get ( "timeout" ) ) ) ) ) ;
pool = new JedisPool ( config, ( String ) redisMap. get ( "host" ) , ( int ) redisMap. get ( "port" ) , Integer . parseInt ( String . valueOf ( redisMap. get ( "timeout" ) ) ) , ( String ) redisMap. get ( "password" ) ) ;
}
private static synchronized void poolInit ( Map redisMap) {
if ( pool == null ) {
createJedisPool ( redisMap) ;
}
}
public static Jedis getJedis ( Map redisMap) {
if ( pool == null ) {
poolInit ( redisMap) ;
}
Jedis resource = pool. getResource ( ) ;
System . out. println ( "redis 连接状态:" + resource. isConnected ( ) ) ;
return resource;
}
public static void returnResource ( Jedis jedis) {
if ( jedis != null ) {
jedis. close ( ) ;
}
}
public static synchronized void destroy ( ) {
if ( pool != null ) {
pool. close ( ) ;
pool. destroy ( ) ;
}
}
public static void main ( String [ ] args) {
ConfigTools . initMySqlConf ( "CosBackupHistoryOriginal" , CosDataBackupHistory . class ) ;
Map redis = ( Map ) ConfigTools . mapConf. get ( "redis" ) ;
Jedis jedis = getJedis ( redis) ;
jedis. hset ( "test1" , "20230606" , "1" ) ;
String test1 = jedis. hget ( "test1" , "20230606" ) ;
System . out. println ( test1) ;
}
}
2)工具类的简单使用
Jedis jedis = getJedis ( redis) ;
jedis. hset ( key, field, value) ;
if ( "1" . equals ( jedis. hget ( redisKey, partition) ) ) {
return true ;
}
JedisPoolUtils . returnResource ( jedis) ;