redis工具
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(); } }