关于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;//时长除以次数,越小优先级越高
}