wendu 发表于 2016-12-20 10:28:34

Redis在java中批量操作数据的更新

  背景:同事说Redis在插入数据时,同样存在插入速度慢,只是get获取时快,通过做实验,完全不是那么回事,同事说的话也根本没有找到有关官方的说法,仅仅是凭几个简单的操作,应该是不能作为依据的。
  今天贴出几个批量操作数据的方法(测试的环境是局域网-单机, Linux要快过Windows):
  windows:
  redis_version:2.8.12
redis_mode:standalone
os:Windows
arch_bits:64
multiplexing_api:winsock_IOCP 
  Linux:
  redis_version:2.6.17
redis_mode:standalone
os:Linux 3.10.42-52.145.amzn1.x86_64 x86_64
arch_bits:64
  (redis_version:2.8.17
redis_mode:standalone
os:Linux 2.6.32-33-server x86_64
arch_bits:64)
  这里使用redis的数据类型:hashs 和 lists
  一次性插入100000条数据消耗时间,windows在3秒以内,linux在2秒以内。
  lists数据类型的操作:

/**
* 从尾部开始插入数据(删除并插入新的数据) 队列, 先进先出
* @param db
* @param key
* @param arr
* @return
*/
public static boolean rpush(RedisAPIDao.Db db, String key, String[] arr){
JedisPool pool = null;
Jedis jedis = null;
boolean ret = false;
try {
pool = getPool(key);
jedis = pool.getResource();
jedis.select(db.toIntValue());
if (null != arr && arr.length > 0) {
jedis.del(key);
long value = jedis.rpush(key, arr);
if (value > 0 ) {
ret = true;
}
}
} catch (Exception e) {
pool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
ret = false;
} finally {
returnResource(pool, jedis);
}
return ret;
}
  hashs数据操作:

/**
* 使用通常的方法,hmset hash
* @param db
* @param key
* @param map
* @return
*/
public static boolean hsetMap(RedisAPIDao.Db db, String key, Map<String, String> map) {
JedisPool pool = null;
Jedis jedis = null;
try {
pool = getPool(key);
jedis = pool.getResource();
jedis.select(db.toIntValue());
jedis.hmset(key, map);
} catch (Exception e) {
pool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
returnResource(pool, jedis);
}
return true;
}
/**
* 使用批量方式操作Pipelinehash
* @param db
* @param key
* @param map
* @return
*/
public static boolean hmset(RedisAPIDao.Db db, String key, Map<String, String> map) {
JedisPool pool = null;
Jedis jedis = null;
try {
pool = getPool(key);
jedis = pool.getResource();
jedis.select(db.toIntValue());
Pipeline pipeline = jedis.pipelined();
pipeline.hmset(key, map);
pipeline.sync();
} catch (Exception e) {
pool.returnBrokenResource(jedis);
logger.error(e.getMessage(), e);
} finally {
returnResource(pool, jedis);
}
return true;
}
  hash的两种方式效果差不多(Pipeline批量操作方式稍快)。
  需要jar: jedis-2.4.2.jar

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
</dependency>
页: [1]
查看完整版本: Redis在java中批量操作数据的更新