Jedis自己整理比较全的API
package com.tebon.ams.utils;
import com.alibaba.fastjson.JSON;
import com.tebon.ams.util.ObjectUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.*;
import java.util.*;
public class JedisUtil {
private final static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
private static JedisPool pool;
private JedisUtil() {
}
static {
InputStream is = null;
try {
Properties constant = new Properties();
is = JedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
if (is != null) {
constant.load(is);
}
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(Integer.valueOf(constant.getProperty("redis.maxIdle", "100")));
poolConfig.setMinIdle(Integer.valueOf(constant.getProperty("redis.minIdle", "20")));//设置最小空闲数
poolConfig.setMaxTotal(Integer.valueOf(constant.getProperty("redis.maxTotal", "300")));
poolConfig.setTimeBetweenEvictionRunsMillis(-1);
poolConfig.setTestOnBorrow(true);
String host = constant.getProperty("redis.host");
int port = Integer.valueOf(constant.getProperty("redis.port"));
int timeout = Integer.valueOf(constant.getProperty("redis.timeout"));
String pwd = constant.getProperty("redis.pwd");
int db = Integer.valueOf(constant.getProperty("redis.db", "0"));
if (pwd == null || pwd.isEmpty()) {
pool = new JedisPool(poolConfig, host, port, timeout);
} else {
pool = new JedisPool(poolConfig, host, port, timeout, pwd, db);
}
} catch (IOException e) {
logger.error("读取redis配置文件出错", e);
} catch (Exception e) {
logger.error("JedisUtil init error", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
logger.error("关闭redis配置文件流出错", e);
}
}
}
}
public static JedisPool getJedisPool() {
return pool;
}
//-----------String Start ------------------
/**
* String类型的增加操作
*
* @param key
* @param value
*/
public static void set(String key, String value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set(key, value);
} catch (Exception e) {
logger.error("set error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
/**
* 字符串
*
* @param key
* @param value
* @param expireTimeInSec
*/
public static void set(String key, String value, int expireTimeInSec) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.setex(key, expireTimeInSec, value);
} catch (Exception e) {
logger.error("set ex error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
public static String get(String key) {
Jedis jedis = null;
String value = null;
try {
jedis = pool.getResource();
value = jedis.get(key);
} catch (Exception e) {
logger.error("getkey error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return value;
}
/**
* 删除某个key
*
* @param name
*/
public static void del(String name) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.del(name);
} catch (Exception e) {
logger.error("pop ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
/**
* 存入对象之前进行序列化
*
* @param key 键
* @param value 值
* @return
*/
public static String setObj(String key, Object value) {
String result = null;
Jedis jedis = null;
try {
jedis = pool.getResource();
result = jedis.set(key.getBytes(), ObjectUtil.serialize(value));
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* 设置缓存
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String setObj(String key, Object value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = pool.getResource();
result = jedis.set(key.getBytes(), ObjectUtil.serialize(value));
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* getObj
*
* @param key 键
* @return
*/
public static Object getObj(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
byte[] bytes = jedis.get(key.getBytes());
if (null != bytes && bytes.length > 0) {
return ObjectUtil.unSerialize(bytes);
}
return null;
} catch (Exception e) {
logger.error("getobj error.", e);
pool.returnBrokenResource(jedis);
return null;
} finally {
pool.returnResource(jedis);
}
}
/**
* 删除key
*/
public static Long delObj(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.del(key.getBytes());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 判断某个key值是否存在
*
* @param key
* @return
*/
public Boolean exists(String key) {
Jedis jedis = null;
Boolean flag = false;
try {
jedis = pool.getResource();
flag = jedis.exists(key);
} catch (Exception e) {
logger.error("set error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return flag;
}
//-----------String End ------------------
//----------Set Start ------------------
/**
* 向Set缓存中添加值
*
* @param key 键
* @param value 值
* @return
*/
public static long setSetAdd(String key, String... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = pool.getResource();
result = jedis.sadd(key, value);
logger.debug("setSetAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetAdd {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* 设置Set缓存
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setSet(String key, Set<String> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.sadd(key, value.toArray(new String[value.size()]));
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSet {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
public static Set<String> getSet(String key) {
Set<String> value = null;
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis.exists(key)) {
value = jedis.smembers(key);
logger.debug("getSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getSet {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return value;
}
/**
* 设置Set缓存
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis.exists(key.getBytes())) {
jedis.del(key);
}
Set<byte[]> set = new HashSet();
for (Object o : value) {
set.add(ObjectUtil.serialize(o));
}
result = jedis.sadd(key.getBytes(), set.toArray(new byte[set.size()][]));
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setObjectSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectSet {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
public static Set<Object> getObjectSet(String key) {
Set<Object> value = null;
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis.exists(key.getBytes())) {
value = new HashSet();
Set<byte[]> set = jedis.smembers(key.getBytes());
for (byte[] bs : set) {
value.add(ObjectUtil.unSerialize(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectSet {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return value;
}
/**
* 向Set缓存中添加值
*
* @param key 键
* @param value 值
* @return
*/
public static long setSetObjectAdd(String key, Object... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = pool.getResource();
Set<byte[]> set = new HashSet();
for (Object o : value) {
//防止传数组,有null报错
if (o == null) {
continue;
}
set.add(ObjectUtil.serialize(o));
}
result = jedis.sadd(key.getBytes(), set.toArray(new byte[set.size()][]));
logger.debug("setSetObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetObjectAdd {} = {}", key, value, e);
} finally {
pool.returnResource(jedis);
}
return result;
}
/**
* 获取给定key中元素个数
*
* @param String key
* @return 元素个数
*/
public static long scard(String key) {
Jedis jedis = null;
long len = 0;
try {
jedis = pool.getResource();
len = jedis.scard(key);
} catch (Exception e) {
logger.warn("scard {} = {}", key, e);
} finally {
pool.returnResource(jedis);
}
return len;
}
/**
* 判断KEY关联的SET集合是否存在对应的成员
*
* @param key Redis里面实际的KEY
* @param value 要查找的成员
*/
public static boolean sismember(String key, String value) {
Jedis jedis = null;
boolean flag = false;
try {
jedis = pool.getResource();
flag = jedis.sismember(key, value);
} catch (Exception e) {
logger.error("set cache error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return flag;
}
/**
* 从集合中删除指定成员
*
* @param key
* @param value
* @return
*/
public static long srem(String key, String value) {
Jedis jedis = null;
long flag = 0;
try {
jedis = pool.getResource();
flag = jedis.srem(key, value);
} catch (Exception e) {
logger.error("set cache error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return flag;
}
//-----------Set End --------------------
//-----------List Start-------------------
@SuppressWarnings("unchecked")
public static <T extends Serializable> void push(String name, T... ts) {
Jedis jedis = null;
try {
jedis = pool.getResource();
for (T t : ts)
jedis.lpush(name, JSON.toJSONString(t));
} catch (Exception e) {
logger.error("push error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
public static long lpush(String name, String json) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.lpush(name, json);
} catch (Exception e) {
logger.error("push error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return -1;
}
public static <T extends Serializable> void push(String name, Collection<T> collection) {
Jedis jedis = null;
try {
jedis = pool.getResource();
for (T t : collection)
jedis.lpush(name, JSON.toJSONString(t));
} catch (Exception e) {
logger.error("push collection error.", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
/**
* 从列表最后一位开始移除并获取列表该元素
*
* @param name
* @param size
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends Serializable> List<T> pop(String name, int size) {
if (size < 1) {
return null;
}
Jedis jedis = null;
List<T> list = new ArrayList<T>();
try {
jedis = pool.getResource();
if (jedis.exists(name)) {
String value = jedis.rpop(name);
for (int i = 1; i <= size && value != null; i++) {
list.add((T) JedisUtil.str2Object(value));
value = jedis.rpop(name);
}
}
} catch (Exception e) {
logger.error("pop ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return list;
}
@SuppressWarnings("unchecked")
public static <T extends Serializable> List<T> lrange(String name, int start, int end) {
Jedis jedis = null;
List<T> list = new ArrayList<T>();
try {
jedis = pool.getResource();
if (jedis.exists(name)) {
List<String> strList = jedis.lrange(name, start, end);
int size = strList == null ? 0 : strList.size();
for (int i = 0; i < size; i++) {
list.add((T) JedisUtil.str2Object(strList.get(i)));
}
}
} catch (Exception e) {
logger.error("lrange ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return list;
}
public static <T extends Serializable> List<T> lrange(String name, int start, int end, Class<T> classes) {
Jedis jedis = null;
List<T> list = new ArrayList<T>();
try {
jedis = pool.getResource();
if (jedis.exists(name)) {
List<String> strList = jedis.lrange(name, start, end);
int size = strList == null ? 0 : strList.size();
ObjectMapper objectMapper = new ObjectMapper();
for (int i = 0; i < size; i++) {
list.add(objectMapper.readValue(strList.get(i), classes));
}
}
} catch (Exception e) {
logger.error("lrange ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return list;
}
public static long length(String name) {
Jedis jedis = null;
long length = 0;
try {
jedis = pool.getResource();
length = jedis.llen(name);
} catch (Exception e) {
logger.error("pop ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return length;
}
/**
* 移除列表中的元素
*
* @param name
* @param count count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT 。
* count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值。
* count = 0 : 移除表中所有与 VALUE 相等的值。
*/
public static void lrem(String name, int count, String value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.lrem(name, count, JSON.toJSONString(value));
} catch (Exception e) {
logger.error("pop ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
}
//---------------List End----------------
//--------------ZSet Start---------------
/**
* 向有序不重复集合添加数据
*
* @param key
* @param score
* @param member
* @return
*/
public static long zadd(String key, double score, String member) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.zadd(key, score, member);
} catch (Exception e) {
logger.error("zadd ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return 0;
}
public static long zadd(String key, Map<String, Double> scoreMembers) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.zadd(key, scoreMembers);
} catch (Exception e) {
logger.error("zadd ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return 0;
}
/**
* 移除有序集合中给定的字典区间的所有成员
*
* @param key
* @param start
* @param end
* @return
*/
public static long zremrangeByRank(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.zremrangeByRank(key, start, end);
} catch (Exception e) {
logger.error("zremrangeByRank ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return 0;
}
/**
* 通过索引区间返回有序集合成指定区间内的成员
*
* @param key
* @param start
* @param end
* @return
*/
public static Set<String> zrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.zrange(key, start, end);
} catch (Exception e) {
logger.error("zrang ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return null;
}
/**
* 获取有序集合的成员数
*
* @param key
* @return
*/
public static long zcard(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.zcard(key);
} catch (Exception e) {
logger.error("zcard ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return 0;
}
//--------------End ZSet-----------------------
//--------------Start Hash---------------------
/**
* 将哈希表 key 中的字段 field 的值设为 value
*
* @param key
* @param field
* @param value
* @return
*/
public static long hset(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hset(key, field, value);
} catch (Exception e) {
logger.error("hset ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return 0;
}
/**
* 获取所有给定字段的值
*
* @param key
* @param field
* @return
*/
public static String hget(String key, String field) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hget(key, field);
} catch (Exception e) {
logger.error("hget ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return null;
}
/**
* 删除一个或多个哈希表字段
*
* @param key
* @param field
* @return
*/
public static Long hdel(String key, String field) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hdel(key, field);
} catch (Exception e) {
logger.error("hget ", e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return null;
}
/**
* 获取byte[]类型Key
*
* @param key
* @return /*
*/
/* public static byte[] getBytesKey(Object object) {
if (object instanceof String) {
return StringUtils.getBytes((String) object);
} else {
return ObjectUtil.serialize(object);
}
}*/
public static Object str2Object(String str) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(getByte(str)));
return ois.readObject();
}
public static byte[] getByte(String str) {
byte[] bt = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (str != null) {
ObjectOutputStream objos = new ObjectOutputStream(baos);
objos.writeObject(str);
bt = baos.toByteArray();
}
} catch (Exception e) {
bt = (byte[]) null;
e.printStackTrace();
}
return bt;
}
}
Jedis自己整理比较全的API的更多相关文章
- 使用html5中video自定义播放器必备知识点总结以及JS全屏API介绍
一.video的js知识点: controls(控制器).autoplay(自动播放).loop(循环)==video默认的: 自定义播放器中一些JS中提供的方法和属性的记录: 1.play()控制视 ...
- HTML5全屏API
现在大多数浏览器都有全屏功能,允许用户来设置或操作.但HTML5的全屏API与之不同,HTML5的全屏API允许web开发工程师在程序中调用. 这样,web开发工程师就可以再网站中设计一个按钮,当该按 ...
- JavaScript网页全屏API
在大多数的浏览器中都有实现网页全屏显示的功能,并且大部分浏览器实现全屏显示和退出全屏显示的快捷键通常是F11和Esc两个按键.如今,W3C已经制定了关于网页全屏显示的API,利用这个API 可以实现网 ...
- HTML5 全屏 API
翻译人员: 铁锚 原文日期: 2013年12月23日 翻译日期: 2013年12月29日 原文链接: Fullscreen API 在越来越真实的web应用程序中,JavaScript也变得越来越给力 ...
- 全屏API
by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=2679 二.相关文章以 ...
- 全屏API接口
HTML5的诞生给我们提供了很多精彩的JavaScript和HTML新功能和新特征.有些新特征我们已知多年并大量的使用,而另外一些主要是用在前沿的手机移动技术上,或者桌面应用中起辅助作用.不管这些HT ...
- 大牛整理最全Python零基础入门学习资料
大牛整理最全Python零基础入门学习资料 发布时间:『 2017-11-12 11:56 』 帖子类别:『人工智能』 阅读次数:3504 (本文『大牛整理最全Python零基础入门学习资料 ...
- 最全的 API 接口集合
对于程序员来说,为自己的程序选择一些合适的API并不是那么简单,有时候还会把你搞得够呛,今天猿妹要和大家分享一个开源项目,这个项目汇集了各种开发的api,涵盖了音乐.新闻.书籍.日历等,无论你是从事W ...
- 一个可能是世界上最全的 API 接口集合库开源项目
对于程序员来说,为自己的程序选择一些合适的API并不是那么简单,有时候还会把你搞得够呛,今天猿妹要和大家分享一个开源项目,这个项目汇集了各种开发的api,涵盖了音乐.新闻.书籍.日历等,无论你是从事W ...
随机推荐
- 已知 $AB$, 求 $BA$
设 $A,B$ 分别是 $3\times 2$ 和 $2\times 3$ 实矩阵. 若 $\dps{AB=\sex{\ba{ccc} 8&0&-4\\ -\frac{3}{2}& ...
- oracle数据库驱动(ojdbc)
第1部分 Q:为什么oralce的jdbc驱动,在maven上搜索到把pom配置复制到pom.xml里进行引用的时候会报错? ANS:虽然能在maven仓库里搜索到,但貌似不能用,原因是oracle是 ...
- jQuery1.9及以上版本检测IE版本号
jQuery 从 1.9 版开始,移除了 $.browser 和 $.browser.version , 取而代之的是 $.support . 在更新的 2.0 版本中,将不再支持 IE 6/7/8. ...
- 连接远程MySQL数据库项目启动时,不报错但是卡住不继续启动的,
连接远程MySQL数据库项目启动时,不报错但是卡住不继续启动的, 2018-03-12 17:08:52.532DEBUG[localhost-startStop-1]o.s.beans.factor ...
- 【转】【Linux】Swap与Memory
背景介绍 Memory指机器物理内存,读写速度低于CPU一个量级,但是高于磁盘不止一个量级.所以,程序和数据如果在内存的话,会有非常快的读写速度.但是,内存的造价是要高于磁盘的,且内存的断电丢失数据也 ...
- Linux命令行下编辑常用的快捷键
Linux命令行编辑快捷键: Ctrl+r 然后输入若干字符,开始向上搜索包含该字符的命令,继续按Ctrl+r,搜索上一条匹配的命令,按Ctrl+c或上下键退出. Ctrl+l 清屏 !num 执行命 ...
- css好看的银行卡号样式
.cardNo { font-size: 17px; font-family: menlo,tahoma; text-shadow: 1px 1px 2px #666; line-height: 18 ...
- 【python3 自动化之mysql操作】python3下的mysql入门基础
1.所需资源:pycharm,python3.6,module:pymysql 2.pycharm配置mysql: 新添加一个mysql数据库 ip:192.168.112.54 端口:3306 ...
- pandas 中处理数据的函数和方法
- 【深度学习】吴恩达网易公开课练习(class2 week1 task2 task3)
正则化 定义:正则化就是在计算损失函数时,在损失函数后添加权重相关的正则项. 作用:减少过拟合现象 正则化有多种,有L1范式,L2范式等.一种常用的正则化公式 \[J_{regularized} = ...