Java 之 hbase连接池(简易版)

Channel

package com.njbdqn.services.utils;

import org.apache.hadoop.hbase.client.Connection;

/**
 *  数据库连接对象包装类,mysql自己有第三方连接池,hbase还没有
 */
public class Channel {
    private Connection conn;
    private boolean isbusy=false;

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public boolean isIsbusy() {
        return isbusy;
    }

    public void setIsbusy(boolean isbusy) {
        this.isbusy = isbusy;
    }
}

CreateConnection

package com.njbdqn.services.utils;


import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CreateConnection {
    static {
        init();
    }

    private static void init() {
        for(int i = 0;i<3;i++){
            Pool.mkChannel();
        }
    }

    private static Connection conn;
    private static Connection getConnection(){
        return Pool.getChannel().getConn();
    }
    public static void destory(Connection conn){
         Pool.destory(conn);
    }

    private static class Pool{
       private static List<Channel> lst = new ArrayList<>();
       private static int maxpool = 30;
       public static Channel mkChannel(){
           Channel c = new Channel();
           try {
               c.setConn(ConnectionFactory.createConnection());
           } catch (IOException e) {
               e.printStackTrace();
           }
           lst.add(c);
           return c;
       }
       // 拿管子
       public static Channel getChannel(){
           // 循环搜索是否有空闲连接
           for(Channel ch:lst){
               if(!ch.isIsbusy()){
                   ch.setIsbusy(true);
                   return ch;
               }
           }
           // 能否开辟新管子
           if(lst.size()<maxpool){
               Channel ch = mkChannel();
               ch.setIsbusy(true);
               return ch;
           }
           // 等待空闲管子,一段时间retry一次
           try {
               Thread.sleep(3000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           return getChannel();
       }
       // 释放管子
        public static void destory(Connection con){
           for(Channel c:lst){
                if(con == c.getConn()){
                    // 还需要判断是否都能用,比如是否能连上查出来东西
                    c.setIsbusy(false);
                    break;
                }
           }

        }
    }

}

 

posted @ 2020-11-20 13:54  PEAR2020  阅读(1154)  评论(0编辑  收藏  举报