依赖包
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.2.0</version> </dependency>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct;
@Component
public class RedisUtils {
private static JedisPool[] jedisPools;
@Value("${redis.host}")
private String host;
@Value("${redis.password}")
private String password;
@Value("${redis.port}")
private String port;
@Value("${redis.maxInst}")
private Integer maxInst;
@Value("${redis.maxIdle}")
private Integer maxIdle;
@Value("${redis.maxWait}")
private Integer maxWait;
@Value("${redis.timeout}")
private Integer timeout;
@PostConstruct
public void init() {
createJedisPools();
}
private void createJedisPools() {
String[] hosts = host.split(",");
String[] ports = port.split(",");
String[] passwords = password.split(",");
jedisPools = new JedisPool[hosts.length];
JedisPoolConfig config = new JedisPoolConfig();
for (int i = 0; i < hosts.length; i++) {
if (passwords != null && i < passwords.length && passwords[i] != null) {
jedisPools[i] = new JedisPool(config, hosts[i], Integer.parseInt(ports[i]), timeout, passwords[i]);
} else {
jedisPools[i] = new JedisPool(config, hosts[i], Integer.parseInt(ports[i]),timeout);
}
}
}
/**
* 获取Redis连接
* @param index Redis实例的索引号
* @return Redis连接
*/
public static Jedis getJedis(int index) {
return jedisPools[index].getResource();
}
/**
* 写入数据
* @param index Redis实例的索引号
* @param key 键
* @param value 值
* @return 写入是否成功
*/
public static boolean set(int index, String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis(index);
jedis.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 删除数据
* @param index Redis实例的索引号
* @param key 键
* @return 删除的记录数
*/
public static long del(int index, String key) {
Jedis jedis = null;
try {
jedis = getJedis(index);
return jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static boolean set(String key, String value) {
boolean success = true;
//RedisUtils.createJedisPools();
for (JedisPool pool : jedisPools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
success = false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
return success;
}
public static long del(String key) {
long total = 0;
for (JedisPool pool : jedisPools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
total += jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
return total;
}
}