NetCore3.1 使用 mongoDb 存储日志,提升查询效率
十年河东,十年河西,莫欺少年穷
学无止境,精益求精
工欲善其事必先利其器,要想使用mongodb,就必须先安装MongoDb服务,关于MongoDb的安装网上有很多教程,我使用的是MongoDb 4.2.1 ,据说4.2版本是最稳定的版本。
关于安装,请参考:https://zhuanlan.zhihu.com/p/136763521 或者自行百度。百度是的时候,记得加上版本4.2哦。
安装配置过程中,.在浏览器中输入网址:http://localhost:27017/ 。如果服务启动成功会看到以下一段话:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
这样就说明你的MongoDB安装配置成功了。关于mongoDb的可视化工具,大家可选择:Robomongo,可自行百度下载 :CSDN下载:https://download.csdn.net/detail/u012238360/12328517。
有了MongoDB服务端以后,我们就可以通过CMD命令来创建数据库,数据表,插入数据,查询数据了。
关于MongoDb的简单使用,
根据微软教程,我整理的相关命令如下:
mongod --dbpath D:\MongoData\data\db --新开启 mongo --转换到表 use LogstoreDb --创建表 db.createCollection('LogsForDg') --插入 db.LogsForDg.insertMany([{'methodNo':'cloud-180','data':'{}','CreateTime':'2020-02-02'}]) --查询 db.LogsForDg.find({}).pretty() --VS2019工具 --安装包 Install-Package MongoDB.Driver -Version 2.11.0 --创建实体
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class LogsForDgModel { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("methodNo")] public string methodNo { get; set; } public string data { get; set; } public string CreateTime { get; set; } } public class LogstoreDatabaseSettings : ILogstoreDatabaseSettings { public string LogsCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } } public interface ILogstoreDatabaseSettings { public string LogsCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } }
配置文件如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "WuAnDBContext": ";User ID=sa;" }, "LogstoreDatabaseSettings": { "LogsCollectionName": "LogsForDg", "ConnectionString": "mongodb://localhost:27017", "DatabaseName": "LogstoreDb" } }
MongoDb的操作类如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using IotDtos.MongodbDtos; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IotApi.Helper.mongo { public class LogService { private readonly IMongoCollection<LogsForDgModel> _books; public LogService(ILogstoreDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _books = database.GetCollection<LogsForDgModel>(settings.LogsCollectionName); } public List<LogsForDgModel> Get() => _books.Find(book => true).ToList(); public LogsForDgModel Get(string id) => _books.Find<LogsForDgModel>(book => book.Id == id).FirstOrDefault(); public LogsForDgModel Create(LogsForDgModel book) { _books.InsertOne(book); return book; } public void Update(string id, LogsForDgModel bookIn) => _books.ReplaceOne(book => book.Id == id, bookIn); public void Remove(LogsForDgModel bookIn) => _books.DeleteOne(book => book.Id == bookIn.Id); public void Remove(string id) => _books.DeleteOne(book => book.Id == id); } }
启动类如下:
启动类完整代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //MongoDb 选项模式 services.Configure<LogstoreDatabaseSettings>( Configuration.GetSection(nameof(LogstoreDatabaseSettings))); services.AddSingleton<ILogstoreDatabaseSettings>(sp => sp.GetRequiredService<IOptions<LogstoreDatabaseSettings>>().Value); #region 注册JWT services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(TokenManagement.Secret)), ValidIssuer = TokenManagement.Issuer, ValidAudience = TokenManagement.Audience, ValidateIssuer = false, ValidateAudience = false }; }); #endregion #region 注册Swagger服务 // 注册Swagger服务 services.AddSwaggerGen(c => { // 添加文档信息 c.SwaggerDoc("v1", new OpenApiInfo { Title = "IOT相关接口", Version = "V1" }); //c.SwaggerDoc("demo", new OpenApiInfo { Title = "示例接口", Version = "demo" }); c.DocInclusionPredicate((docName, apiDesc) => apiDesc.GroupName == docName.ToUpper()); var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) var xmlPath = Path.Combine(basePath, "IotApi.xml"); c.IncludeXmlComments(xmlPath); #region Jwt //开启权限小锁 c.OperationFilter<AddResponseHeadersFilter>(); c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); //在header中添加token,传递到后台 c.OperationFilter<SecurityRequirementsOperationFilter>(); c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"", Name = "Authorization",//jwt默认的参数名称 In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); #endregion }); #endregion #region 注册SQLSERVER services.AddDbContext<WuAnDBTestContext>(options => options.UseSqlServer(Configuration.GetConnectionString("WuAnDBContext"))); #endregion #region 注册自定义服务 services.AddScoped<IIotMns, IotMnsService>(); //MongoDb 日志服务类 services.AddSingleton<LogService>(); //MongoDb 日志服务类 #endregion }
结合微软教程 及我的代码,即可迅速完成MongoDB的学习。
@博客园好牛逼