import java.util.Arrays;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisUtils {
// Redis服务器IP
private static String ADDR = "localhost";

// Redis的端口号
private static int PORT = 6379;

// 访问密码,若你的redis服务器没有设置密码,就不需要用密码去连接
// private static String AUTH = "123456";

// 可用连接实例的最大数目,默认值为8;
private static int MAX_TOTAL = 512;

// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 50;

// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
private static int MAX_WAIT = -1;

private static int TIMEOUT = 100000;

// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;

private static JedisPool jedisPool = null;

private static List<JedisShardInfo> shards = null;

private static ShardedJedisPool shardedJedisPool = null;

private static Object lock = new Object();

public static void setADDR(String aDDR, int port) {
ADDR = aDDR;
PORT = port;
}

private static Logger log = Logger.getLogger(RedisUtils.class);

/**
* 初始化Redis连接池
*/
private static void initJedisPool() {
synchronized (lock) {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_TOTAL);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
} catch (Exception e) {
log.error("initJedisPool出错:" + e);
}
}
}

private static void initShardedJedisPool() {
synchronized (lock) {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_TOTAL);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
JedisShardInfo info = new JedisShardInfo(ADDR, PORT);
info.setTimeout(TIMEOUT);
shards = Arrays.asList(info);
shardedJedisPool = new ShardedJedisPool(config, shards);
} catch (Exception e) {
log.error("initShardedJedisPool出错:" + e);
}
}
}

/**
* 获取shardedJedis实例
* @return
*/
public static ShardedJedis getShardedJedis() {
try {
if (shardedJedisPool == null) {
initShardedJedisPool();
}
ShardedJedis jedis = shardedJedisPool.getResource();
return jedis;
} catch (Exception e) {
log.error("getShardedJedis出错:" + e);
return null;
}
}

/**
* 释放shardedJedis资源
* @param jedis
*/
public static void returnShardedResource(final ShardedJedis jedis) {
if (jedis != null) {
shardedJedisPool.returnResource(jedis);
}
}

/**
* 获取Jedis实例
* @return
*/
public static Jedis getJedis() {
try {
if (jedisPool == null) {
initJedisPool();
}
Jedis jedis = jedisPool.getResource();
return jedis;
} catch (Exception e) {
log.error("getJedis出错:" + e);
return null;
}
}

/**
* 释放jedis资源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}

/**
* 根据key值来获取对应的数据
* @param key
* @return
*/
public static String getString(final String key) {
String result = "";
try (Jedis jedis = getJedis()) {
if (StringUtils.isEmpty(key)) {
return result;
}
result = jedis.get(key);
} catch (Exception e) {
log.error("get String fail", e);
}
return result;
}

/**
* 设置缓存
* @param key
* @param values
*/
public static void setString(final String key, final String values) {
try (Jedis jedis = getJedis()) {
if (StringUtils.isEmpty(key)) {
return;
}
jedis.set(key, values);
} catch (Exception e) {
log.error("set String fail", e);
}

}

/**
* 根据key值来删除缓存
* @param key
* @return
*/
public static long delKey(final String key) {
long result = 0;
try (Jedis jedis = getJedis()) {
if (StringUtils.isEmpty(key)) {
return result;
}
result = jedis.del(key);
} catch (Exception e) {
log.error("del key fail", e);
}
return result;
}

/**
* 生成key genKey
* @param projectId
* @param module
* @param unit
* @return String
*/
public static String genKey(String projectId, String module, String unit) {
StringBuilder builder = new StringBuilder();
builder.append(unit);
builder.append("_");
builder.append(module);
builder.append(projectId);
return builder.toString();
}

/**
* 设置键值 setString
* @param key
* @param values
* @param seconds
*/
public static void setString(final String key, final String values, final int seconds) {
try (Jedis jedis = getJedis()) {
if (StringUtils.isEmpty(key)) {
return;
}
jedis.setex(key, seconds, values);
} catch (Exception e) {
log.error("set String and expire fail ", e);
}
}

public synchronized static void deleteKey(String... keys) {
try (Jedis jedis = getJedis()) {

jedis.del(keys);
} catch (Exception e) {
log.error("delete key[] fail ", e);
}
}

public synchronized static void deleteKeys(String pattern) {
try (Jedis jedis = getJedis()) {
Set<String> keySet = jedis.keys(pattern);
if (keySet == null || keySet.size() <= 0) {
return;
}
String keyArr[] = new String[keySet.size()];
int i = 0;
for (String keys : keySet) {
keyArr[i] = keys;
i++;
}
deleteKey(keyArr);
} catch (Exception e) {
log.error("delete keys by pattern fail ", e);
}

}

public synchronized static void deleteKeyByPrefix(String prefix) {
deleteKeys(prefix + "*");
}

public synchronized static void deleteKeyByContain(String contain) {
deleteKeys("*" + contain + "*");
}

}

简单的redis工具类的更多相关文章

  1. Redis 工具类 java 实现的redis 工具类

    最近了解了一下非关系型数据库 redis 会使用简单的命令 在自己本地电脑 使用时必须先启动服务器端 在启动客户端 redis 简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内 ...

  2. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  3. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  4. redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置

    http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...

  5. SpringBoot整合Redis及Redis工具类撰写

            SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...

  6. redistemplate优雅地操作redis redis 工具类

    参考:https://www.cnblogs.com/superfj/p/9232482.html redis 工具类 package com.service; import org.springfr ...

  7. java的redis工具类

    package com.mracale.sell.utils; /** * @Auther: Mracale */ import org.springframework.beans.factory.a ...

  8. Redis 工具类

    项目里的Redis 工具类,写下来以备后用 public class RedisConnector { public class RedisParseResult<T> { public ...

  9. Java操作Redis工具类

    依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...

随机推荐

  1. JPA规范实现

    JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. JPA 是 JCP定义的一种规范,要使用此规 ...

  2. jQuery 和 YUI (Yahoo User Interface) 各自的优缺点有哪些?具体的使用场景是怎样的?

    张经纬,前端工程师 知乎用户.赵勇杰.知乎用户 等人赞同 其实jQuery和YUI的侧重点是不一样的. jQuery专注于DOM的操作,他通过继承的方式给传入的对象增加了新的方法,从而使我们可以通过链 ...

  3. 加密算法--->对称加密与非对称加密算举例说明

    目前主流的加密方式有:(对称加密)AES.DES        (非对称加密)RSA.DSA 对称加密例子:des对称加密 des对称加密,对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用 ...

  4. PHPExcel 导入

    首先: //包含excel的类库require APPPATH . 'third_party/PHPExcel.php';require APPPATH . 'third_party/PHPExcel ...

  5. 自动搭建ssm项目

    手把手教你搭建ssm项目 注意,必须修改:包名.数据库名称.账号.密码 注意:必须配置好第一次,“引入后”才能配置第二次 第一步:打开idea选择创建maven项目 import java.io.*; ...

  6. vue-cli 安装失败Failed to download repo vuejs-templates/vuedemo: Response code 404 (Not Found)

    还原问题现场: 第一次使用vue init webpack projectName的时候,由于操作失误,执行了两次npm install -g vue-cli,然后再使用vue init webpac ...

  7. Threadpool python3

    from concurrent.futures import ThreadPoolExecutor,ALL_COMPLETED,wait,as_completedimport time def add ...

  8. cpu负载过高分析

    如何定位是哪个服务进程导致CPU过载,哪个线程导致CPU过载,哪段代码导致CPU过载? 步骤一.找到最耗CPU的进程 工具:top 方法: 执行top -c ,显示进程运行信息列表 键入P (大写p) ...

  9. 使用CSS3的“transition ”属性控制长宽度的缓慢变化

    有时候我们可能会想要改变某个资源信息的长宽度,比如改变某个div的宽度,而且需要让这个宽度缓慢改变,而不是突然就改变了.这时候你可能会想到使用jquery的animate()函数,不过这个方法既得引用 ...

  10. 解决JS在url中传递参数时参数包含中文乱码的问题

    1.传参页面JavaScript代码: function go_mark(id,jobname,headimgurl,nickname){ window.location.href = "m ...