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

一、连接池部分

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();
}
}
}

Jedis工具类(含分布式锁的调用和释放)的更多相关文章

  1. Jedis工具类代码

    安装Redis可以参考 https://www.cnblogs.com/dddyyy/p/9763098.html Redis的学习可以参考https://www.cnblogs.com/dddyyy ...

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

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

  3. Jedis工具类

    1.RedisCache.java package cn.itcast.mybatis.dao; import java.util.Date;import java.util.HashMap;impo ...

  4. Java Redis 连接池 Jedis 工具类

    import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import re ...

  5. Jedis 工具类

    package com.pig4cloud.pigx.admin.utils; import redis.clients.jedis.*; import java.util.ArrayList; im ...

  6. 2020最新的Spring Boot 分布式锁的具体实现(内附代码)

    前言 面试总是会被问到有没有用过分布式锁.redis 锁,大部分读者平时很少接触到,所以只能很无奈的回答 "没有".本文通过 Spring Boot 整合 redisson 来实现 ...

  7. Jedis 操作 Redis 工具类

    配置类 pom.xml pom.xml 里配置依赖 <dependency> <groupId>redis.clients</groupId> <artifa ...

  8. Spring普通类/工具类获取并调用Spring service对象的方法

    参考<Spring普通类获取并调用Spring service方法>,网址:https://blog.csdn.net/jiayi_0803/article/details/6892455 ...

  9. Redis 4.0.2分布式锁的Java实现

    简介 Redis分布式锁算法有两种,一种是单个Redis实例下的,一种是多个Redis实例的Redlock算法. 官方推荐Redlock算法,但是这个算法需要比较多的Redis实例而且是完全互相独立, ...

随机推荐

  1. JavaScript Array 对象扩展方法

    /** 删除数组中指定索引的数据 **/ Array.prototype.deleteAt = function (index) { if (index < 0) { return this; ...

  2. WinForm 之 VS2010发布、打包安装程序

    第一步.在vs2010 打开要打包的应用程序解决方案,右键“ 解决方案 ” → “ 添加 ” → “ 新建项目 ” → “ 其他项目类型 ” → “ 安装和部署 ” → “ Visual Studio ...

  3. robot framework-databaselibaray库使用(python)

    公司做项目用到了databaselibaray,刚开始使用时碰到了很多问题,网上也查阅了很多资料终于是可以用了,现在整理记录下来,有需要的同学可随意使用: 另,本文主要是databaselibaray ...

  4. 如何设置Vmware下Linux系统全屏显示

    环境:Vmware10+RedHat5 在Vmware10中安装好RedHat5后,即使点击了全屏按钮(或使用快捷键Ctrl+Alt+Enter),全屏的效果依然不尽人意,跟下图中差不多,RedHat ...

  5. Python有关模块学习记录

    1 pandas numpy模块 首先安装搭建好jupyter notebook,运行成功后的截图如下: 安装使用步骤(PS:确定Python安装路径和安装路径里面Scripts文件夹路径已经配置到环 ...

  6. 算法笔记_214:第六届蓝桥杯软件类校赛真题(Java语言A组)

    目录 1 题目一 2 题目二 3 题目三 4 题目四 5 题目五 6 题目六 7 题目七 前言:以下代码仅供参考,若有错误欢迎指正哦~ 1 题目一 一个串的子串是指该串的一个连续的局部.如果不要求连续 ...

  7. jquery vue 框架区别

    1.数据和视图分离,解耦 2.以数据驱动视图,只关心数据变化,DOM操作被封装

  8. 【shell】创建长目录,目录存在则忽略,缺失则创建

    有时候,我们需要创建一个空目录树,如果给定路径包含目录,那么还必须检查这些目录是否存在: mkdir –p /qinys/oliver/tmp/ 执行上述命令即可创建长目录,并且有则忽略,无则创建原则 ...

  9. java第六节 字符串/集合

    /* *String类和StringBuffer类 * 位于java.lang包中 * String类对象中的内容一旦被初始化就不能再改变 * StringBuffer类中用于封装内容可以改变的字符串 ...

  10. 利用XAMPP搭建PHP开发环境,解决443端口被占用

    为了方便,作为学习使用的PHP环境,我们可以直接使用Apache+mysql+php集成开发环境.这样的集成软件有appserv和xampp,这里我们以xampp为例. 首先下载xampp软件,下载地 ...