创建一个连接池操作类

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers; namespace CommonAssistant
{ public class MySqlConnectionPool
{
private readonly string sqlConnect = string.Empty;
public MySqlConnectionPool(string Connection)
{
sqlConnect = Connection; //定时器轮询连接,清理不在使用的连接
var timer = new Timer();
timer.Enabled = true;
timer.Elapsed += (a, b) =>
{
//轮询连接池连接,删除满足条件的连接
delwithConnectPool("remove");
Console.WriteLine( "连接数:"+getCount()); };
timer.Interval = * ; //10分钟一次
timer.AutoReset = true;//一直执行
} private static List<ConnectionItem> listConnects = new List<ConnectionItem>(); private static readonly object obj_getConnects = new object();
public Tuple<bool, ConnectionItem> delwithConnectPool(string type)
{
//保证并发条件下集合增删改查时的数据唯一性
lock (obj_getConnects)
{
bool result = false;
ConnectionItem result_item = null;
switch (type)
{
case "get":
var connectItem = listConnects.Where(u => u.ifBusy == false).FirstOrDefault(); if (connectItem == null)
{
listConnects.Add(result_item = getInstance(sqlConnect));
}
else {
if (connectItem.mySqlConn.State == System.Data.ConnectionState.Open)
{
connectItem.setBusy(true);
connectItem.updateTime(DateTime.Now);
result_item = connectItem;
}
else {
listConnects.Add(result_item = getInstance(sqlConnect));
}
} break;
case "remove":
if (listConnects != null && listConnects.Any())
{
//删除移除 超过10分钟未使用的的连接,使用两分钟的未释放连接,连接状态已关闭的连接
var listOuteTimes = listConnects.Where(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > ) || ((DateTime.Now - u.time).TotalSeconds > * ) ||(u.mySqlConn.State != System.Data.ConnectionState.Open) );
foreach (var item in listOuteTimes)
{
item.mySqlConn.Close();
item.mySqlConn.Dispose();//释放
}
//超时连接移除
listConnects.RemoveAll(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > ) || ((DateTime.Now - u.time).TotalSeconds > * ) || (u.mySqlConn.State != System.Data.ConnectionState.Open));
}
break;
}
return new Tuple<bool, ConnectionItem>(result, result_item);
} } public ConnectionItem getInstance(string connect)
{ var item = new ConnectionItem()
{ ifBusy = true,
time = DateTime.Now,
mySqlConn = new MySqlConnection(connect)
};
item.mySqlConn.Open();
return item; } //获取一个空闲连接
public ConnectionItem getFreeConnectItem()
{
return delwithConnectPool("get").Item2;
} public int getCount() {
return listConnects.Count;
} } public class ConnectionItem : IDisposable
{
public DateTime time { get; set; } public MySqlConnection mySqlConn { get; set; } public bool ifBusy { get; set; }//设置是否在使用
public void setBusy(bool busy)
{
ifBusy = busy;
} public void updateTime(DateTime dt)
{
time = dt;
} public void Dispose()
{
ifBusy = false;
}
}
}

基于不同的mysql数据库,使用不同连接池

using System;
using System.Collections.Generic;
using System.Text; namespace CommonAssistant
{
public class WorkDbConnectManage
{
#region 连接池(1)
private static MySqlConnectionPool tempPool_A = null;
private static readonly string dbConnect_A = "Database=ywthgoods;Data Source=localhost;Port=3306;UserId=root;Password=123456;Charset=utf8;TreatTinyAsBoolean=false;Allow User Variables=True"; private static readonly object readPoolA = new object();
public static MySqlConnectionPool getTempPool_A()
{
//双if加锁,有且只创建一个连接池
if (tempPool_A == null)
{
lock (readPoolA)
{
if (tempPool_A == null)
{
tempPool_A = new MySqlConnectionPool(dbConnect_A);
}
}
}
return tempPool_A;
} public static ConnectionItem getWork1Conn_A()
{
return getTempPool_A().getFreeConnectItem(); }
#endregion #region 连接池(2)
private static MySqlConnectionPool tempPool_B = null;
private static readonly string dbConnect_B = ""; private static readonly object readPoolB_lock = new object();
public static MySqlConnectionPool getTempPool_B()
{
//双if加锁,有且只创建一个连接池
if (tempPool_B == null)
{
lock (readPoolB_lock)
{
if (tempPool_A == null)
{
tempPool_A = new MySqlConnectionPool(dbConnect_B);
}
}
}
return tempPool_A;
} public static ConnectionItem getWork1Conn_B()
{
return getTempPool_B().getFreeConnectItem(); }
#endregion }
}

C# 基于创建一个mysql 连接池的更多相关文章

  1. JDBC创建mysql连接池代码

    1.底层实现类(DBConnection) package JDBC.JDBCPool.MyJDBCPool; import java.sql.Connection; import java.sql. ...

  2. Swoole4-swoole创建Mysql连接池

    一 .什么是mysql连接池 场景:每秒同时有1000个并发,但是这个mysql同时只能处理400个连接,mysql会宕机. 解决方案:连接池,这个连接池建立了200个和mysql的连接,这1000个 ...

  3. swoole4创建Mysql连接池

    一 .什么是mysql连接池 场景:每秒同时有1000个并发,但是这个mysql同时只能处理400个连接,mysql会宕机.   解决方案:连接池,这个连接池建立了200个和mysql的连接,这100 ...

  4. 实现一个协程版mysql连接池

    实现一个协程版的mysql连接池,该连接池支持自动创建最小连接数,自动检测mysql健康:基于swoole的chanel. 最近事情忙,心态也有点不积极.技术倒是没有落下,只是越来越不想写博客了.想到 ...

  5. nodejs + redis/mysql 连接池问题

    nodejs + redis/mysql 连接池问题 需不需要连接池 连接池的作用主要是较少每次临时建立连接所带来的开销.初步一看,nodejs运行单线程上,它不能同时使用多个连接,乍一看是不需要连接 ...

  6. MySQL连接池

    1. using System; using System.Collections; using MySql.Data.MySqlClient; namespace Helper { /// < ...

  7. python中实现mysql连接池

    python中实现mysql连接池 import pymysql from DBUtils.PooledDB import PooledDB MYSQL_HOST = 'localhost' USER ...

  8. workerman如何写mysql连接池

    首先要了解为什么用连接池,连接池能为你解决什么问题 连接池主要的作用1.减少与数据服务器建立TCP连接三次握手及连接关闭四次挥手的开销,从而降低客户端和mysql服务端的负载,缩短请求响应时间2.减少 ...

  9. Mysql 连接池

    数据库连接池的作用: 数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个:释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接 ...

随机推荐

  1. Money

    /** * www.yiji.com Inc. * Copyright (c) 2012 All Rights Reserved. */package com.yjf.common.lang.util ...

  2. 迭代器,生成器,yield,yield from理解

    迭代器 说到迭代器就得想说可迭代对象Iterable,实现了__iter__()方法的对象都是可迭代对象,例如很多容器,list ,set, tuples.使用iter方法可以把一个可迭代对象变成迭代 ...

  3. uoj175 【Goodbye Yiwei】新年的网警

    题目 胡乱分析 不妨定谣言的源头得到谣言的时刻为\(1\),那么其他人听到谣言的时间就是源头到这个点的最短路 假设\(i\)是谣言的源头,那么如果存在一个点\(j\)满足\(\forall k\in[ ...

  4. 将arcEngine9.3和dev9.2.4开发的项目升级成arcObject10.2和dev15.1.3过程中遇到的问题和解决

    好久没碰.net了,arcgis更是感觉都忘干净了,今天将arcEngine9.3和dev9.2.4开发的一个项目升级成arcObject10.2和dev15.1.3过程中遇到了一系问题,留个笔记,留 ...

  5. 2018-8-9-win-消息

    title author date CreateTime categories win 消息 lindexi 2018-8-9 15:35:4 +0800 2018-2-13 17:23:3 +080 ...

  6. 喜讯!联诚发创始人龙平芳荣获2019LED行业优秀女企业家称号!联诚发横揽三项大奖!

           2019年12月20日,在深圳大梅沙京基喜来登度假酒店隆重举行“蝶变跨越”慧聪LED显示屏行业品牌盛会颁奖典礼!在来自全国各地的LED显示屏行业协会领导,企业领袖,精英代表以及来自全国各 ...

  7. JavaScript 中 reduce去重方法

    过去有很长一段时间,我一直很难理解 reduce() 这个方法的具体用法,平时也很少用到它.事实上,如果你能真正了解它的话,其实在很多地方我们都可以用得上,那么今天我们就来简单聊聊 JS 中 redu ...

  8. linux挂载群辉的NFS共享文件夹

    mount -t nfs 192.168.137.136:/volume1/NFSfile /NFSfile -o proto=tcp -o nolock  df -h   #查看挂载点    

  9. 在IntelliJ IDEA中新建Maven项目

    在IntelliJ IDEA中新建Maven项目,选择“File->New->Project”,创建一个简单项目,不选择模板,如下图所示: 2 选择“Maven”,不需要使用内置结构(模板 ...

  10. bootstrapTable 分页插件

    前端: @{ ViewBag.Title = "BootstrapTable 入门"; Layout = null; } <!-- 引入bootstrap样式 --> ...