首页 > 其他分享 >Dapper简单使用读写分离

Dapper简单使用读写分离

时间:2023-06-23 10:12:20浏览次数:43  
标签:return string 读写 分离 new using Dapper public listconnectionInfoEntity

using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Linq;
using CloudCubic.Common.LogHelper;
using Cloudcubic.Common;
using System.Diagnostics;

namespace CloudCubic.Common.Helper
{
    /// <summary>
    /// 多为异步操作 部分函数
    /// </summary>
    public class YlfDapperHelper
    {
        public static async Task<List<T>> SqlQueryListAsync<T>(string sql, object parames = null, int timeOutSencond = 20, CommandType sqltype = CommandType.Text, bool mainDb = false)
        {
            try
            {
                using (IDbConnection conn = GetDbConnnetion(mainDb))
                {
                    var data = await conn.QueryAsync<T>(sql, parames, commandTimeout: timeOutSencond, commandType: sqltype);
                    return data != null ? data.ToList() : new List<T>();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parames"></param>
        /// <param name="mainDb"></param>
        /// <returns></returns>
        public static async Task<T> SqlQueryOrProcedureAsync<T>(string sql, object parames = null, int timeOutSencond = 20, CommandType sqltype = CommandType.Text, bool mainDb = false)
        {
            try
            {
                using IDbConnection conn = GetDbConnnetion(mainDb);
                return await conn.ExecuteScalarAsync<T>(sql, parames, commandTimeout: timeOutSencond, commandType: sqltype);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        /// <summary>
        /// 查询  
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parames"></param>
        /// <returns></returns>
        public static async Task<T> SQlQueryFirstOrDefault<T>(string sql, object parames = null, int timeOutSencond = 20, CommandType sqltype = CommandType.Text, bool mainDb = false)
        {
            try
            {
                using IDbConnection conn = GetDbConnnetion(mainDb);
                return await conn.QueryFirstOrDefaultAsync<T>(sql, parames, commandTimeout: timeOutSencond, commandType: sqltype);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        /// <summary>
        /// 查询单个值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parames"></param>
        /// <param name="timeOutSencond"></param>
        /// <param name="sqltype"></param>
        /// <param name="mainDb"></param>
        /// <returns></returns>
        public static async Task<T> SQlQuerySingleAsync<T>(string sql, object parames = null, int timeOutSencond = 20, CommandType sqltype = CommandType.Text, bool mainDb = false)
        {
            try
            {
                using IDbConnection conn = GetDbConnnetion(mainDb);
                return await conn.QuerySingleAsync<T>(sql, parames, commandTimeout: timeOutSencond, commandType: sqltype);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        ///// <summary>
        ///// 同时查询多个实体的操作
        ///// </summary>
        ///// <param name="sql"></param>
        ///// <param name="funcObj"></param>
        ///// <param name="dicParams"></param>
        ///// <returns></returns>
        //public static async void QueryMultipeEntityAsync(string sql, Dictionary<string, object> dicParams, Action<GridReader> funcObj, int timeOutSencond = 20, bool mainDb = false)
        //{
        //    using IDbConnection conn = await GetDbConnnetion(mainDb);
        //    if (dicParams != null)
        //    {
        //        DynamicParameters ps = new DynamicParameters();
        //        foreach (string item in dicParams.Keys)
        //        {
        //            ps.Add(item, dicParams[item]);
        //        }
        //        using (var readRsult = await conn.QueryMultipleAsync(sql, ps, commandTimeout: timeOutSencond))
        //        {
        //            funcObj.Invoke(readRsult);
        //        }
        //    }
        //}

        /// <summary>
        /// 执行sql 并返回受影响的行数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parames"></param>
        /// <param name="mainDb">写入默认为主库true</param>
        /// <returns></returns>
        public static async Task<int> SQlExecuteAsync(string sql, object parames = null, int timeOutSencond = 20, CommandType sqltype = CommandType.Text, bool mainDb = true)
        {
            try
            {
                using IDbConnection conn = GetDbConnnetion(mainDb);
                return await conn.ExecuteAsync(sql, parames, commandTimeout: timeOutSencond, commandType: sqltype);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        /// <summary>
        /// 获取 数据库连接 true:主库;false:从库
        /// </summary>
        /// <returns></returns>
        private static IDbConnection GetDbConnnetion(bool mainDb = false)
        {
            var listconnectionInfoEntity = YLF_ConfigHelper.listConfigEntity;
            // YLF_ConfigHelper._configuration.GetSection("DBS").Get<DBOptionsInFo[]>();
            if (listconnectionInfoEntity == null)
                throw new Exception("请检查是否存在数据库连接字符串");

            // List<string> listConnection = new List<string>();//第一个索引为主库,
            if (!mainDb) //从数据库,通常为读的数据库
            {
                if (listconnectionInfoEntity != null && listconnectionInfoEntity.Length <= 1)
                {
                    SerilogServer.WriteLog("dbconStr111", new string[] { listconnectionInfoEntity[0].Connection });
                    return new SqlConnection(listconnectionInfoEntity[0].Connection);
                }
                else if (listconnectionInfoEntity != null && listconnectionInfoEntity.Length > 2)//两个从库就开始随机
                {
                    int index = new Random().Next(1, listconnectionInfoEntity.Length - 1);
                    return new SqlConnection(listconnectionInfoEntity[index].Connection);
                }
                else
                {
                    //Console.WriteLine($"=====listconnectionInfoEntity>2===={listconnectionInfoEntity[1].Connection}====");
                    //SerilogServer.WriteLog("dbconStr_else", new string[] { listconnectionInfoEntity[1].Connection });
                    return new SqlConnection(listconnectionInfoEntity[1].Connection);
                }
            }
            else
            {
                return new SqlConnection(listconnectionInfoEntity[0].Connection);
            }
        }
        /// <summary>
        /// 返回的是
        /// </summary>
        /// <param name="mainDb"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private static string GetDbConnnetionStr(bool mainDb = false)
        {
            var listconnectionInfoEntity = YLF_ConfigHelper.listConfigEntity;
            if (listconnectionInfoEntity == null)
                throw new Exception("请检查是否存在数据库连接字符串");
            if(mainDb)
            {
                if (listconnectionInfoEntity != null && listconnectionInfoEntity.Length <= 1)
                {
                    Console.WriteLine("=====listconnectionInfoEntity.Length <= 1======");
                    SerilogServer.WriteLog("dbconStr111", new string[] { listconnectionInfoEntity[0].Connection });

                    return  listconnectionInfoEntity[0].Connection;
                }
                else if (listconnectionInfoEntity != null && listconnectionInfoEntity.Length > 2)//两个从库就开始随机
                {
                    int index = new Random().Next(1, listconnectionInfoEntity.Length - 1);
                    Console.WriteLine($"=====listconnectionInfoEntity>2===={index}====");
                    return  listconnectionInfoEntity[index].Connection;
                }
                else
                {
                    return  listconnectionInfoEntity[1].Connection;
                }
            }
            else
            {
                return  listconnectionInfoEntity[0].Connection;
            }
        }

        /// <summary>
        /// 执行存储过程,迁移
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="parms"></param>
        /// <param name="tableNames"></param>
        /// <param name="cmdType"></param>
        /// <param name="isMainDB"></param>
        /// <returns></returns>
        public static DataSet RunProcedure(string cmdText, SqlParameter[] parms, string tableNames, CommandType cmdType = CommandType.StoredProcedure, bool isMainDB = false)
        {
            DataSet ds = new DataSet();
            var listconnectionInfoEntity = YLF_ConfigHelper.listConfigEntity;
            string newConnectionString = listconnectionInfoEntity[0].Connection;// connectionString;
            if (isMainDB) newConnectionString = GetDbConnnetionStr(isMainDB);
            using (SqlConnection conn = new SqlConnection(newConnectionString))
            {
                using (SqlCommand comm = new SqlCommand())
                {
                    try
                    {
                        conn.Open();
                        comm.Connection = conn;
                        comm.CommandText = cmdText;
                        comm.CommandTimeout = 600;
                        comm.CommandType = cmdType;
                        if (parms != null)
                        {
                            foreach (SqlParameter parm in parms)
                            {
                                comm.Parameters.Add(parm);
                            }
                        }
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        using (SqlDataAdapter sda = new SqlDataAdapter(comm))
                        {
                            sw.Stop();
                            try
                            {
                                if (sw.ElapsedMilliseconds > 5000)
                                {
                                    string parmsStr = "";
                                    foreach (var item in parms)
                                    {
                                        parmsStr += $"{item.ParameterName}={item.Value}";
                                    }
                                    Utils.LogFile("/Log/timeOut", $"/{DateTime.Now.ToString("yyyy-MM-dd")}.txt", $"执行存储时间过长,执行时间为:{sw.ElapsedMilliseconds}毫秒,存储过程名为:{cmdText},参数:{parmsStr}");
                                    //LogHelper.WriteLog($"执行存储时间过长,执行时间为:{sw.ElapsedMilliseconds}毫秒,存储过程名为:{cmdText}", new Exception("执行存储时间过长"));

                                }
                            }
                            catch
                            {
                            }
                            string[] tables = tableNames.Split('|');
                            string mapTableName = "Table";
                            for (int index = 0; index < tables.Length; index++)
                            {
                                if (tables[index] != null && tables[index].Length >= 0)
                                {
                                    sda.TableMappings.Add(mapTableName, tables[index]);
                                    mapTableName = "Table" + (index + 1).ToString();
                                }
                            }
                            sda.Fill(ds);
                            comm.Parameters.Clear();
                            return ds;
                        }
                    }
                    catch
                    {
                        string parmsStr = "";
                        foreach (var item in parms)
                        {
                            parmsStr += $"{item.ParameterName}={item.Value},";
                        }
                        // LogHelper.WriteLog($"执行存储过程出现异常,存储过程名为:{cmdText},参数param:{parmsStr}");
                        SerilogServer.WriteLog("dbconStr111", new string[] { listconnectionInfoEntity[0].Connection });
                        conn.Close();
                        throw new Exception("执行异常");
                    }
                }
            }
        }
       
    }

    /// <summary>
    /// 
    /// </summary>
    public static class YLF_ConfigHelper
    {
        // public static IConfiguration _configuration { get; set; }

        public static DBOptionsInFo[] listConfigEntity { get; set; }
    }



    public class DBOptionsInFo
    {
        public string ConnId { get; set; }
        public int DBType { get; set; }
        public bool Enabled { get; set; }
        public int HitRate { get; set; }
        public string Connection { get; set; }


        //"DBS": [

        //{
        //  "ConnId": "MYSQL1",
        //  "DBType": 1,
        //  "Enabled": true,
        //  "HitRate": 20,
        //  "Connection": "server=192.168.1.7\\ms2012;uid=sa;pwd=Promotech1;database=ccp;"
        //  //"Connection": "server=q39.cloudcubic.net;uid=sa;pwd=cloudcubicptdsa91kd219AD9D2K2D;database=CloudCubicPlatform;"
        //}

    }
}
    public class Startup
    {

        private IServiceCollection _services;

        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            Env = env;
            // YLF_ConfigHelper._configuration = configuration;
            YLF_ConfigHelper.listConfigEntity = Configuration.GetSection("DBS").Get<DBOptionsInFo[]>();
        }
    }

 

标签:return,string,读写,分离,new,using,Dapper,public,listconnectionInfoEntity
From: https://www.cnblogs.com/Fengge518/p/17498765.html

相关文章

  • mysql proxy实现读写分离
    Mysql-proxy实现读写分离目录Mysql-proxy实现读写分离环境说明Mysql-proxy简介部署mysql-proxy服务读写分离测试总结环境说明Mysql-proxy简介mysql-proxy是官方提供的mysql中间件产品可以实现负载平衡,读写分离,failover等MySQLProxy就是这么一个中间层代理,简单的说,MySQLPro......
  • mycat分库分表和读写分离
    1.mycat分库分表和读写分离目录1.mycat分库分表和读写分离1.1.分库分表实现1.1.1.Mycat安装与配置详解1.1.1.1.下载地址1.1.1.2.解压安装包1.1.2.修改mycat内存配置1.1.3.配置实例1.1.4.环境准备1.1.4.1.分库分表规则1.1.4.2.创建数据库和表结构1.1.4.3.配置conf文件......
  • Jenkins部署前后端不分离springboot项目
    背景写这篇博客的时候我还是大学生,学校期末课程设计时要求使用Jenkins部署项目,所以使用windows,但是企业中都是使用linux,往往还会搭建一个gitlab。下面我介绍的是在window环境下使用jenkins部署项目,这阵子搞这个期末作业时感觉收获还是挺大的,专门记录下。持续集成(CI)持续集成......
  • 多路Qt串口通信源码C++语言接口自定义协议帧Qt读写配置文件ini出售: 可变长定长通信接
    多路Qt串口通信源码C++语言接口自定义协议帧Qt读写配置文件ini出售:可变长定长通信接口协议实现Qt多路串口发送接收SerialProtocol.rar工控自定义报文可用于嵌入式,单片机,ARM,DSP等常见的串口通信中,出售在应用实践中编写总结的源代码,实现自定义的串口通信协议,包括报文头部、长度......
  • HDFS数据读写过程
    读数据的全过程写数据的全过程:......
  • labview操作access和sql server数据库很实用的例子,含有创建表格,读写数据,按时间段读取,
    labview操作access和sqlserver数据库很实用的例子,含有创建表格,读写数据,按时间段读取,读取表格名称,还有部分sql指令操作等提供数据库软件,提供远程安装等ID:96128597927697257......
  • 分离式液位传感器代替浮球传感器的优势
    分离式液位传感器是一种新型的液位检测设备,它可以代替传统的浮球传感器。相比于浮球传感器,分离式液位传感器具有以下优势:精度高:分离式液位传感器采用先进的电容式检测技术,可以实现高精度的液位检测,避免了浮球传感器因受到液体波动等因素而导致的误差。可靠性强:分离式液位传感器采用......
  • Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离
    Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离 分类于 实战例子本文ShardingJDBC相关知识主要参考自ShardingJDBC官方文档,更多的用法建议到官网文档查看。前言传统的业务系统都是将数据集中存储至单一数据节点的解决方案,如今随着互联网数据......
  • Kafka的文件顺序读写
    背景说明Kafka使用起来很方便,而且磁盘写入性能非常好,那么它是如何实现的呢。在Kafka的文档说明中,有这样一段:大致意思是磁盘的读写性能并不弱,现代操作系统都会对磁盘的操作进行预读/缓存,合理复用操作系统的磁盘IO特性,可以提高Kafka的日志磁盘写入性能。数据写入以Kafka生产者......
  • Welcome To Learn Dapper
    WelcomeToLearnDapperThissiteisfordeveloperswhowanttolearnhowtouseDapper-ThemicroORMcreatedbythepeoplebehind StackOverflow.WhatisDapper? Dapperisanopen-sourceobject-relationalmapping(ORM)libraryfor.NETand.NETCore......