redis3.2 Jedis java操作
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操作的更多相关文章
- Redis学习(5)-Jedis(Java操作redis数据库技术)
Java连接redis 一,导入jar包 Redis有什么命令,Jedis就有什么方法 设置防火墙 在Linux上面运行如下代码: 单实例:Jedis实例: package com.jedis.dem ...
- java操作redis之jedis篇
首先来简单介绍一下jedis,其实一句话就可以概括的,就是java操作redis的一种api.我们知道redis提供了基本上所有常用编程语言的clients,大家可以到http://redis.io/ ...
- Redis入门(四)-Java操作Redis
<Redis入门>系列文章的第四篇,这一节看一下如何用Java版本的redis客户端工具--Jedis来操作redis. Jedis封装了丰富的api来对redis的五种数据类型 stri ...
- Redis java操作客户端
Jedis常用操作 1.测试连通性 Jedis jedis = new Jedis("192.168.1.201",6380,10000); System.out.println( ...
- java 操作redis
使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...
- windows下Redis安装及利用java操作Redis
一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...
- java操作redis集群配置[可配置密码]和工具类(比较好用)
转: java操作redis集群配置[可配置密码]和工具类 java操作redis集群配置[可配置密码]和工具类 <dependency> <groupId>red ...
- java操作redis集群配置[可配置密码]和工具类
java操作redis集群配置[可配置密码]和工具类 <dependency> <groupId>redis.clients</groupId> & ...
- Linux+Redis实战教程_day02_3、redis数据类型_4、String命令_5、hash命令_6、java操作redis数据库技术
3. redis数据类型[重点] redis 使用的是键值对保存数据.(map) key:全部都是字符串 value:有五种数据类型 Key名:自定义,key名不要过长,否则影响使用效率 Key名不要 ...
随机推荐
- 多线程下NSOperation、NSBlockOperation、NSInvocationOperation、NSOperationQueue的使用
本篇文章主要介绍下多线程下NSOperation.NSBlockOperation.NSInvocationOperation.NSOperationQueue的使用,列举几个简单的例子. 默认情况下 ...
- 编辑 Ext 表格(二)——— 编辑表格元素
一.编辑单元格 Ext 中通过配置表格的属性 plugins 来设置表格是否可编辑, 表格的配置具体如下: var gridTable = Ext.create('Ext.grid.Panel', { ...
- ASP.NET知识总结(2.对比Get和Post提交方式)
2.对比Get和Post提交方式 get:<1>在地址栏中通过?key1=value1&key2=value2...的方式传值 <2>传递的数据用户可以直接在url中看 ...
- 【Java EE 学习 49 下】【Spring学习第一天】【MVC】【注解回顾】
一.MVC 1.使用Spring有一个非常大的好处,那就是能够实现完全面向接口编程,传统的使用Dao.Service并不能实现完全的面向接口编程. 2.示例:https://github.com/kd ...
- Oracle 11g RAC停止和启动步骤
关闭前备份控制文件/参数文件: sqlplus / as sysdba alter database backup controlfile to '/home/oracle/control.ctl ...
- VS2015 自动添加头部注释
让VS自动生成类的头部注释,只需修改两个文集即可,一下两个路径下个有一个 Class.cs文件 D:\Program Files (x86)\Microsoft Visual Studio 14.0\ ...
- curl运行json串,代理转发格式
curl -b 'uin=o0450654733; skey=@tq9xjRvYy' -H "Content-Type: application/json" -X POST -d ...
- 【面试】http协议知识
一.什么是HTTP协议 HTTP协议是一种应用层协议,HTTP是HyperText Transfer Protocol(超文本传输协议)的英文缩写.HTTP可以通过传输层的TCP协议在客 ...
- Windows远程连接CentOS桌面
VNC (Virtual Network Console)是虚拟网络控制台的缩写.它 是一款优秀的远程控制工具软件.VNC的基本运行原理和一些Windows下的远程控制软件很相像 VNC基本上是由两部 ...
- 集中式vs分布式区别
记录一下我了解到的版本控制系统,集中式与分布式,它们之间的区别做下个人总结. 什么是集中式? 集中式开发:是将项目集中存放在中央服务器中,在工作的时候,大家只在自己电脑上操作,从同一个地方下载最新版本 ...