个人把工具类分为两部分:

一、连接池部分

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class JedisPoolUtil {protected static Logger logger = LoggerFactory.getLogger(JedisPoolUtil.class);public static JedisPool jedisPool = null;private String host;private int port;private int maxTotal;private int maxIdle;private int minIdle;private boolean blockWhenExhausted;private int maxWaitMillis;private boolean testOnBorrow;private boolean testOnReturn;public static Lock lock = new ReentrantLock();private void initialConfig() {try {InputStream stream = JedisUtilBak.class.getClassLoader().getResourceAsStream("config.properties");Properties prop = new Properties();prop.load(stream);host = prop.getProperty("redis.host");port = Integer.parseInt(prop.getProperty("redis.port"));maxTotal = Integer.parseInt(prop.getProperty("redis.maxTotal"));maxIdle = Integer.parseInt(prop.getProperty("redis.maxIdle"));minIdle = Integer.parseInt(prop.getProperty("redis.minIdle"));blockWhenExhausted = Boolean.parseBoolean(prop.getProperty("redis.blockWhenExhausted"));maxWaitMillis = Integer.parseInt(prop.getProperty("redis.maxWaitMillis"));testOnBorrow = Boolean.parseBoolean(prop.getProperty("redis.testOnBorrow"));testOnReturn = Boolean.parseBoolean(prop.getProperty("redis.testOnReturn"));//            boolean testWhileIdle = Boolean.parseBoolean(prop.getProperty("redis.testWhileIdle"));
//            int timeBetweenEvictionRunsMillis = Integer.parseInt(prop.getProperty("redis.timeBetweenEvictionRunsMillis"));
//            int minEvictableIdleTimeMillis = Integer.parseInt(prop.getProperty("redis.minEvictableIdleTimeMillis"));
//            int numTestsPerEvictionRun = Integer.parseInt(prop.getProperty("redis.numTestsPerEvictionRun"));} catch (Exception e) {logger.debug("parse configure file error.");}}/*** initial redis pool*/private void initialPool() {if (lock.tryLock()) {lock.lock();initialConfig();try {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(maxTotal);config.setMaxIdle(maxIdle);config.setMaxWaitMillis(maxWaitMillis);config.setTestOnBorrow(testOnBorrow);jedisPool = new JedisPool(config, host, port);} catch (Exception e) {logger.debug("init redis pool failed : {}", e.getMessage());} finally {lock.unlock();}} else {logger.debug("some other is init pool, just wait 1 second.");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}public Jedis getJedis() {if (jedisPool == null) {initialPool();}try {return jedisPool.getResource();} catch (Exception e) {logger.debug("getJedis() throws : {}" + e.getMessage());}return null;}public Pipeline getPipeline() {BinaryJedis binaryJedis = new BinaryJedis(host, port);return binaryJedis.pipelined();}}

二、操作方法部分

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;public class JedisUtil {protected static Logger logger = LoggerFactory.getLogger(JedisUtil.class);public static ReentrantLock lock = new ReentrantLock();private final String DIST_LOCK_SUCCESS = "OK";private final Long DIST_LOCK_RELEASE_SUCCESS = 1L;private final String SET_IF_NOT_EXIST = "NX";private final String SET_WITH_EXPIRE_TIME = "PX";private JedisPoolUtil jedisPool = new JedisPoolUtil();public boolean setString(String key, String value) {Jedis jedis = jedisPool.getJedis();try {jedis.set(key, value);return true;} catch (Exception e) {logger.debug("setString() key {} throws:{}", key, e.getMessage());return false;} finally {close(jedis);}}public boolean setStringEx(String key, int seconds, String value) {Jedis jedis = jedisPool.getJedis();try {jedis.setex(key, seconds, value);return true;} catch (Exception e) {logger.debug("setStringEx() key {} throws:{}",key, e.getMessage());return false;} finally {close(jedis);}}public String getString(String key) {Jedis jedis = jedisPool.getJedis();try {return jedis.get(key);} catch (Exception e) {logger.debug("getString() key {} throws:{}", key,e.getMessage());return null;} finally {close(jedis);}}public boolean delString(String key) {Jedis jedis = jedisPool.getJedis();try {jedis.del(key);return true;} catch (Exception e) {logger.debug("delString() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public boolean delHash(String key, String mKey) {Jedis jedis = jedisPool.getJedis();try {jedis.hdel(key, mKey);return true;} catch (Exception e) {logger.debug("setHash() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public boolean setHash(String key, String mKey, String mVal) {Jedis jedis = jedisPool.getJedis();try {jedis.hset(key, mKey, mVal);return true;} catch (Exception e) {logger.debug("setHash() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public String getHash(String key, String mKey) {Jedis jedis = jedisPool.getJedis();try {return jedis.hget(key, mKey);} catch (Exception e) {logger.debug("setHash() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public boolean setHashMulti(String key, Map<String, String> map) {Jedis jedis = jedisPool.getJedis();try {jedis.hmset(key, map);return true;} catch (Exception e) {logger.debug("setMHash() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public List<String> getHashMulti(String key, String[] members) {Jedis jedis = jedisPool.getJedis();try {return jedis.hmget(key, members);} catch (Exception e) {logger.debug("getHashMulti() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public List<String> getHashValsAll(String key) {Jedis jedis = jedisPool.getJedis();try {return jedis.hvals(key);} catch (Exception e) {logger.debug("getHashValsAll() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public Set<String> getHashKeysAll(String key) {Jedis jedis = jedisPool.getJedis();try {return jedis.hkeys(key);} catch (Exception e) {logger.debug("getHashValsAll() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public boolean addScoreSet(String key, String mKey, int score) {Jedis jedis = jedisPool.getJedis();try {jedis.zadd(key, score, mKey);return true;} catch (Exception e) {logger.debug("addScoreSet() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public boolean delScoreSet(String key, String mKey) {Jedis jedis = jedisPool.getJedis();try {jedis.zrem(key, mKey);return true;} catch (Exception e) {logger.debug("delScoreSet() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public boolean changeScoreSet(String key, String mKey, int score) {Jedis jedis = jedisPool.getJedis();try {jedis.zincrby(key, score, mKey);return true;} catch (Exception e) {logger.debug("changeScoreSet() key {} throws:{}", key,e.getMessage());return false;} finally {close(jedis);}}public Set<String> listScoreSetString(String key, int start, int end, boolean asc) {Jedis jedis = jedisPool.getJedis();try {if (asc) {return jedis.zrange(key, start, end);} else {return jedis.zrevrange(key, start, end);}} catch (Exception e) {logger.debug("listScoreSetString() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public Set<Tuple> listScoreSetTuple(String key, int start, int end, boolean asc) {Jedis jedis = jedisPool.getJedis();try {if (asc) {return jedis.zrangeWithScores(key, start, end);} else {return jedis.zrevrangeWithScores(key, start, end);}} catch (Exception e) {logger.debug("listScoreSetString() key {} throws:{}", key,e.getMessage());} finally {close(jedis);}return null;}public boolean getDistributedLock(String lockKey, String requestId, int expireTime) {Jedis jedis = jedisPool.getJedis();try {String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);if (DIST_LOCK_SUCCESS.equals(result)) {return true;}return false;} catch (Exception e) {
//            logger.debug("getDistributedLock key {} throws:{}", lockKey, e.getMessage());logger.debug("getDistributedLock throws {}", e);} finally {close(jedis);}return false;}public boolean releaseDistributedLock(String lockKey, String requestId) {Jedis jedis = jedisPool.getJedis();try {String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));if (DIST_LOCK_RELEASE_SUCCESS.equals(result)) {return true;}return false;} catch (Exception e) {logger.debug("releaseDistributedLock throws {}", e.getMessage());} finally {close(jedis);}return false;}public void close(Jedis jedis) {if (jedis != null) {jedis.close();}}
}

转载于:https://www.cnblogs.com/yoyotl/p/8677711.html

Jedis工具类(含分布式锁的调用和释放)相关推荐

  1. 【文件压缩解压工具类-含密码】

    文件压缩解压工具类-含密码 一.zip4j简介 二.zip4j工具类使用步骤 1.添加maven依赖 2.工具类代码 3.调用测试 三.结语 一.zip4j简介 zip4j功能比较强大,支持加密.解密 ...

  2. 最强分布式工具Redisson:分布式锁

    一.Redisson概述 什么是Redisson?-- Redisson Wiki Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid).它 ...

  3. 分布式架构-ZK客户端工具Curator框架分布式锁及基本使用

    分布式架构-基于Curator分布式锁及基本使用 一.Curator Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作 ...

  4. JDBC(本质,配置环境变量,JDBC编程六步,类加载注册,sql注入,事务问题,封装工具类,悲观锁,乐观锁)

    JDBC 2021.5.21 依然跟着动力节点杜老师学!!! 1.什么是JDBC? Java DataBase Connectivity 在java语言中编写sql语句,对mysql数据库中的数据进行 ...

  5. 【工具类】分布式文件存储-FastDFS

    FastDFS简介 FastDFS体系结构 FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等,解决了大容量存储和负载均衡 ...

  6. Memcached的配置,SSH项目中的整合(com.whalin),Memcached工具类,Memcached的代码调用

     1 修改pom.xml,添加依赖文件: <dependency> <groupId>com.whalin</groupId> <artifactId&g ...

  7. Jedis工具类使用及设置

    Jedis是Redis数据库的java工具类,类似于JDBC中的Connection,也是对数据库进行CRUD的通道(这样说是不是有点不严谨~~~) 附上几个Redis的通用命令: key* 查看所有 ...

  8. Java Redis 连接池 Jedis 工具类,java基础面试笔试题

    我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家. 扫描二维码或搜索下图红色VX号,加VX好友,拉你进[程序员面试学习交流群]免费领取.也欢迎各位一起 ...

  9. JAVA 16位ID生成工具类含16位不重复的随机数数字+大小写

    package com.fty.util;import java.security.SecureRandom; import java.util.Random; import java.util.co ...

最新文章

  1. 绝对干货:19个有用的基于云的Web开发工具
  2. Science揭示:身体如何应对细菌的“群体感应”
  3. 如何更新android v7 support library,新手入门之Android Support Library | Soo Smart!
  4. matlabsimulink仿真天体运行轨迹
  5. 自由存储区和堆的区别_区块链发展阶段:IPFS和Filecoin赋能分布式存储
  6. 【Android 修炼手册】Gradle 篇 -- Android Gradle Plugin 主要流程分析
  7. python中如何对dict对象进行排序
  8. 《企业安全软件能否免费?》 ——百位中国CIO对免费企业级信息安全软件的态度调查报告...
  9. Batch批量替换hosts
  10. lnmp一键安装包 安装php-fpm,为LNMP一键安装包下PHP编译安装fileinfo扩展
  11. 第70页的gtk+编程例子——快捷键
  12. Java基础——对象和类1(面向对象基本概念)
  13. 移动机器人五种坐标系
  14. zynq嵌入式linux显示logo,如何定制嵌入式linux 启动logo(小企鹅)
  15. Spring学习笔记之MyBatis
  16. 财商帮解读:高质量的社群都离不开这10个关键要素!
  17. 国内外创业环境的比较
  18. JZOJ2018.07.12【2018提高组】模拟B组 魔道研究
  19. 我的Linux学习之路(纯小白)
  20. 影响关键词排名的因素有哪些?

热门文章

  1. 根据输入时间段备份压缩日志文件
  2. ASP.NET 系统对象 Request(一)
  3. Hibernate 关联 set 和 list 对比
  4. 多变异位自适应遗传算法(MMAdapGA)的算法原理、算法步骤和matlab实现
  5. rsync的配置应用
  6. redmine添加自定义问题状态
  7. 用自然语言指导强化学习agent打游戏,这是斯坦福的最新研究
  8. windows下把Apache加入系统服务
  9. 在Eclipse中生成API方法
  10. 再谈select, iocp, epoll,kqueue及各种I/O复用机制 - Shallway - 博客频道 - CSDN.NET