Commit d58bba2b by java-李谡

添加redis依赖

parent 721e1946
package com.ejweb.core.util;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* @author lisu
*/
@Component
public class RedisUtils {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private JedisPool jedisPool;
/**
* 通过key获取储存在redis中的value
* 并释放连接
*
* @param key
* @param indexDb 选择redis库 0-15
* @return 成功返回value 失败返回null
*/
public String get(String key, int indexDb) {
Jedis jedis = null;
String value = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexDb);
value = jedis.get(key);
log.info(value);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return value;
}
/**
* 通过key 对value进行加值+1操作,当value不是int类型时会返回错误,当key不存在是则value为1
*
* @param key
* @return 加值后的结果
*/
public Long incr(String key, int indexDb) {
Jedis jedis = null;
Long res = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexDb);
res = jedis.incr(key);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return res;
}
public String set(String key, Object value, int indexDb) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexDb);
JSON.toJSONString(value);
return jedis.set(key, JSON.toJSONString(value));
} catch (Exception e) {
log.error(e.getMessage());
return "0";
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* 设置过期时间
*
* @param key
* @param unixTime 过期时间的时间戳(秒)
* @return
*/
public Long expireAt(String key, long unixTime, int indexDb) {
Jedis jedis = null;
Long res = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexDb);
res = jedis.expireAt(key, unixTime);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return res;
}
/**
* 设置过期时间
*
* @param key
* @param seconds 过期时间(秒)
* @return
*/
public Long expire(String key, int seconds, int indexDb) {
Jedis jedis = null;
Long res = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexDb);
res = jedis.expire(key, seconds);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return res;
}
/**
* 返还到连接池
*
* @param jedisPool
* @param jedis
*/
public static void returnResource(JedisPool jedisPool, Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment