http://www.php361.com/index.php?c=index&a=view&id=3857
不建议用,太重的框架EF,仅仅参考一下别人的思路就好。 [导读]最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构表现层view 主要提供Web、WebApi等表现层的解决方案公共层public 主要提供项目公共类库,数据缓存基础方法等实体层model 主要提供数据
最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构 表现层view 主要提供Web、WebApi等表现层的解决方案 公共层public 主要提供项目公共类库,数据缓存基础方法等 实体层model 主要提供数据库映射模型,还有就是DDD领域操作模型 数据层Db 主要封装EF操作基础类 数据服务层Service 主要提供数据库操作服务、缓存操作服务 数据接口服务层inface 主要提供数据库操作服务接口、缓存操作服务接口 .首先是多数据库的支持,目前就支持mysql/sqlservice,如果需要添加更多的数据库支持,只需要再数据库操作类型上面添加即可 [源码] view plain
/// <summary>
/// 数据库类型
/// </summary>
public enum DbContextType : byte
{
SqlService = ,
MySql =
} 分别对mysql/sqlservice的上下文操作进行封装 [源码] view plain
/// <summary>
/// MySql操作类
/// </summary>
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MySqlContext : DbContext
{
public DbSet<Test> TestEntities { get; set; }
/// <summary>
/// 配置默认的字符串链接
/// </summary>
public MySqlContext() : base("DefaultConnection") {
}
/// <summary>
/// 自定义数据库链接
/// </summary>
/// <param name="connenction"></param>
public MySqlContext(string connenction) : base(connenction) { }
/// <summary>
/// 实体对应规则的映射配置
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
} [源码] view plain
/// <summary>
/// Sql数据库操作类
/// </summary>
public class SqlServiceContext : DbContext
{
/// <summary>
/// 配置默认的字符串链接
/// </summary>
public SqlServiceContext() {
}
/// <summary>
/// 自定义数据库链接
/// </summary>
/// <param name="connenction"></param>
public SqlServiceContext(string connenction) : base(connenction) {
}
/// <summary>
/// 实体对应规则的映射配置
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
} 在view调用时候,进行ef上下文初始化只需要设置类型 [源码] view plain
/// <summary>
/// 数据库策略初始化类
/// </summary>
public static class DBInitializer
{
public static DbContextType DbContextType { get; set; }
/// <summary>
/// 数据库初始化策略配置
/// </summary>`
public static void Initialize(DbContextType ContextType)
{
string IsUsedWR = System.Configuration.ConfigurationManager.AppSettings["IsUsedWR"];
DbContextType = ContextType;
///获得数据库最后一个版本
// Database.SetInitializer<DBContextHelper>(new MigrateDatabaseToLatestVersion<DBContextHelper, DBConfiguration>());
if (ContextType == DbContextType.SqlService)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<WriteSqlServiceContext, WriteSqlServiceDBConfiguration>());
if (IsUsedWR == "") {
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ReadSqlServiceContext, ReadSqlSqlServiceDBConfiguration>());
}
else
{
Database.SetInitializer<ReadSqlServiceContext>(null);
}
}
else
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<WriteMySqlContext, WriteMySqlDBConfiguration>());
if (IsUsedWR == "")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ReadMySqlContext, ReadMySqlDBConfiguration>());
}
else
{
Database.SetInitializer<ReadMySqlContext>(null);
}
//Database.SetInitializer<WriteMySqlContext>(null);
// Database.SetInitializer<ReadMySqlContext>(null);
}
// Database.SetInitializer<DBContextHelper>(null);
///删除原来数据库 重新创建数据库
//Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ContextHelper>());
// Database.SetInitializer<ContextHelper>(new DropCreateDatabaseIfModelChanges<ContextHelper>());
}
} [源码] view plain
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); //Autofac
//ContainerBuilder builder = new ContainerBuilder();
//builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
//IContainer container = builder.Build();
//DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Autofac初始化过程
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());//注册mvc容器的实现
var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.Contains("Service")).AsImplementedInterfaces();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
//初始化数据库
DBInitializer.Initialize(DbContextType.MySql);
}
} 通过上面多数据库的支持已经完成,下面进行读写分离,分别进行继承上述上下文操作 [源码] view plain
/// <summary>
/// 读
/// </summary>
public class WriteSqlServiceContext : SqlServiceContext
{
public WriteSqlServiceContext() : base("") { }
}
/// <summary>
/// 写
/// </summary>
public class ReadSqlServiceContext : SqlServiceContext
{
public ReadSqlServiceContext() : base("") { }
} 通过工厂类进行初始化 [源码] view plain
/// <summary>
/// 上下文工厂类
/// </summary>
public static class Contextfactory
{
/// <summary>
/// 获取上下文
/// </summary>
/// <returns></returns>
public static DbContext GetContext(DbOpertionType OpertionType)
{
DbContextType ContextType = DBInitializer.DbContextType;
if (ContextType == DbContextType.MySql)
{
if (OpertionType == DbOpertionType.Read)
return new ReadMySqlContext();
else
return new WriteMySqlContext();
}
else
{
if (OpertionType == DbOpertionType.Read)
return new ReadSqlServiceContext();
else
return new WriteSqlServiceContext();
}
}
/// <summary>
/// 获取上下文操作
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="OpertionType"></param>
/// <returns></returns>
public static TEntity CallContext<TEntity>(DbOpertionType OpertionType) where TEntity: DbContext
{
var DbContext = GetContext(OpertionType);
return (TEntity)DbContext;
}
} 最后配置webcofig即可 [源码] view plain
<!--数据库配置(WriteMySqlConnection:读数据库,ReadMySqlConnection:写数据库 如果无需要进行 就配置IsUsedWR,2个链接都写写入库)-->
<connectionStrings>
<add name="WriteMySqlConnection" connectionString="data source=*; Initial Catalog=YK_Test_WriteDB ; uid=root; pwd=yk12345;Charset=utf8" providerName="MySql.Data.MySqlClient" />
<add name="ReadMySqlConnection" connectionString="data source=*; Initial Catalog=YK_Test_ReadDB ; uid=root; pwd=yk12345;Charset=utf8" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<!--数据库读取分离配置-->
<!--是否开启读写分离 :开启 :不开启-->
<add key="IsUsedWR" value=""/> 最后进行测试 [源码] view plain
public class TestController : Controller
{
private ITestService _TestServiceDb { get; set; } public TestController(ITestService TestServiceDb) {
_TestServiceDb = TestServiceDb;
}
// GET: Test
public ActionResult Index()
{
var result = _TestServiceDb.AddEntity(new Test() { ID=Guid.NewGuid(), Age=, CreateTime=DateTime.Now, Name="Test" });
var NewResult = _TestServiceDb.GetEntityByID(result.ID);
return View();
}
} 搞定,可能在代码上有点累赘,但是总算是可行的。

C#简单构架之EF进行读写分离+多数据库Mysql/SqlServer的更多相关文章

  1. C#简单构架之EF进行读写分离+多数据库(Mysql/SqlService)

    最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构 表现层view 主要提供Web.WebApi等表现层的解决方案 公共层public 主要提供项目公共类库,数据 ...

  2. redis作为mysql的缓存服务器(读写分离,通过mysql触发器实现数据同步)

    一.redis简介Redis是一个key-value存储系统.和Memcached类似,为了保证效率,数据都是缓存在内存中.区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录 ...

  3. SQL Server、MySQL主从搭建,EF Core读写分离代码实现

    一.SQL Server的主从复制搭建 1.1.SQL Server主从复制结构图 SQL Server的主从通过发布订阅来实现 1.2.基于SQL Server2016实现主从 新建一个主库&quo ...

  4. windows NLB实现MSSQL读写分离--从数据库集群读负载均衡

    主从模式,几乎大部分出名的数据库都支持的一种集群模式. 当Web站点的访问量上去之后,很多站点,选择读写分离,减轻主数据库的的压力.当然,一主多从也可以作用多个功能,比如备份.这里主要演示如何实现从数 ...

  5. Mysql读写分离——主从数据库+Atlas

    mysql集群 最近在参加项目开发微信小程序后台,由于用户数量巨大,且后台程序并不是很完美,所以对用户的体验很是不友好(简单说就是很卡).赶巧最近正在翻阅<大型网站系统与Java中间件实践> ...

  6. MysqL读写分离的实现-Mysql proxy中间件的使用

    为什么要架设读写分离,这里不做多余的说明,想了解具体原理,请百度或者参考其他帖子.在这里只做大概的配置说明,测试中使用三台服务器 192.168.136.142   主服务器 192.168.136. ...

  7. Mysql读写分离方案-MySQL Proxy环境部署记录

    Mysql的读写分离可以使用MySQL Proxy和Amoeba实现,其实也可以使用MySQL-MMM实现读写分离的自动切换.MySQL Proxy有一项强大功能是实现"读写分离" ...

  8. 用mycat做读写分离:基于 MySQL主从复制

    版权声明:本文为博主原创文章,未经博主允许不得转载. mycat是最近很火的一款国人发明的分布式数据库中间件,它是基于阿里的cobar的基础上进行开发的 搭建之前我们先要配置MySQL的主从复制,这个 ...

  9. .netcore实现一个读写分离的数据库访问中间件

    在实际业务系统中,当单个数据库不能承载负载压力的时候,一般我们采用数据库读写分离的方式来分担数据库负载.主库承担写以及事务操作,从库承担读操作. 为了支持多种数据库我们先定义一个数据类型字典.key为 ...

随机推荐

  1. Oracle PLSQL游标、游标变量的使用

    参考文章:https://www.cnblogs.com/huyong/archive/2011/05/04/2036377.html 在 PL/SQL 程序中,对于处理多行记录的事务经常使用游标来实 ...

  2. bat 获取管理员权限,判断系统位数,获取当前文件所在目录,regsvr32注册DLL、OCX

    1.获取管理员权限 @echo off if exist "%SystemRoot%\SysWOW64" path %path%;%windir%\SysNative;%Syste ...

  3. 用 Splashtop Wired XDisplay HD 让 ipad做电脑扩展屏幕__亲测有效

    参考: [1]https://blog.csdn.net/Tang_Chuanlin/article/details/86433152

  4. 前端(1)HTML介绍

    1.1 HTML介绍 1.1Web服务本质 服务端 import socket server = socket.socket() server.bind(("127.0.0.1", ...

  5. Django-Model操作数据库

    查询 models.UserInfo.objects.all() models.UserInfo.objects.all().values('user') #只取user列 models.UserIn ...

  6. Linux—— 记录所有登陆用户的历史操作记录

    前言 记录相应的人登陆服务器后,做了那些操作,这个不是我自己写的,因为时间久了,原作者连接也无法提供,尴尬. 步骤 history是查询当前连接所操作的命令,通过编写以下内容添加至/etc/profi ...

  7. eclipse---之Console窗口命令行输入

    在 Eclipse 中使用 Windows 命令行. 第一步:设置一个新的外部配置工具  在 Eclipse 中,选择 “Run -> External Tools -> External ...

  8. html--前端css样式初识

    一.CSS概述 css是英文Cascading Style Sheets的缩写,称为层叠样式表,用于对页面进行美化,CSS的可以使页面更加的美观.基本上所有的html页面都或多或少的使用css. CS ...

  9. python发邮件报错SMTP AUTH extension not supported by server."

    在login(username,password)之前添加 smtp.ehlo() smtp.starttls() d ={'smtp_server': '','smtp_email': '','sm ...

  10. 【meet in the mid】【qbxt2019csp刷题班day1C】birthday

    Description 给定一个长度为 \(n\) 序列,值域为 \([1, v]\),每次选择一段区间,要求在这个区间上选择一些元素加入到两个集合中,每个元素要么不选要么只能加入一个集合,要求两个集 ...