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 ...
随机推荐
- Mathematica 求出解后代入变量
Solve[2 x - 3 == 0, x] x = x //. %[[1]]
- MySQL的一些基本命令笔记(4)
delete 语句嵌套子查询: delete from 表名1 where 列名 操作符 (select 列名 from 表名2 where 条件); 示例: delete from customer ...
- 【hdu 5217】Brackets
Description Miceren likes playing with brackets. There are N brackets on his desk forming a sequence ...
- Pytorch报错记录
1.BrokenPipeError 执行以下命令时: a,b = iter(train_loader).next() 报错:BrokenPipeError: [Errno 32] Broken pip ...
- vue 报错总结
关闭vue-cli 默认eslint规则: 找到 build -> webpack.base.config.js ,删除箭头指向代码 1.Newline required at end of f ...
- 【原创】大叔经验分享(16)Context namespace element 'component-scan' and its parser class [org.springframework.context.annotation.ComponentScanBeanDefinitionParser] are only available on JDK 1.5 and higher
今天尝试运行一个古老的工程,配置好之后编译通过,结果运行时报错: org.springframework.beans.factory.BeanDefinitionStoreException: Une ...
- java----dom4j 解析XML
dom4j: 由于内部采用迭代器,适合读取大文档: 数据块 1.下载 https://dom4j.github.io/ 2.添加包到工程目录下 使用 import org.dom4j.Document ...
- Python3 元组(tuple)
一.定义:不可变序列的数据元素集合,元组的元素是不可以修改的 元组使用小括号,例如:tuple = (1,) 注意:即使元组里面只有一个元素,该元素后面也要加 ",":在函数传递参 ...
- SQL 安装MySQL
假设学员的电脑是Windows系统,如Windows7,需要准备以下软件 Microsoft .NET Framework 4.5 Visual C++ Redistributable for Vis ...
- CSS之垂直对齐
vertical-align: baseline 默认.元素放置在父元素的基线上. sub 垂直对齐文本的下标. super 垂直对齐文本的上标 top 把元素的顶端与行中最高元素的顶端对齐 text ...