C#简单构架之EF进行读写分离+多数据库Mysql/SqlServer
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的更多相关文章
- C#简单构架之EF进行读写分离+多数据库(Mysql/SqlService)
最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构 表现层view 主要提供Web.WebApi等表现层的解决方案 公共层public 主要提供项目公共类库,数据 ...
- redis作为mysql的缓存服务器(读写分离,通过mysql触发器实现数据同步)
一.redis简介Redis是一个key-value存储系统.和Memcached类似,为了保证效率,数据都是缓存在内存中.区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录 ...
- SQL Server、MySQL主从搭建,EF Core读写分离代码实现
一.SQL Server的主从复制搭建 1.1.SQL Server主从复制结构图 SQL Server的主从通过发布订阅来实现 1.2.基于SQL Server2016实现主从 新建一个主库&quo ...
- windows NLB实现MSSQL读写分离--从数据库集群读负载均衡
主从模式,几乎大部分出名的数据库都支持的一种集群模式. 当Web站点的访问量上去之后,很多站点,选择读写分离,减轻主数据库的的压力.当然,一主多从也可以作用多个功能,比如备份.这里主要演示如何实现从数 ...
- Mysql读写分离——主从数据库+Atlas
mysql集群 最近在参加项目开发微信小程序后台,由于用户数量巨大,且后台程序并不是很完美,所以对用户的体验很是不友好(简单说就是很卡).赶巧最近正在翻阅<大型网站系统与Java中间件实践> ...
- MysqL读写分离的实现-Mysql proxy中间件的使用
为什么要架设读写分离,这里不做多余的说明,想了解具体原理,请百度或者参考其他帖子.在这里只做大概的配置说明,测试中使用三台服务器 192.168.136.142 主服务器 192.168.136. ...
- Mysql读写分离方案-MySQL Proxy环境部署记录
Mysql的读写分离可以使用MySQL Proxy和Amoeba实现,其实也可以使用MySQL-MMM实现读写分离的自动切换.MySQL Proxy有一项强大功能是实现"读写分离" ...
- 用mycat做读写分离:基于 MySQL主从复制
版权声明:本文为博主原创文章,未经博主允许不得转载. mycat是最近很火的一款国人发明的分布式数据库中间件,它是基于阿里的cobar的基础上进行开发的 搭建之前我们先要配置MySQL的主从复制,这个 ...
- .netcore实现一个读写分离的数据库访问中间件
在实际业务系统中,当单个数据库不能承载负载压力的时候,一般我们采用数据库读写分离的方式来分担数据库负载.主库承担写以及事务操作,从库承担读操作. 为了支持多种数据库我们先定义一个数据类型字典.key为 ...
随机推荐
- Zabbix监控多个JVM进程
一.场景说明: 我们这边的环境用的是微服务,每个程序都是有单独的进程及单独的端口号,但用jps查询出来的结果有些还会有重名的情况,所以某些脚本不太适用本场景: 二.需求说明: 需使用Zabbix- ...
- Linux Tomcat安装及端口配置
1. JDK安装配置 待写 2. Tomcat安装配置 1,下载Tomcat链接,到启动测试. 将文件apache-tomcat-8.5.50.tar.gz移动到/usr/tomcat/下,并解压 ...
- java 深copy
public static<T> T deepClone(T src) throws IOException, ClassNotFoundException { Object obj = ...
- 《浅谈我眼中的express、koa和koa2》好文留存+笔记
原文 :三英战豪强,思绪走四方.浅谈我眼中的express.koa和koa2 一.回调大坑怎么解决呢? 1.es5可以利用一下第三方库,例如 async 库, 2.或者单纯使用 connect中间件 ...
- 【oracle】截取字符串
select id,name,substr(dept,1,2) from test; 提取字段dept前两位 substr(string,start,length)
- Python面向对象 | 双下方法
定义:双下方法是特殊方法,他是解释器提供的.由双下划线+方法名+双下划线 .它具有特殊意义的方法,双下方法主要是python源码程序员使用的,我们在开发中尽量不要使用双下方法,但是深入研究双下方法,更 ...
- Flask常用路由参数
Flask中的路由参数: @app.route(‘/’, endpoint=’xx’ , methods=[‘GET’,...]) >endpoint后的名字,用来反向生成url的.后面的名字随 ...
- 箭头函数可不用return直接将表达式作为函数返回值
箭头函数如果函数体只有一个表达式,那么表达式将作为函数的返回值,这种写法无须加上return关键字, 看下面两个函数定义 var testAf = () => '111'; var testAf ...
- Apollo配置中心--安装使用-docker
官网:https://github.com/ctripcorp/apollo Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够实时推 ...
- MongoDB查询和sql查询的总结
查询所有表或集合 sql show tables mongodb db.getCollectionNames() 删除集合或表 sql drop table 表名 mongodb ...