maven依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
完整代码
package com.xyulu.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* @Author Xyulu
* @Date 2021/3/10 10:35
* @Version 1.0
*/
public class RedisUtil {
private final static Logger log = LoggerFactory.getLogger(RedisUtil.class);
private static RedisUtil instance;
private JedisPoolConfig config;
private JedisPool pool;
public static RedisUtil getInstance() {
if (instance == null) {
synchronized (RedisUtil.class) {
if (instance == null) {
instance = new RedisUtil();
instance.init();
}
}
}
return instance;
}
private void init() {
String ip = "127.0.0.1";
int port = 6379;
String auth = "123ABCdef*";
int timeOut = 1000;
config = new JedisPoolConfig();
config.setMaxIdle(10); // 控制pool中最多有多少个连接给空闲状态
config.setMaxTotal(20); // 控制pool中最大连接实例
config.setMaxWaitMillis(1000); // 最大超时等待时间(毫秒)
config.setTestOnBorrow(true); // 获取连接提前验证
config.setTestOnReturn(true); // 归还连接提前验证
pool = new JedisPool(config,ip,port,timeOut,auth);
}
/**
* 获取Jedis
* @return Jedis
*/
public Jedis getClient(){
if (pool == null) {
init();
}
return pool.getResource();
}
/**
* 关闭jedis连接池
* @param jedis
*/
private void returnJedis (Jedis jedis) {
if (jedis != null){
try{
jedis.close();
}catch (Exception e){
log.error("Jedis关闭异常,ecxeption is {}",e);
}
}
}
public String set(String key, String value) {
String result = null;
if (pool == null) {
init();
}
Jedis resource = pool.getResource();
try {
result = resource.set(key, value);
} catch (Exception e) {
log.error("set key is error ,exception is {}",e);
} finally {
if (resource != null) {
resource.close();
}
}
return result;
}
public String get (String key) {
String value = null;
if (pool == null) {
init();
}
Jedis resource = pool.getResource();
try {
value = resource.get(key);
} catch (Exception e) {
log.error("get value is error ,exception is {}",e);
} finally {
if (resource != null) {
resource.close();
}
}
return value;
}
}