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(); }
}
redis工具的更多相关文章
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置
http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...
- SpringBoot整合Redis及Redis工具类撰写
SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...
- redistemplate优雅地操作redis redis 工具类
参考:https://www.cnblogs.com/superfj/p/9232482.html redis 工具类 package com.service; import org.springfr ...
- java的redis工具类
package com.mracale.sell.utils; /** * @Auther: Mracale */ import org.springframework.beans.factory.a ...
- redis 工具
搜索关键词:redis 工具 推荐:http://redisdesktop.com/download 点评:使用顺手,顺畅. ★★★★★ 五星好评 备注:redis key 可以采用某种format ...
- Redis 工具类
项目里的Redis 工具类,写下来以备后用 public class RedisConnector { public class RedisParseResult<T> { public ...
- Redis 工具类 java 实现的redis 工具类
最近了解了一下非关系型数据库 redis 会使用简单的命令 在自己本地电脑 使用时必须先启动服务器端 在启动客户端 redis 简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内 ...
- Java操作Redis工具类
依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...
随机推荐
- Linux usb子系统(二) _usb-skeleton.c精析
"./drivers/usb/usb-skeleton.c"是内核提供给usb设备驱动开发者的海量存储usb设备的模板程序, 程序不长, 通用性却很强,十分经典, 深入理解这个文件 ...
- JavaScript 事件绑定函数
function panTest(m_onClickFun) { var This = this; This.onClickFun = m_onClickFun; /* This.onClickFun ...
- Piggy-Bank 完全背包
来源hdu1114 Problem Description Before ACM can do anything, a budget must be prepared and the necessar ...
- 使用soap遇到的缓存问题
- template.js artTemplate 简洁语法官网下载不了 template.js artTemplate 新下载地址
参考:https://blog.csdn.net/tavatimsa/article/details/82019792
- 查看集成环境 phpstudy 中 mysql 版本号
1. 打开面板 2.其他选项菜单 3. Mysql工具 4. mysql命令行 5.输入密码,回车.phpstudy mysql默认 root 6.运行 select version();
- PHP中递归的实现(附例子)
递归函数是一种调用自己的函数.写递归函数时要小心,因为可能会无穷递归下去.必须确保有充分的方法来终止递归. 一:使用参数引用完成递归函数.操作的是同一块内存地址. <?php $i=1; fun ...
- 2 虚拟机Oracle11.2.0.4服务器端,第三方图形化界面安装步骤
环境: 虚拟机:winserver 2012r2 数据中心版 64位 物理主机:win7 旗舰版 64位 网络环境:网线连接内网,WiFi外网 一.虚拟机相关设置 包括计算机名,与物理主机的网络 ...
- SpringBoot介绍
SpringBoot作用:对框架整合做了简化,和分布式集成.pom.xml中的spring-parent中有很多已经集成好的东西,拿来直接用 SpringBoot核心功能: 1.独立运行的Spring ...
- ajaxFileUpload只能上传一次,和上传同名图片不能上传等bug问题
createUploadForm: function (id, fileElementId) { //create form var formId = 'jUploadForm' + id; var ...