首先构建非切片连接池jedisPool对象,写好配置redis连接的方法。
/**
* 构建redis切片连接池
*
* @param ip
* @param port
* @return JedisPool
*/
public static JedisPool getJedisPool() {
if (jedisPool == null) {
synchronized (lock) {
//redis服务器对应的IP和端口
String redisIp = PropertiesUtils.getProperties("REDIS_SERVER_IP");
Integer redisPort = Integer.valueOf(PropertiesUtils.getProperties("REDIS_SERVER_PORT"));
if (jedisPool == null) {
JedisPoolConfig config = new JedisPoolConfig();
//设置连接池初始化大小和最大容量
// 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(-1);
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
config.setMaxIdle(1000);
// 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(1000 * 30);
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
config.setTestOnBorrow(true);
// 写
jedisPool = new JedisPool(config, redisIp, redisPort,DEFAULT_TIME_OUT);
}
}
}
return jedisPool;
}
我们都知道redis是key,value型就当它是内存数据库把,虽然一般常用于数据缓存,毕竟你往内存中放几千万条数据会弄爆- -(虽然我就是要这么干) 下来,根据key获取value
/**
* 获取数据
*
* @param key
* @return
*/
public static String getForString(String key){
List<String> values = mgetForString(key);
if(values == null) {
return null;
} else {
return values.get(0);
}
}
也可根据key获取value的集合
/**
* 获取数据
*
* @param key
* @return
*/
public static List<String> mgetForString(String... key){
List<String> value = null;
JedisPool pool = null;
Jedis jedis = null;
try {
pool = getJedisPool();
jedis = pool.getResource();
value = jedis.mget(key);
} catch (Exception e) {
log.error(e);
} finally {
//返还到连接池
returnJedisResource(jedis);
}
return value;
}
将数据加载到redis中的方法 一般是用set. 如下列方法,这里指定value是String类型,也是因为我的业务关系把value转成了json串~
public static void setForString(String key,String value){
JedisPool pool = null;
Jedis jedis = null;
try {
pool = getJedisPool();
jedis = pool.getResource();
jedis.set(key, value);
} catch (Exception e) {
log.error(e);
} finally {
//返还到连接池
returnJedisResource(jedis);
}
}
也可获取哈希结构的字段和值
/**
* 设置哈希结构的字段和值
* @param key
* @param value
*/
public static void setForHashObj(String key, Map<String, String> value) {
JedisPool pool = null;
Jedis jedis = null;
try {
pool = getJedisPool();
jedis = pool.getResource();
jedis.hmset(key, value);
} catch (Exception e) {
log.error(e);
} finally {
// 返还到连接池
returnJedisResource(jedis);
}
}
这里的Map也可以改为List<Map<String, String>> values,其实一样的~然后再遍历这个Map即可~