(一)、新建JedisPoolTest类,测试连接池
package org.hx.jedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisPoolTest {
public static void main(String[] args) {
JedisPool pool = new JedisPool("192.168.133.8",6379);
try(Jedis jedis = pool.getResource()) {
jedis.auth("hx");
String ping = jedis.ping();
System.out.println(ping);
}
}
}
(二)、实现强约束
新建CallwithJedis接口
package org.hx.jedis;
import redis.clients.jedis.Jedis;
public interface CallwithJedis {
void call(Jedis jedis);
}
新建Redis类
package org.hx.jedis;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Redis {
private JedisPool jedisPool;
public Redis(){
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxIdle(300);
config.setMaxTotal(1000);
config.setMaxWaitMillis(10000);
config.setTestOnBorrow(true);
jedisPool = new JedisPool(config,"192.168.133.8",6379,10000,"hx");
}
public void execute(CallwithJedis callwithJedis){
try(Jedis jedis = jedisPool.getResource()){
callwithJedis.call(jedis);
}
}
}
新建MyJedis类
package org.hx.jedis;
import redis.clients.jedis.Jedis;
public class MyJedis {
public static void main(String[] args) {
Redis redis = new Redis();
redis.execute(jedis -> {
System.out.println(jedis.ping());
});
}
}