java jedis连接_JAVA中通过Jedis操作Redis连接与插入简单库

packagecom.test.utils.redis;importlombok.extern.log4j.Log4j2;importredis.clients.jedis.Jedis;importredis.clients.jedis.JedisPool;importredis.clients.jedis.JedisPoolConfig;importredis.clients.jedis.Pipeline;importcom.test.utils.redis.items.KvItem;importjava.io.IOException;importjava.util.List;

@Log4j2public classRedisUtils {private finalJedisPool jedisPool;private intdbIndex;/*Redis辅助插入类。

**/

public RedisUtils(String host, int post, int timeout, String password, boolean ssl, int maxTotal, int maxIdel, intdbIndex) {this.dbIndex =dbIndex;

JedisPoolConfig config= newJedisPoolConfig();

config.setTestOnBorrow(true);

config.setMaxWaitMillis(120000);

config.setMaxIdle(maxIdel);

config.setMaxTotal(maxTotal);

jedisPool= newJedisPool(config, host, post, timeout, password, ssl);

}public booleancheckConnection() {try{

Jedis jedis=jedisPool.getResource();if (jedis != null) {

jedis.close();return true;

}

}catch(Exception ignored) {

log.warn("[checkConnection] check redis connection failed. ", ignored);

}return false;

}private synchronized Jedis getJedis(intmaxRetry) {

Jedis jedis= null;

Exception lastEx= new Exception("no error.");for (int i = 0; i < maxRetry; i++) {if (jedisPool == null) break;try{

jedis=jedisPool.getResource();if (jedis == null) {

Thread.sleep(1000);

}else{

jedis.select(dbIndex);//临时使用

break;

}

}catch(Exception e) {

jedis= null;

lastEx=e;

}

}if (jedis == null) {

log.error("[get a jedis] get a jedis from pools failed, has been retry [" + maxRetry + "] times. please check connection. ", lastEx);

}returnjedis;

}public synchronized boolean add(Listitem) {if (item == null || item.isEmpty()) return true;try{

Jedis jedis= getJedis(300);if (jedis == null) {

log.error("[add to redis] add to [" + item.size() + "] items to redis, but get a jedis failed. please check");return false;

}

Pipeline p=jedis.pipelined();for(KvItem kv : item) {

p.set(kv.getKey(), kv.getValue());

}

p.sync();try{

p.close();

}catch(IOException e) {

log.warn("[add to redis] close jedis Pipeline failed.", e);

}

jedis.close();return true;

}catch(Exception ex) {

log.warn("[add to redis] occur a error.", ex);return false;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值