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 ...
随机推荐
- 淘宝网站上的 HTTP 缓存问题两则
在阅读本文前推荐你先阅读我的前两篇文章< 扼杀 304,Cache-Control: immutable>和<关于缓存和 Chrome 的“新版刷新”>:下面要说的两个问题是在 ...
- [译]Ocelot - Configuration
原文 这里有一个配置的样例.配置主要有两个部分.一个是ReRoutes数组,另一个是GlobalConfiguration.ReRoute告诉Ocelot怎么处理上游的请求.Global config ...
- ES6 的 一些语法
1,let 声明变量 let 声明的变量只能在let 的块级作用域中生效,也是为了弥补var声明变量的全局污染问题. var 声明变量有变量提升的作用,也就是在声明变量之前可以使用变量 console ...
- Linux Shell远程执行命令
1.问题描述 经常需要远程到其他节点上执行一些shell命令,如果分别ssh到每台主机上再去执行很麻烦,下边介绍shell命令远程执行的方法. 前提: 远程电脑之间已经配置ssh免密码登陆 2.脚本方 ...
- Django之验证码
一.自己生成验证码 二.极验科技互动验证码 使用前步骤:下载官网文件——pip install geetest——引入其封装的js模块 代码分为三段:生成验证码——显示验证码——验证验证码. from ...
- Visual Studio Code(VSCODE)语言设置
Visual Studio Code(VSCODE)语言设置 语言设置 1.快捷键 Windows.Linux 快捷键是:ctrl+shift+p macOS 快捷键是:command + shift ...
- k64 datasheet学习笔记25--Multipurpose Clock Generator (MCG)
0.前言 MCG模块为MCU提供了几种可选时钟源.模块包含一个FLL和一个PLL.FLL使用内部或外部参考时钟是可控的,PLL受外部参考时钟控制 模块可以选择FLL或PLL输出时钟,或内/外部参考时钟 ...
- centos 6 部署Nodejs
线上环境需要一套nodjs,没话说,那就部署唠. 一.下载编译包.解压.软链 nodjs历史版本连接:https://nodejs.org/zh-cn/download/releases/ cd /u ...
- 【原创】Linux基础之linux常用命令之文本替换
linux常用命令之文本替换 1 vi vi test_file :%s/h/h1/g 注释:全文替换,将h替换为h1 :1,4s/h/h1/g 注释:将第1行到第4行的h替换为h1 :%s/\n/, ...
- php-beast 代码加密
https://github.com/liexusong/php-beast 修改php.ini配置 extension_dir = "/usr/lib/php/20151012/" ...