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. 18年11月5日 NOIP模拟赛

    T1 题解 对于k=100的情况,贪心 对于100%的数据 可以发现,当前的决策只对后面的开采有影响,且剩余耐久度与之后的开采收益成正比,如果倒着考虑这个问题,得出i-n的星球1点耐久度所能获得的最大 ...

  2. MySQL主从.md

    MySQL Replication 概述 Mysql内建的复制功能是构建大型,高性能应用程序的基础.将Mysql的数据分布到多个系统上去,这种分布的机制,是通过将Mysql的某一台主机的数据复制到其它 ...

  3. vue 项目项目启动时由于EsLint代码校验报错

    今天在编写好vue项目代码时,在命令行输入npm start的时候出现了如下图所示的一大堆错误: 在网上查找资料说是缺少EsLint配置文件的问题,最终找到一篇由 hahazexia 编写的一篇博客文 ...

  4. 约束,索引,rownum&rownum

    --constraint --not null 非空约束 --unique 唯一键 --非空&唯一 --自定义检查约束 --创建约束时,为约束起名 --在添加完列后,还可以添加约束 --除了n ...

  5. 记一次爬虫经历(友话APP的Web端)

    背景:学校为迎接新生举办了一个活动,在友话APP的校园圈子内发布动态即可参与活动,最终抽取数名同学赠送福利. 分析:动态的数量会随着迎新的开始逐渐增加,人工统计显然不现实,因此可以使用爬虫脚本在友话A ...

  6. ajax调用webservice 跨域问题

    用js或者jquery跨域调用接口时 对方的接口需要做jsonp处理,你的ajax jsonp调用才可以 egg 接口中已经做了jsonp处理,所以可以跨域调用 //$.ajax({ // url: ...

  7. ganache-cli

    安装: npm install -g ganache-cli@6.1.8 使用: userdeMacBook-Pro:~ user$ ganache-cli -m "success rifl ...

  8. Longest Substring Without Repeating Characters[medium]

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  9. the django travel(two)分页

    一:django路由系统: 注意:我们在urls.py中 定义url的时候,可以加$和不加$,区别的是:加$正则匹配的时候,比如:'/index/$'只能匹配'/index/'这样的url 不能匹配' ...

  10. VSC 插件开发从入门到Hello World

    1.原理放一边,我们先来个Hello,World 1.1 安装基础环境 需要的基础环境列表: Node.js npm vs code yo generator-code yo:全称Yeoman,可以把 ...