Flutter Grpc Client 连接池

关于Flutter Grpc Client 连接的管理,我写了一个,有什么不对的和可以优化的还望大家指正一下。

/**
* 类:ClientChannelManager
 * 描述:连接池管理器
 * 作者:dingzuhua
* 创建时间:2019/3/14 13:20
*/
import 'package:grpc/grpc.dart';
class ClientChannelManager {
	static Map<String,ClientChannelManagerObject> clientChannels = new Map();
	static int maxChannelNumber = 10;//连接上限数
	static String exitKey = '';//优先级最低的key

	static ClientChannel getChannel(String host,int port){
		//连接存在,取缓存,不存在则创建
		if(clientChannels.containsKey(host+'$port')){
 		 	//每取一次请求数量加1
 	 		clientChannels[host+'$port'].number++;
 		 	new Future((){
      			sort();
  			});
  			return clientChannels[host+'$port'].clientChannel;
		}else{
  			return createChannel(host, port);
		}
	}

	static ClientChannel createChannel(String host,int port){
		//如果超过连接上限数
		if(clientChannels.length>=maxChannelNumber){
  			ClientChannelManagerObject object = clientChannels[exitKey];
  			object.clientChannel.shutdown();//关闭优先级最低的连接
  			clientChannels.remove(exitKey);//清出连接池
		}
		print('创建连接,端口:$port');
		 ClientChannel channel = new ClientChannel(host,
   		 									port: port,
    						options: const ChannelOptions(
        		credentials: const ChannelCredentials.insecure()));
		clientChannels[host+'$port'] = new ClientChannelManagerObject()..clientChannel = channel ..number = 1..createtime = new DateTime.now().millisecondsSinceEpoch;
		new Future((){
 			 sort();
		});
		return channel;
	}

	static void sort(){
		 //计算优先级
		 int currentTime = new DateTime.now().millisecondsSinceEpoch;
		double maxProportion = 0.0;
		clientChannels.forEach((String key,ClientChannelManagerObject value){
  			value.proportion = (currentTime-value.createtime)/(value.number*1.0);//时长除以次数,越小优先级越高
 		 	if(value.proportion>maxProportion){
    			maxProportion = value.proportion;
    			exitKey = key;
 		 	}
		});
	}
}

class ClientChannelManagerObject{
	ClientChannel clientChannel;
	int number;//总共请求次数
	int createtime;//第一次创建时间
	double proportion;//时长除以次数,越小优先级越高
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值