//简单连接池之二
public class RedisPool2 {
public static void main(String[] args) {
RedisPool2 pool = new RedisPool2(10,20,5);
try {
for(int i=0;i<28;i++) {
Thread t1 = new TestThread2("t"+i, pool);
t1.start();
t1.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.close();
}
//private Vector<JedisExt> list = new Vector<JedisExt>();
private List<JedisExt> list = new LinkedList<JedisExt>();
private int size; //当前正使用的连接数
private int maxSize;
private int minSize;
public RedisPool2(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);
}
}
public synchronized JedisExt getConnection() {
//先从闲置中获取,从list删除
JedisExt j = null;
for(int i=0;i<size;i++) {
//j = list.get(i);
j = list.remove(i);
if(!j.isused) {
System.out.println("获取连接..");
j.setIsused(true); //使用中
return j;
}
}
//创建新的连接
if(size<maxSize) {
System.out.println("创建新连接..");
size++;
JedisExt je = new JedisExt(initConnection(), true);
//list.add(je);
return je;
}
//已到最大连接数返回空
System.out.println("无连接..");
return null;
}
//关闭所有连接
public synchronized void close() {
JedisExt je = null;
for(int i=0;i<list.size();i++) {
je = list.get(i);
je.getJedis().close();
}
list.clear();
this.size = 0;
}
//释放连接
public synchronized void release(JedisExt e) {
e.setIsused(false);
list.add(e); //加入list
//size++;
}
private class JedisExt extends Jedis{
private boolean isused = false; //是否空闲
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 close() {
this.setIsused(false); //未使用
//this.jedis.close();
}
public synchronized Jedis getJedis() {
return jedis;
}
}
//获取单个连接
private static Jedis initConnection(){
String host = "192.168.19.1";
Jedis client = new Jedis(host, 6379);
return client;
}
private static class TestThread2 extends Thread{
private RedisPool2 pool;
public TestThread2(String name, RedisPool2 pool) {
super(name);
this.pool = pool;
}
public void run() {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
JedisExt e = pool.getConnection();
boolean b = false;
if(e!=null) {
b = e.isIsused();
}
System.out.println(e + " " + b);
try {
Thread.sleep(new Random().nextInt(600));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
//释放连接
if(e!=null)
pool.release(e);
}
}
}