pom.xml添加

    <!--jedis redis客户端-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>provided</scope>
</dependency>

配置文件redis.properties

#最大连接数
redis.poolconfig.maxTotal=20
#最大idle(空闲)状态的jedis实例的个数
redis.poolconfig.maxIdle=10
#最小idle(空闲)状态的jedis实例的个数
redis.poolconfig.minIdle = 2
#在borrow一个jedis实例的时候,如果该值为true的时候,实例肯定是OK的
redis.poolconfig.testOnBorrow=true
#在return一个jedis实例的时候,如果该值为true的时候,放回jedis的连接池的实例肯定是OK的
redis.poolconfig.testOnReturn=true redis.timeout=3000 redis.jedispool.open=true
redis.jedispool.hostandport=127.0.0.1:6379
redis.jedispool.password=123456 redis.sentinelpool.open=false
redis.sentinelpool.masterName=server-M1
redis.sentinelpool.hostandports=127.0.0.1:6379;127.0.0.1:6390;
redis.sentinelpool.password=123456 redis.shardpool.open=false;
redis.shardpool.hostandports=127.0.0.1:6379;127.0.0.1:6380;
redis.shardpool.password=123456

log4j.properties

#rootLogger[即普通的Logger.getLogger()获取到的] start====================================================#
log4j.rootLogger=DEBUG,CONSOLE,A
log4j.addivity.org.apache=false log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-4r [%t] %-5p %c.%M(%F:%L) %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File=${catalina.home}/logs/user-servce.log
log4j.appender.A.DatePattern='.'yyyy-MM-dd
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-4r [%t] %-5p %c.%M(%F:%L) %x - %m%n
#rootLogger end==============================================================================# #InfoLog[即普通的Logger.getLogger("InfoLog")获取到的] start====================================================#
log4j.logger.InfoLog=OFF,B
#不继承rootLogger的设置
log4j.additivity.InfoLog = false
log4j.appender.B=org.apache.log4j.RollingFileAppender
log4j.appender.B.File=${catalina.home}/logs/user-servce.log
log4j.appender.B.layout=org.apache.log4j.PatternLayout
log4j.appender.B.layout.ConversionPattern=[%p] %-d{yyyy-MM-dd HH:mm:ss} [%c %M] %m%n
#InfoLog end====================================================# #ErrorLog[即普通的Logger.getLogger("ErrorLog")获取到的] start====================================================#
log4j.logger.ErrorLog=OFF,C
#不继承rootLogger的设置
log4j.additivity.ErrorLog = false
log4j.appender.C=org.apache.log4j.RollingFileAppender
log4j.appender.C.File=${catalina.home}/logs/user-servce.log
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=[%p] %-d{yyyy-MM-dd HH\:mm\:ss} [%c %M] %m%n
#ErrorLog end====================================================# #其他jar包log设置
log4j.logger.org.springframework=DEBUG
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

以下几个工具类

LogUtil

package com.develop.web.util;

import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class LogUtil{ private static final String utilClass = LogUtil.class.getName();
private static Logger logger = null;
private static ReentrantLock lock = new ReentrantLock(); public static Logger getLogger() { StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); int depath = 0;
if(stacks!=null&&stacks.length>0){
for(int i=0;i<stacks.length;i++){
if(utilClass.equals(stacks[i].getClassName())){
depath = i+1;
break;
}
}
} String className = stacks[depath].getClassName();
lock.lock();
try {
logger = LoggerFactory.getLogger(className);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
} return logger;
}
}

PropertiesUtil

package com.develop.web.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock; public class PropertiesUtil { private static Properties p = new Properties();
private static ReentrantLock lock = new ReentrantLock(); public static void load(String path){
InputStream in = null;
lock.lock();
try {
path = PropertiesUtil.class.getClassLoader().getResource("") + path;
path = path.replaceAll("file:/", "");
       path = path.replaceAll("20%", " ");
in = new FileInputStream(path);
p.load(in); } catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
lock.unlock();
}
} public static String getProperty(String key){
String val = "";
if(p!=null&&p.size()>0){
val = p.getProperty(key);
}else{
String msg = "";
if(p.size()==0){
msg = "请确认是否load()过配置文件.";
}
LogUtil.getLogger().info("key:{}不存在。{}", key, msg);
}
return val;
}
}

RedisPool

package com.develop.web.util;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded; public class RedisPool { private static JedisPoolConfig poolConfig = null;
//jedis连接池
private static JedisPool jedisPool = null; private static JedisSentinelPool sentinelpool = null; private static ShardedJedisPool shardPool = null; static{
init();
} public static void init(){
PropertiesUtil.load("redis.properties");
initPoolConfig();
initJedisPool();
initJedisSentinelPool();
initShardedJedisPool();
} /**
* 获取配置
* @return
*/
private static JedisPoolConfig initPoolConfig(){
if(poolConfig==null){
String maxTotal = PropertiesUtil.getProperty("redis.poolconfig.maxTotal");
String maxIdle = PropertiesUtil.getProperty("redis.poolconfig.maxIdle");
String minIdle = PropertiesUtil.getProperty("redis.poolconfig.minIdle");
String testOnBorrow = PropertiesUtil.getProperty("redis.poolconfig.testOnBorrow");
String testOnReturn = PropertiesUtil.getProperty("redis.poolconfig.testOnReturn"); poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(Integer.parseInt(maxTotal));
poolConfig.setMaxIdle(Integer.parseInt(maxIdle));
poolConfig.setMinIdle(Integer.parseInt(minIdle));
poolConfig.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));
poolConfig.setTestOnReturn(Boolean.parseBoolean(testOnReturn));
//连接耗尽时,是否阻塞,false会抛出异常,true会阻塞直到超时,默认是true
poolConfig.setBlockWhenExhausted(true);
} return poolConfig;
} /**
* 单节点连接池
*/
private static void initJedisPool(){
//检查连接池开启状态
if(!open("redis.jedispool.open")){
if(jedisPool!=null){
if(!jedisPool.isClosed()){
jedisPool.close();
jedisPool = null;
}
}
return;
} if(jedisPool==null){
String hostAndPort = PropertiesUtil.getProperty("redis.jedispool.hostandport");
String password = PropertiesUtil.getProperty("redis.jedispool.password"); if(hostAndPort!=null&&hostAndPort.trim().length()>0){
hostAndPort = hostAndPort.trim().replaceAll(";", "");
String[] hostAndPortArr = getHostAndPortArr(hostAndPort);
if(hostAndPortArr!=null&&hostAndPortArr.length==2){
jedisPool = new JedisPool(poolConfig, hostAndPortArr[0], Integer.parseInt(hostAndPortArr[1]), getTimeout(), password);
}
}else{
jedisPool = new JedisPool(poolConfig, Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT, getTimeout(), password);
}
} } /**
* 该连接池用于应对Redis的Sentinel的主从切换机制,
* 能够正确在服务器宕机导致服务器切换时得到正确的服务器连接,
* 当服务器采用该部署策略的时候推荐使用该连接池进行操作;
*/
private static void initJedisSentinelPool() {
//检查连接池开启状态
if(!open("redis.sentinelpool.open")){
if(sentinelpool!=null){
if(!sentinelpool.isClosed()){
sentinelpool.close();
sentinelpool = null;
}
}
return;
} if(sentinelpool == null){
String hostAndPorts = PropertiesUtil.getProperty("redis.sentinelpool.hostandports");
String masterName = PropertiesUtil.getProperty("redis.sentinelpool.masterName");
String password = PropertiesUtil.getProperty("redis.sentinelpool.password"); //监听器列表
Set<String> sentinels = new HashSet<String>(); if(hostAndPorts!=null&&hostAndPorts.trim().length()>0){
hostAndPorts = hostAndPorts.trim();
String hostAndPortArr[] = hostAndPorts.split(";");
if(hostAndPortArr!=null&&hostAndPortArr.length>0){
for(String hostAndPort :hostAndPortArr){
if(hostAndPort.trim().length()==0){
continue;
}
sentinels.add(hostAndPort);
}
} if(sentinels.size()==0){
sentinels.add(new HostAndPort(Protocol.DEFAULT_HOST, Protocol.DEFAULT_SENTINEL_PORT).toString());
}
} sentinelpool = new JedisSentinelPool(masterName, sentinels, poolConfig, getTimeout(), password, Protocol.DEFAULT_DATABASE);
} } /**
* 初始化ShardedJedisPool连接池
*/
private static void initShardedJedisPool() {
//检查连接池开启状态
if(!open("redis.shardpool.open")){
if(shardPool!=null){
if(!shardPool.isClosed()){
shardPool.close();
shardPool = null;
}
}
return;
} if (shardPool == null) {
List<JedisShardInfo> serverlist = new LinkedList<JedisShardInfo>(); String hostAndPorts = PropertiesUtil.getProperty("redis.shardpool.hostandports");
String password = PropertiesUtil.getProperty("redis.shardpool.password"); if(hostAndPorts!=null&&hostAndPorts.trim().length()>0){
String hostAndPortsArr[] = hostAndPorts.trim().split(";");
if(hostAndPortsArr!=null&&hostAndPortsArr.length>0){
for(String hostAndPort :hostAndPortsArr){
if(hostAndPort.length()==0){
continue;
} String [] hostAndPortArr = getHostAndPortArr(hostAndPort);
if(hostAndPortArr!=null&&hostAndPortArr.length==2){
JedisShardInfo jedisShardInfo = new JedisShardInfo(hostAndPortArr[0], Integer.parseInt(hostAndPortArr[1]), getTimeout());
jedisShardInfo.setPassword(password);
serverlist.add(jedisShardInfo);
}
}
}
} if(serverlist.size()==0){
JedisShardInfo jedisShardInfo = new JedisShardInfo(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT, getTimeout());
jedisShardInfo.setPassword(password);
serverlist.add(jedisShardInfo);
} shardPool = new ShardedJedisPool(poolConfig, serverlist, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
} } /**
* 将ip和端口号分隔出来
* @param hostAndPort
* @return
*/
private static String[] getHostAndPortArr(String hostAndPort){
if(hostAndPort==null||hostAndPort.trim().length()==0){
return null;
} if (!hostAndPort.contains(":")) {
return null;
} return hostAndPort.split(":");
} /**
* 获取超时设置
* @return
*/
private static int getTimeout(){
int timeout = Protocol.DEFAULT_TIMEOUT;
String timeoutStr = PropertiesUtil.getProperty("redis.timeout");
if(timeoutStr!=null&&timeoutStr.trim().length()>0){
timeout = Integer.parseInt(timeoutStr);
}
return timeout;
} /**
* 获取启动那种连接池设置
* @param bundleAttrName
* @return
*/
private static boolean open(String bundleAttrName){
boolean open = false;
String openVal = PropertiesUtil.getProperty(bundleAttrName);
if(openVal.contains("true")||openVal.contains("open")||openVal.contains("1")){
open = true;
}
return open;
} public static Jedis getJedis(){
Jedis jedis = null;
if(jedisPool!=null){
jedis = jedisPool.getResource();
}
return jedis;
} public static Jedis getSentinelJedis(){
Jedis jedis = null;
if(sentinelpool!=null){
jedis = sentinelpool.getResource();
}
return jedis;
} public static void returnJedis(Jedis jedis){
if(jedis!=null){
if(jedis.isConnected()){
jedis.close();
}
jedis = null;
}
} public static ShardedJedis getShardedJedis(){
ShardedJedis shardedJedis = null;
if(shardPool!=null){
shardedJedis = shardPool.getResource();
}
return shardedJedis;
} public static void returnShardedJedis(ShardedJedis shardedJedis){
if(shardedJedis!=null){
shardedJedis.close();
shardedJedis = null;
}
} }

RedisUtil

package com.develop.web.util;
import java.util.UUID; import com.develop.web.util.RedisPool; import redis.clients.jedis.Jedis; /**
* 封装jedis常用api
*/ public class RedisUtil { /***
* 根据key获取value
* @param key
* @return
*/
public static String get(String key){
Jedis jedis = null;
String value = null;
try {
jedis = RedisPool.getJedis();
value = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
LogUtil.getLogger().error("get error key{}", key, e);
return null;
} finally {
RedisPool.returnJedis(jedis);
} LogUtil.getLogger().info("get key:{} value:{}", key, value); return value;
} /***
* 删除key
* @param key
* @return
*/
public static Long del(String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
LogUtil.getLogger().error("del error key:{}", key, e);
return null;
} finally {
RedisPool.returnJedis(jedis);
} LogUtil.getLogger().info("del key:{} result:{}", key, result); return result;
} /**
* 根据key set value
* @param key
* @param value
* @return
*/
public static String set(String key,String value){
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.set(key,value);
} catch (Exception e) {
e.printStackTrace();
LogUtil.getLogger().error("set error key:{} value:{}", key, value, e);
return null;
} finally {
RedisPool.returnJedis(jedis);
} LogUtil.getLogger().info("set key:{} value:{} result:{}", key, value, result); return result;
} /***
*设置session服务器有效时间
* @param key
* @param value
* @param exTime 单位是秒
* @return
*/
public static String setEx(String key, String value, int exTime){
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.setex(key, exTime, value);
} catch (Exception e) {
e.printStackTrace();
LogUtil.getLogger().error("setEx error key:{} value:{} exTime:{}", key, value, exTime, e);
return null;
} finally {
RedisPool.returnJedis(jedis);
} LogUtil.getLogger().info("setEx key:{} value:{} exTime:{} result:{}", key, value, exTime, result); return result;
} /**
* 设置key的有效期
* @param key
* @param exTime
* @return
*/
public static Long expire(String key, int exTime){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.expire(key,exTime);
} catch (Exception e) {
e.printStackTrace();
LogUtil.getLogger().error("expire error key:{} exTime:{}", key, exTime, e);
return null;
} finally {
RedisPool.returnJedis(jedis);
} LogUtil.getLogger().info("expire key:{} exTime:{} result:{}", key, exTime, result); return result;
} public static String createKey(){
long threadId = Thread.currentThread().getId();
int threadHash = Thread.currentThread().hashCode();
long currentTime = System.currentTimeMillis();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
StringBuilder s = new StringBuilder();
s.append(threadId);
s.append("-");
s.append(threadHash);
s.append("-");
s.append(currentTime);
s.append("-");
s.append(uuid); LogUtil.getLogger().info(s.toString());
return s.toString();
} public static void main(String[] args) {
String key = createKey(); }
}

redis工具的更多相关文章

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

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

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

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

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

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

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

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

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

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

  6. java的redis工具类

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

  7. redis 工具

    搜索关键词:redis 工具 推荐:http://redisdesktop.com/download 点评:使用顺手,顺畅. ★★★★★ 五星好评 备注:redis key 可以采用某种format ...

  8. Redis 工具类

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

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

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

  10. Java操作Redis工具类

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

随机推荐

  1. Cocoapods 创建自己的公开库、私有库

    如何创建自己的共有库 1.注册Trunk trunk需要CocoaPods 0.33版本以上,用pod --version 命令查看版本 CocoaPods版本 如果版本低,需要升级: sudo ge ...

  2. 【Zookeeper系列】ZooKeeper机制架构(转)

    原文链接:https://www.cnblogs.com/sunddenly/p/4133784.html 一.ZooKeeper权限管理机制 1.1 权限管理ACL(Access Control L ...

  3. 把Oracle由归档模式改为非归档模式

    把Oracle由归档模式改为非归档模式 开始–>运行命令cmd进入命令行模式 1. 使用命令sqlplus以无日志形式打开如下: sqlplus /nolog; 2. 连接数据库dev.worl ...

  4. Could not find or load main class org.apache.spark.deploy.yarn.ApplicationMaster

    Spark YARN Cluster mode get this error "Could not find or load main class org.apache.spark.depl ...

  5. StreamSocket

    转载自:http://blog.csdn.net/yuanguozhengjust/article/details/19175085 StreamSocket的基本流程和一般的Socket通信操作类似 ...

  6. 线段树合并 || 树状数组 || 离散化 || BZOJ 4756: [Usaco2017 Jan]Promotion Counting || Luogu P3605 [USACO17JAN]Promotion Counting晋升者计数

    题面:P3605 [USACO17JAN]Promotion Counting晋升者计数 题解:这是一道万能题,树状数组 || 主席树 || 线段树合并 || 莫队套分块 || 线段树 都可以写..记 ...

  7. C和C指针小记(十七)-使用结构和指针-链表

    1.链表 链表(linked list)即使是一些包含数据的独立数据结构的(Node)集合. 链表中的每个节点通过链或指针链接在一起. 程序通过指针访问链表中的节点. 节点通常是动态分配的,但也有由节 ...

  8. 全文索引&&地理空间索引

    Ⅰ.全文索引 搜索引擎的实现核心技术,搜索类似where col like '%xxx%';关键字可以出现再某个列任何位置 这种查询条件,B+ tree索引是无法使用的.如果col上创建了索引,因为排 ...

  9. day5_非空即真非零即真

    非空即真(字符串.元组.列表.字典.None),非零即真(指的是int类型或数字这种) # d={}# l=[]# t=()# a = ''# b = None以上都代表空 举例1: name = i ...

  10. IO调度算法的选择

    一) I/O调度程序的总结 1) 当向设备写入数据块或是从设备读出数据块时,请求都被安置在一个队列中等待完成. 2) 每个块设备都有它自己的队列. 3) I/O调度程序负责维护这些队列的顺序,以更有效 ...