1. First you need to download the driver package jedis.jar make sure to download the latest driver package.
2.public class RedisUtil {
// server IP address
private static String ADDR = "192.168.41.65";
//port
private static int PORT = 6379;
//password
private static String AUTH = "123456";
// The maximum number of instances of connection
private static int MAX_ACTIVE = 1024;
// control a pool up to the number of state jedis instance idle (idle), the default value is 8.
private static int MAX_IDLE = 200;
// maximum time to wait for an available connection, in milliseconds, the default value is -1, never times out. If the wait time is exceeded, then a direct throw JedisConnectionException
private static int MAX_WAIT = 10000;
// connection timeout time
private static int TIMEOUT = 10000;
// When a borrow jedis example, validate whether the operation in advance; jedis instance, if true, the obtained average is available;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
// database 16 is a database schema 0-15
public static final int DEFAULT_DATABASE = 0;
/**
* Initialize the connection pool Redis
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT,AUTH,DEFAULT_DATABASE);
} catch (Exception e) {
e.printStackTrace ();
}
}
/**
* Get Jedis examples
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
System.out.println ( "redis-- service is running:" + resource.ping ());
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace ();
return null;
}
}
/***
*
* Release resources
*/
public static void returnResource(final Jedis jedis) {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}