项目github地址:https://github.com/lalalallalala/SSMJedis 对你有帮助的话点个star
一.pom引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二.创建config.properties
# Redis服务器地址
redis.host=127.0.0.1
# Redis服务器连接端口
redis.port=6379
# Redis服务器连接密码(默认为空)
redis.password=
# 连接超时时间(毫秒)
redis.timeout=10000
# 连接池最大连接数(使用负值表示没有限制)
redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.pool.max-wait=-1
# 连接池中的最大空闲连接
redis.pool.max-idle=8
# 连接池中的最小空闲连接
redis.pool.min-idle=0
三.创建JedisConfig
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:config.properties")
@ConfigurationProperties(prefix = "redis")
public class JedisConfig {
/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(JedisConfig.class);
private String host;
private int port;
private String password;
private int timeout;
@Value("${redis.pool.max-active}")
private int maxActive;
@Value("${redis.pool.max-wait}")
private int maxWait;
@Value("${redis.pool.max-idle}")
private int maxIdle;
@Value("${redis.pool.min-idle}")
private int minIdle;
@Bean
public JedisPool redisPoolFactory() {
try {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWait);
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMinIdle(minIdle);
// 密码为空设置为null
if (StringUtil.isBlank(password)) {
password = null;
}
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
logger.info("初始化Redis连接池JedisPool成功!地址: {}:{}", host, port);
return jedisPool;
} catch (Exception e) {
logger.error("初始化Redis连接池JedisPool异常:{}", e.getMessage());
}
return null;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
}
四.创建jedisutil工具类
@Component
public class JedisUtil {
/**
* 静态注入JedisPool连接池
* 本来是正常注入JedisUtil,可以在Controller和Service层使用,但是重写Shiro的CustomCache无法注入JedisUtil
* 现在改为静态注入JedisPool连接池,JedisUtil直接调用静态方法即可
*
*/
private static JedisPool jedisPool;
@Autowired
public void setJedisPool(JedisPool jedisPool) {
JedisUtil.jedisPool = jedisPool;
}
/**
* 获取Jedis实例
* @param
* @return redis.clients.jedis.Jedis
* @author dolyw.com
* @date 2018/9/4 15:47
*/
public static synchronized Jedis getJedis() {
try {
if (jedisPool != null) {
return jedisPool.getResource();
} else {
return null;
}
} catch (Exception e) {
throw new RuntimeException("获取Jedis资源异常:" + e.getMessage());
}
}
/**
* 释放Jedis资源
* @param
* @return void
* @author dolyw.com
* @date 2018/9/5 9:16
*/
public static void closePool() {
try {
jedisPool.close();
} catch (Exception e) {
throw new RuntimeException("释放Jedis资源异常:" + e.getMessage());
}
}
/**
* 获取redis键值-object
* @param key
* @return java.lang.Object
* @author dolyw.com
* @date 2018/9/4 15:47
*/
public static Object getObject(String key) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] bytes = jedis.get(key.getBytes());
if (StringUtil.isNotNull(bytes)) {
return SerializableUtil.unserializable(bytes);
}
} catch (Exception e) {
throw new RuntimeException("获取Redis键值getObject方法异常:key=" + key + " cause=" + e.getMessage());
}
return null;
}
/**
* 设置redis键值-object
* @param key
* @param value
* @return java.lang.String
* @author dolyw.com
* @date 2018/9/4 15:49
*/
public static String setObject(String key, Object value) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.set(key.getBytes(), SerializableUtil.serializable(value));
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setObject方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-object-expiretime
* @param key
* @param value
* @param expiretime
* @return java.lang.String
* @author dolyw.com
* @date 2018/9/4 15:50
*/
public static String setObject(String key, Object value, int expiretime) {
String result;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.set(key.getBytes(), SerializableUtil.serializable(value));
if (Constant.OK.equals(result)) {
jedis.expire(key.getBytes(), expiretime);
}
return result;
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setObject方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 获取redis键值-Json
* @param key
* @return java.lang.Object
* @author dolyw.com
* @date 2018/9/4 15:47
*/
public static String getJson(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.get(key);
} catch (Exception e) {
throw new RuntimeException("获取Redis键值getJson方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-Json
* @param key
* @param value
* @return java.lang.String
* @author Wang926454
* @date 2018/9/4 15:49
*/
public static String setJson(String key, String value) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.set(key, value);
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setJson方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 设置redis键值-Json-expiretime
* @param key
* @param value
* @param expiretime
* @return java.lang.String
* @author Wang926454
* @date 2018/9/4 15:50
*/
public static String setJson(String key, String value, int expiretime) {
String result;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.set(key, value);
if (Constant.OK.equals(result)) {
jedis.expire(key, expiretime);
}
return result;
} catch (Exception e) {
throw new RuntimeException("设置Redis键值setJson方法异常:key=" + key + " value=" + value + " cause=" + e.getMessage());
}
}
/**
* 删除key
* @param key
* @return java.lang.Long
* @author Wang926454
* @date 2018/9/4 15:50
*/
public static Long delKey(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.del(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("删除Redis的键delKey方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* key是否存在
* @param key
* @return java.lang.Boolean
* @author Wang926454
* @date 2018/9/4 15:51
*/
public static Boolean exists(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.exists(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("查询Redis的键是否存在exists方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 模糊查询获取key集合(keys的速度非常快,但在一个大的数据库中使用它仍然可能造成性能问题,生产不推荐使用)
* @param key
* @return java.util.Set<java.lang.String>
* @author Wang926454
* @date 2018/9/6 9:43
*/
public static Set<String> keysS(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(key);
} catch (Exception e) {
throw new RuntimeException("模糊查询Redis的键集合keysS方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 模糊查询获取key集合(keys的速度非常快,但在一个大的数据库中使用它仍然可能造成性能问题,生产不推荐使用)
* @param key
* @return java.util.Set<java.lang.String>
* @author Wang926454
* @date 2018/9/6 9:43
*/
public static Set<byte[]> keysB(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(key.getBytes());
} catch (Exception e) {
throw new RuntimeException("模糊查询Redis的键集合keysB方法异常:key=" + key + " cause=" + e.getMessage());
}
}
/**
* 获取过期剩余时间
* @param key
* @return java.lang.String
* @author Wang926454
* @date 2018/9/11 16:26
*/
public static Long ttl(String key) {
Long result = -2L;
try (Jedis jedis = jedisPool.getResource()) {
result = jedis.ttl(key);
return result;
} catch (Exception e) {
throw new RuntimeException("获取Redis键过期剩余时间ttl方法异常:key=" + key + " cause=" + e.getMessage());
}
}
}
五 序列化工具类SerializableUtil
public class SerializableUtil {
private SerializableUtil() {}
/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);
/**
* 序列化
* @param object
* @return byte[]
* @author dolyw.com
* @date 2018/9/4 15:14
*/
public static byte[] serializable(Object object) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
return baos.toByteArray();
} catch (IOException e) {
logger.error("SerializableUtil工具类序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}
/**
* 反序列化
* @param bytes
* @return java.lang.Object
* @author dolyw.com
* @date 2018/9/4 15:14
*/
public static Object unserializable(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (ClassNotFoundException e) {
logger.error("SerializableUtil工具类反序列化出现ClassNotFoundException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
} finally {
try {
if (ois != null) {
ois.close();
}
if (bais != null) {
bais.close();
}
} catch (IOException e) {
logger.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
throw new RuntimeException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
}
}
}
}
其他的字符串处理类
StringUtil和Constant
public class StringUtil {
private StringUtil() {}
/**
* 定义下划线
*/
private static final char UNDERLINE = '_';
/**
* String为空判断(不允许空格)
* @param str
* @return boolean
* @author dolyw.com
* @date 2018/9/4 14:49
*/
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}
/**
* String不为空判断(不允许空格)
* @param str
* @return boolean
* @author dolyw.com
* @date 2018/9/4 14:51
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
/**
* Byte数组为空判断
* @param bytes
* @return boolean
* @author dolyw.com
* @date 2018/9/4 15:39
*/
public static boolean isNull(byte[] bytes) {
// 根据byte数组长度为0判断
return bytes == null || bytes.length == 0;
}
/**
* Byte数组不为空判断
* @param bytes
* @return boolean
* @author dolyw.com
* @date 2018/9/4 15:41
*/
public static boolean isNotNull(byte[] bytes) {
return !isNull(bytes);
}
/**
* 驼峰转下划线工具
* @param param
* @return java.lang.String
* @author dolyw.com
* @date 2018/9/4 14:52
*/
public static String camelToUnderline(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}
/**
* 下划线转驼峰工具
* @param param
* @return java.lang.String
* @author dolyw.com
* @date 2018/9/4 14:52
*/
public static String underlineToCamel(String param) {
if (isNotBlank(param)) {
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c == 95) {
i++;
if (i < len) {
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
} else {
return "";
}
}
/**
* 在字符串两周添加''
* @param param
* @return java.lang.String
* @author dolyw.com
* @date 2018/9/4 14:53
*/
public static String addSingleQuotes(String param) {
return "\'" + param + "\'";
}
}
public class Constant {
private Constant() {}
/**
* redis-OK
*/
public static final String OK = "OK";
/**
* redis过期时间,以秒为单位,一分钟
*/
public static final int EXRP_MINUTE = 60;
/**
* redis过期时间,以秒为单位,一小时
*/
public static final int EXRP_HOUR = 60 * 60;
/**
* redis过期时间,以秒为单位,一天
*/
public static final int EXRP_DAY = 60 * 60 * 24;
/**
* redis-key-前缀-shiro:cache:
*/
public static final String PREFIX_SHIRO_CACHE = "shiro:cache:";
/**
* redis-key-前缀-shiro:access_token:
*/
public static final String PREFIX_SHIRO_ACCESS_TOKEN = "shiro:access_token:";
/**
* redis-key-前缀-shiro:refresh_token:
*/
public static final String PREFIX_SHIRO_REFRESH_TOKEN = "shiro:refresh_token:";
/**
* JWT-account:
*/
public static final String ACCOUNT = "account";
/**
* JWT-currentTimeMillis:
*/
public static final String CURRENT_TIME_MILLIS = "currentTimeMillis";
/**
* PASSWORD_MAX_LEN
*/
public static final Integer PASSWORD_MAX_LEN = 8;
}
六 测试使用
注意bean类要存到redis中,需要实现Serializable接口,否则会报错,存取都成功。