package com.util;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; public class JedisUtil { private static Jedis jedis;
private static final String PREFIX = "ll_idea";
private static final Logger logger = LoggerFactory.getLogger(JedisUtil.class); // Redis服务器IP
private static String ADDR_ARRAY = "127.0.0.1,192.168.241.132";// FileUtil.getPropertyValue("/properties/redis.properties",
// "server"); // Redis的端口号
private static int PORT = 6379;// FileUtil.getPropertyValueInt("/properties/redis.properties",
// "port"); // 访问密码
// private static String AUTH =
// FileUtil.getPropertyValue("/properties/redis.properties", "auth"); // 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 1000;// FileUtil.getPropertyValueInt("/properties/redis.properties",
// "max_active");; // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 8;// FileUtil.getPropertyValueInt("/properties/redis.properties",
// "max_idle");; // 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = -1;// FileUtil.getPropertyValueInt("/properties/redis.properties",
// "max_wait");; // 超时时间 毫秒
private static int TIMEOUT = 100000;// FileUtil.getPropertyValueInt("/properties/redis.properties",
// "timeout");; // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;// FileUtil.getPropertyValueBoolean("/properties/redis.properties",
// "test_on_borrow");; private static JedisPool jedisPool = null; /**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT);
} catch (Exception e) {
logger.error("First create JedisPool error : " + e);
try {
// 如果第一个IP异常,则访问第二个IP
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT);
} catch (Exception e2) {
logger.error("Second create JedisPool error : " + e2);
}
}
} /**
* 在多线程环境同步初始化
*/
private static synchronized void poolInit() {
if (jedisPool == null) {
initialPool();
}
} /**
* 同步获取Jedis实例
*
* @return Jedis
*/
public synchronized static Jedis getJedis() {
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
}
} catch (Exception e) {
logger.error("Get jedis error : " + e);
} finally {
returnResource(jedis);
}
return jedis;
} /**
* 释放jedis资源 jedispool returnresource 废弃 用 colose代码 3.0
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool != null) {
jedis.close();
}
} public static Jedis getJedis(String host_ip, int host_port) {
jedis = new Jedis(host_ip, host_port);
// jedis.auth("admin.123"); //开启密码验证(配置文件中为 requirepass root)的时候需要执行该方法
return jedis;
} public static Jedis getDefaultJedis() {
// return getJedis(HOST_IP, HOST_PORT);//简装版 return getJedis();
} /**
* 清空 redis 中的所有数据
*/
public static String flushRedis() {
logger.debug("flush redis data");
return getDefaultJedis().flushDB();
} /**
* 根据 pattern 获取 redis 中的键
*/
public static Set<String> getKeysByPattern(String pattern) {
return getDefaultJedis().keys(pattern);
} /**
* 获取 redis 中所有的键
*/
public static Set<String> getAllKeys() {
return getKeysByPattern("*");
} /**
* 判断key是否存在redis中
*/
public static boolean exists(String key) throws Exception { if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
} return getDefaultJedis().exists(PREFIX + key);
} /**
* 从Redis中移除一个key
*/
public static void del(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
getDefaultJedis().del(PREFIX + key);
} // ======================String 类型接口====================================== /**
* 存储字符串
*/
public static void setString(String key, String value, int expireTime) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
} String finalKey = PREFIX + key;
getDefaultJedis().set(finalKey, value);
if (expireTime > 0) {
/**
* 如果设置了 expireTime, 那么这个 finalKey会在expireTime秒后过期,那么该键会被自动删除
* 这一功能配合出色的性能让Redis可以作为缓存系统来使用,成为了缓存系统Memcached的有力竞争者
*/
getDefaultJedis().expire(finalKey, expireTime);
}
} /**
* 获取字符串
*/
public static String getString(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().get(PREFIX + key);
} public static long setnx(String key, String value) throws Exception { if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
} return getDefaultJedis().setnx(PREFIX + key, value);
} public static long expire(String key, int seconds) throws Exception { if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
} return getDefaultJedis().expire(PREFIX + key, seconds);
} // ========================List类型接口==========================
/**
* 存储 List
*/
public static void pushList(String key, String value, String flag) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(flag)) {
logger.error("key or flag is null");
throw new Exception("key or flag is null");
} /**
* key代表的是链表的名字 List是一个双端链表,lpush是往链表的头部插入一条数据,rpush是往尾部插入一条数据
*/
if (flag.equalsIgnoreCase("L")) {
getDefaultJedis().lpush(PREFIX + key, value);
} else if (flag.equalsIgnoreCase("R")) {
getDefaultJedis().rpush(PREFIX + key, value);
} else {
logger.error("unknown flag");
throw new Exception("unknown flag");
}
} /**
* 获取 List 中的单个元素
*/
public static String popList(String key, String flag) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(flag)) {
logger.error("key or flag is null");
throw new Exception("key or flag is null");
} if (flag.equalsIgnoreCase("L")) {
return getDefaultJedis().lpop(PREFIX + key);
} else if (flag.equalsIgnoreCase("R")) {
return getDefaultJedis().rpop(PREFIX + key);
} else {
logger.error("unknown flag");
throw new Exception("unknown flag");
}
} /**
* 获取 List 中指定区间上的元素
*/
public static List<String> getAppointedList(String key, long start, long end) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().lrange(PREFIX + key, start, end);
} /**
* 获取 List 上所有的元素
*/
public static List<String> getList(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().lrange(PREFIX + key, 0, -1);
} /**
* 获取 List 的长度
*/
public static long getListLength(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().llen(PREFIX + key);
} // =====================Set类型接口==================
/**
* 存储 Set : 单值存储
*/
public static void addValueToSet(String key, String value) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
getDefaultJedis().sadd(PREFIX + key, value);
} /**
* 存储 Set : 多值存储
*/
public static void addListToSet(String key, List<String> values) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
for (String value : values) {
getDefaultJedis().sadd(PREFIX + key, value);
}
} /**
* 删除 Set 中的某个元素
*/
public static void deleteElementInSet(String key, String value) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
getDefaultJedis().srem(PREFIX + key, value);
} /**
* 获取 Set 中所有的成员
*/
public static Set<String> getSet(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().smembers(PREFIX + key);
} /**
* 判断 value 是否属于 set
*/
public static boolean isExistInSet(String key, String value) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
logger.error("key or value is null");
throw new Exception("key or value is null");
}
return getDefaultJedis().sismember(PREFIX + key, value);
} /**
* 获取 Set 中元素个数
*/
public static long getLengthOfSet(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().scard(PREFIX + key);
} /**
* 取两个 Set 的交集
*/
public static Set<String> getSetInter(String key1, String key2) throws Exception {
if (StringUtils.isEmpty(key1) || StringUtils.isEmpty(key2)) {
logger.error("key1 or key2 is null");
throw new Exception("key1 or key2 is null");
}
return getDefaultJedis().sinter(PREFIX + key1, PREFIX + key2);
} /**
* 取两个 Set 的并集
*/
public static Set<String> getSetUnion(String key1, String key2) throws Exception {
if (StringUtils.isEmpty(key1) || StringUtils.isEmpty(key2)) {
logger.error("key1 or key2 is null");
throw new Exception("key1 or key2 is null");
}
return getDefaultJedis().sunion(PREFIX + key1, PREFIX + key2);
} /**
* 取两个 Set 的差集
*/
public static Set<String> getSetDiff(String key1, String key2) throws Exception {
if (StringUtils.isEmpty(key1) || StringUtils.isEmpty(key2)) {
logger.error("key1 or key2 is null");
throw new Exception("key1 or key2 is null");
}
return getDefaultJedis().sdiff(PREFIX + key1, PREFIX + key2);
} // ==================================SortedSet类型接口
/**
* 存储有序集合 SortedSet
*/
public static void setSortedSet(String key, double weight, String value) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
getDefaultJedis().zadd(PREFIX + key, weight, value);
} /**
* 获取有序集合指定区间上的元素
*/
public static Set<String> getAppointedSortedSet(String key, long start, long end) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().zrange(PREFIX + key, start, end);
} /**
* 获取有序集合上的所有元素
*/
public static Set<String> getSortedSet(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().zrange(PREFIX + key, 0, -1);
} /**
* 获取有序集合上某个权重区间上的元素
*/
public static long getLengthOfSortedSetByWeight(String key, double min, double max) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().zcount(PREFIX + key, min, max);
} /**
* 删除有序集合上的元素
*/
public static void deleteElementInSortedSet(String key, String value) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
getDefaultJedis().zrem(PREFIX + key, value);
} /**
* 获取有序集合中元素的个数
*/
public static long getLengthOfSortedSet(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().zcard(PREFIX + key);
} /**
* 查看有序集合中元素的权重
*/
public static double getWeight(String key, String value) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().zscore(PREFIX + key, value);
} // ========================hash 类型接口==============
/**
* 存储 HashMap
*/
public static void setHashMapByFieldAndValue(String key, String field, String value) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
logger.error("key or field is null");
throw new Exception("key or field is null");
}
getDefaultJedis().hset(PREFIX + key, field, value);
} /**
* 存储 HashMap
*/
public static void setHashMapByMap(String key, Map<String, String> map) throws Exception {
if (StringUtils.isEmpty(key) || map == null) {
logger.error("key or map is null");
throw new Exception("key or map is null");
}
getDefaultJedis().hmset(PREFIX + key, map);
} /**
* 删除 HashMap 中的键值对
*/
public static void deleteHashMapValueByField(String key, String field) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
logger.error("key or field is null");
throw new Exception("key or field is null");
}
getDefaultJedis().hdel(PREFIX + key, field);
} /**
* 获取 HashMap 中键对应的值
*/
public static String getHashMapValueByField(String key, String field) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
logger.error("key or field is null");
throw new Exception("key or field is null");
}
return getDefaultJedis().hget(PREFIX + key, field);
} /**
* 获取 HashMap 中所有的 key
*/
public static Set<String> getHashMapKeys(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().hkeys(PREFIX + key);
} /**
* 获取 HashMap 中所有的值
*/
public static List<String> getHashMapValues(String key) throws Exception {
if (StringUtils.isEmpty(key)) {
logger.error("key is null");
throw new Exception("key is null");
}
return getDefaultJedis().hvals(PREFIX + key);
} /**
* 判断 HashMap 中是否存在某一个键
*/
public static boolean isFieldExistsInHashMap(String key, String field) throws Exception {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
logger.error("key or field is null");
throw new Exception("key or field is null");
}
return getDefaultJedis().hexists(PREFIX + key, field);
} public static long lpush(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
logger.error("key or field is null");
} return getDefaultJedis().lpush(key, value);
} public static long rpush(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
logger.error("key or field is null");
} return getDefaultJedis().rpush(key, value);
} public static String lpop(String key) {
if (StringUtils.isEmpty(key)) {
logger.error("key or field is null");
} return getDefaultJedis().lpop(key);
} public static String rpop(String key) {
if (StringUtils.isEmpty(key)) {
logger.error("key or field is null");
} return getDefaultJedis().rpop(key);
} static { getDefaultJedis().lpush("key1", "123");
getDefaultJedis().lpush("key1", "456");
getDefaultJedis().lpush("key1", "789");
getDefaultJedis().lpush("key1", "012"); } public static void main(String[] args) throws Exception {
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
//在添加集群节点的时候只需要添加一个,其余同一集群的节点会被自动加入
jedisClusterNodes.add(new HostAndPort("192.168.241.132", 7000));
JedisCluster jc = new JedisCluster(jedisClusterNodes);
jc.set("rediskey", "redisvalue_123");
String value = jc.get("rediskey");
System.out.println(value); }
}

  

redis3.2 Jedis java操作的更多相关文章

  1. Redis学习(5)-Jedis(Java操作redis数据库技术)

    Java连接redis 一,导入jar包 Redis有什么命令,Jedis就有什么方法 设置防火墙 在Linux上面运行如下代码: 单实例:Jedis实例: package com.jedis.dem ...

  2. java操作redis之jedis篇

    首先来简单介绍一下jedis,其实一句话就可以概括的,就是java操作redis的一种api.我们知道redis提供了基本上所有常用编程语言的clients,大家可以到http://redis.io/ ...

  3. Redis入门(四)-Java操作Redis

    <Redis入门>系列文章的第四篇,这一节看一下如何用Java版本的redis客户端工具--Jedis来操作redis. Jedis封装了丰富的api来对redis的五种数据类型 stri ...

  4. Redis java操作客户端

    Jedis常用操作 1.测试连通性 Jedis jedis = new Jedis("192.168.1.201",6380,10000); System.out.println( ...

  5. java 操作redis

    使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...

  6. windows下Redis安装及利用java操作Redis

    一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...

  7. java操作redis集群配置[可配置密码]和工具类(比较好用)

    转: java操作redis集群配置[可配置密码]和工具类 java操作redis集群配置[可配置密码]和工具类     <dependency>   <groupId>red ...

  8. java操作redis集群配置[可配置密码]和工具类

    java操作redis集群配置[可配置密码]和工具类     <dependency>   <groupId>redis.clients</groupId>   & ...

  9. Linux+Redis实战教程_day02_3、redis数据类型_4、String命令_5、hash命令_6、java操作redis数据库技术

    3. redis数据类型[重点] redis 使用的是键值对保存数据.(map) key:全部都是字符串 value:有五种数据类型 Key名:自定义,key名不要过长,否则影响使用效率 Key名不要 ...

随机推荐

  1. centos6.3安装python2.7, pip2.7, mysql

    参考: https://github.com/h2oai/h2o-2/wiki/Installing-python-2.7-on-centos-6.3.-Follow-this-sequence-ex ...

  2. ubuntu下安装mcrypt

    sudo apt-get install libmcrypt4 php5-mcrypt 一句命令搞定

  3. PHP 链接数据库1(连接数据库&简单的登录注册)

    对 解析变量的理解 数据库的名称和表的名称不能重复 从结果中取出的数据   都是以数组的形式取出的 1.PHP查询数据库中的某条信息 //PHP链接数据库 /*1.造链接对象 IP地址 用户名 密码 ...

  4. 登录oracle数据库提示账户锁定解决方法

    问题再现: 由于更改了oracle账户的密码,退出重新连接oracle出现了账户被锁定的情况. 请了百度君出来卸载一下,问题已解决. 在cmd下:sqlplus /nolog 然后:以dba身份登录: ...

  5. [MongoDB]MongoDB与JAVA结合使用CRUD

    汇总: 1. [MongoDB]安装MongoDB2. [MongoDB]Mongo基本使用:3. [MongoDB]MongoDB的优缺点及与关系型数据库的比较4. [MongoDB]MongoDB ...

  6. UWP webview 键盘bug,回退页面,键盘会弹一下。

    最新项目发现一个关于Webview的键盘bug. 具体问题:当点击Webview 网页里面input之类的东东,输入键盘会弹出来,这个时候,按回退键,键盘会收起来,再按回退键,界面会退到前一个页面,但 ...

  7. Python学习笔记(四)——编码和字符串

    一.编码 1.编码类别: (1)ASCII码:127个字母被编码到计算机里,也就是大小写英文字母.数字和一些符号 (2)GB2312码:中国制定的用于加入中文汉字的编码 (3)Unicode:防止由于 ...

  8. 在visual studio2015中使用easyX画图

    配置:解压EasyX压缩包: 将文件内的include,lib,lib/amd64下的文件拷贝到visualstudio中VC文件夹内对应的地方: 然后再执行上图中的Setup.hta进行安装: 在v ...

  9. DirectShow

    1 最简单的DirectShow应用程序 — 播放视频 1.简介DirectShow是DirectX中的一套处理媒体播放.音视频采集的开发包,在DirectX SDK Summer 2004(Dire ...

  10. Ext之ExtGrid增删改查询回顾总结

    学习Ext已经有些许时间了,发现实际运用过程中ExtGrid系列还是最为常用的,本来想自己写些话语来总结的,无意间看到有位仁兄早就总结了,故冒犯贴在此处,以便以后翻阅,还望见谅 Ext - Grid  ...