❝java开发中,你使用的redis client工具是哪一个?
我了解的有jedis,lettuce,redission, spring-redis-templete。
萝卜与青菜
client | 优点 | 缺点 |
---|---|---|
jedis | 老牌,轻量易于改造,支持连接池 | BIO模型,同步方法调用;实例不是线程安全的,需要配合线程池使用;功能单一,高级功能缺失 |
lettuce | 生菜,spring redisTemplate底层默认实现,线程安全;性能高,基于Netty,支持异步方法调用 | 编程模型复杂,不太直观 |
redission | 更高级的工具; 线程安全; 基于Netty,支持异步方法调用,提供分布式相关操作:分布式锁,分布式集合等 | spring boot支持不太友好 |
jedis
从名字来看,就知道和redis
有多亲,作为老牌java client,也确实伴随我写过不少项目,但是因为他实例线程不安全,所以一般都是通过提供的线程池管理,每次操作从线程池中拿到一个实例,处理完毕后,调用jedis.close()
。
所以,使用jedis
的项目,你基本会看到类似如下的代码:
public class JedisUtil {
private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
private static String address;
public static void init(String address) {
JedisUtil.address = address;
getInstance();
}
private static JedisSentinelPool jedisSentinelPool;
private static ReentrantLock INSTANCE_INIT_LOCL = new ReentrantLock(false);
public static void destroy() {
jedisSentinelPool.destroy();
}
/**
* 获取ShardedJedis实例
*
* @return
*/
private static Jedis getInstance() {
if (jedisSentinelPool == null) {
try {
if (INSTANCE_INIT_LOCL.tryLock(2, TimeUnit.SECONDS)) {
try {
if (jedisSentinelPool == null) {
Set sentines = Arrays.stream(address.split(",")).collect(Collectors.toSet());
jedisSentinelPool = new JedisSentinelPool("mymaster",sentines);
}
} finally {
INSTANCE_INIT_LOCL.unlock();
}
}
} catch (InterruptedException e) {
logger.error(e.getMes