jedis是Redis的Java客户端,用它可以很方便地操作redis。
需要引入的jar包有jedis和common-pool2,用Maven来引入:
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
一个简单的redis client如下,只操作list。
public class RedisClient {
private static final Logger logger = Logger.getLogger(RedisClient.class);
private JedisPool jedisPool = null;
private String hostname_;
private int port_;
/**
* 初始化连接池
* @param hostname
* @param port
*/
public boolean initialPool(String hostname, int port)
{
this.hostname_ = hostname;
this.port_ = port;
try{
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(5);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config,hostname,port);
logger.info(MessageFormat.format("redis server connect sucessfully,hostname:{0},port:{1}", hostname , port));
}catch(JedisConnectionException e){
logger.warn(MessageFormat.format("redis server connect fail,hostname:{0},port:{1}", hostname , port));
logger.error(e.getMessage(),e);
return false;
}
return true;
}
/**
* ping redis节点
* @return
*/
public boolean ping(){
if(jedisPool!=null && !jedisPool.isClosed()){
return true;
}
logger.warn(MessageFormat.format("redis server ping fail,hostname:{0},port:{1}", hostname_ , port_));
return initialPool(hostname_, port_);
}
/**
* push到队列
* @param key
* @param value
*/
public void PushList(String key,String value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.rpush(key, value);
logger.debug("Push:"+key+","+value);
} catch (Exception e) {
logger.error("failed to push to list");
logger.error(e.getMessage(),e);
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* * pop队列
* @param key
*/
public String PopList(String key){
Jedis jedis = null;
String value = null;
try {
jedis = jedisPool.getResource();
value = jedis.lpop(key);
if(value != null){
logger.debug("Pop:"+key+","+value);
}
} catch (Exception e) {
logger.error("failed to pop from list");
logger.error(e.getMessage(),e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}