import java.util.Vector;
import redis.clients.jedis.Jedis;
//Simple connection pool
public class RedisPool {
public static void main(String[] args) {
/*
RedisPool pool = new RedisPool(1,1,1);
for(int i=0;i<2;i++) {
Jedis j = pool.getConnection();
System.out.println(j);
}
pool.close();
RedisPool pool = new RedisPool(1,2,1);
for(int i=0;i<2;i++) {
JedisExt j = pool.getConnection();
System.out.println(j);
if(i==1) {
j.release();
}
}
pool.close();
*/
RedisPool pool = new RedisPool(1,2,1);
new TestThread("t1", pool).start();
new TestThread("t2", pool).start();
new TestThread("t3", pool).start();
}
private Vector<JedisExt> list = new Vector<JedisExt>();
private int size; //Number of connections currently in use
private int maxSize;
private int minSize;
public RedisPool(int size,int maxSize,int minSize) {
this. size = size;
this.maxSize = maxSize;
this.minSize = minSize;
init();
}
private void init() {
JedisExt je = null;
for(int i=0;i<this.size;i++) {
je = new JedisExt(initConnection());
this.list.add(je);
}
}
// Is there any synchronization problem in this code?
public JedisExt getConnection() {
//Get
JedisExt from idle first j = null;
for(int i=0;i<size;i++) {
j = list.get(i);
if(!j.isused) {
j.setIsused(true); //in use
return j;
}
}
//create a new connection
if(size<maxSize) {
size++;
JedisExt je = new JedisExt(initConnection(), true );
list.add(je);
return je;
}
//The maximum number of connections has been reached and return null
return null;
}
public void close() {
JedisExt je = null;
for(int i=0;i<list.size( );i++) {
je = list.get(i);
je.getJedis().close();
}
list.clear();
}
private class JedisExt extends Jedis{
private boolean isused = false; //Is free
private Jedis jedis;
public JedisExt(Jedis j) {
this.jedis = j;
}
public JedisExt(Jedis j, boolean isused) {
this.jedis = j;
this.isused = true;
}
public synchronized boolean isIsused() {
return isused;
}
public synchronized void setIsused(boolean isused) {
this.isused = isused;
}
//释放连接
public void release() {
this.setIsused(false); //未使用
}
public synchronized Jedis getJedis() {
return jedis;
}
}
//获取单个连接
private static Jedis initConnection(){
String host = "192.168.191.128";
Jedis client = new Jedis(host, 6379);
return client;
}
private static class TestThread extends Thread{
private RedisPool pool;
public TestThread(String name, RedisPool pool) {
super(name);
this.pool = pool;
}
public void run() {
JedisExt e = pool.getConnection();
boolean b = false;
if(e!=null) {
b = e.isIsused();
}
System.out.println(e + " " + b);
}
}
}