连接池之一

import java.util.Vector;
import redis.clients.jedis.Jedis;

//简单连接池
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; //当前正使用的连接数
 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);
  }
 }
 
 //这段代码有没有同步的问题?
 public JedisExt getConnection() {
  //先从闲置中获取
  JedisExt j = null;
  for(int i=0;i<size;i++) {
   j = list.get(i);
   if(!j.isused) {
    j.setIsused(true); //使用中
    return j;
   }
  }
  //创建新的连接
  if(size<maxSize) {
   size++;
   JedisExt je = new JedisExt(initConnection(), true);
   list.add(je);
   return je;
  }
  //已到最大连接数返回空
  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; //是否空闲
  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);
  }
 }
}

猜你喜欢

转载自zw7534313.iteye.com/blog/2418625