Commit 841a13f9 by 赵剑炜

增加业务

parent ea7f26b5
[*.cs]
# CS8600: 将 null 字面量或可能为 null 的值转换为非 null 类型。
dotnet_diagnostic.CS8600.severity = none
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.11",
"commands": [
"dotnet-ef"
]
}
}
}
\ No newline at end of file
...@@ -11,6 +11,10 @@ ...@@ -11,6 +11,10 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="..\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="7.1.0" /> <PackageReference Include="Autofac" Version="7.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" /> <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
...@@ -27,4 +31,10 @@ ...@@ -27,4 +31,10 @@
<ProjectReference Include="..\Services\Services.csproj" /> <ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="Properties\launchSettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>
using APIs.Common;
using APIs.Dto;
using APIs.Req;
using Autofac.Core;
using AutoMapper;
using Common.Utility.RabbitMQ;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Models.SqlModel;
using Models.ToolsModel;
using Newtonsoft.Json;
using Services;
using Services.Interface;
using static Microsoft.AspNetCore.Razor.Language.TagHelperMetadata;
namespace APIs.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class BaseInfoController : ControllerBase
{
public IMapper Mapper { get; }
private readonly IPoliceService _policeService;
private readonly IEquipmentTypeService _equipmentTypeService;
private readonly IEquipmentSizeService _equipmentSizeService;
private readonly ICarService _carService;
public BaseInfoController(IMapper mapper,IPoliceService policeService, IEquipmentTypeService equipmentTypeService,
IEquipmentSizeService equipmentSizeService,ICarService carService)
{
_carService = carService;
_equipmentSizeService = equipmentSizeService;
_equipmentTypeService = equipmentTypeService;
_policeService = policeService;
Mapper = mapper;
}
/// <summary>
/// 查询人员信息
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
public virtual async Task<ApiResult> GetAllPersonnel([FromBody] CommonReq req)
{
try
{
DateTime reqTime = DateTime.MinValue;
if (!string.IsNullOrEmpty(req.updateTime))
{
reqTime = DateTime.Parse(req.updateTime);
}
var police = await _policeService.Query(p=>p.updateTime>= reqTime);
var src = new ApiResult
{
code = ResultCode.OPERATE_SUCCESS.Code,
msg = ResultCode.OPERATE_SUCCESS.Msg,
data = police
};
return src;
}
catch (Exception ex)
{
var error = new ApiResult
{
code = ResultCode.OPERATE_FAILED.Code,
msg = ex.Message,
};
return error;
}
}
/// <summary>
/// 查询装备类型信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<string> GetEquipmentType([FromBody] CommonReq req)
{
try
{
DateTime reqTime = DateTime.MinValue;
if (!string.IsNullOrEmpty(req.updateTime))
{
reqTime = DateTime.Parse(req.updateTime);
}
var typeQuery = await _equipmentSizeService.Query(p => p.updateTime >= reqTime);
List<EquipmentTypeDto> typeDto = new List<EquipmentTypeDto>() ;
Mapper.Map(typeQuery, typeDto);
var src = new ApiResult
{
code = ResultCode.OPERATE_SUCCESS.Code,
msg = ResultCode.OPERATE_SUCCESS.Msg,
data= typeDto
};
return JsonConvert.SerializeObject(src);
}
catch (Exception ex)
{
var error = new ApiResult
{
code = ResultCode.OPERATE_FAILED.Code,
msg = ex.Message,
};
return JsonConvert.SerializeObject(error);
}
}
/// <summary>
/// 查询装备号型信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<string> GetEquipmentSize([FromBody] CommonReq req)
{
try
{
DateTime reqTime= DateTime.MinValue;
if (!string.IsNullOrEmpty(req.updateTime))
{
reqTime = DateTime.Parse(req.updateTime);
}
var sizeQuery = await _equipmentSizeService.Query(p => p.updateTime >= reqTime);
List<EquipmentSizeDto> sizeDto = new List<EquipmentSizeDto>();
Mapper.Map(sizeQuery, sizeDto);
var src = new ApiResult
{
code = ResultCode.OPERATE_SUCCESS.Code,
msg = ResultCode.OPERATE_SUCCESS.Msg,
data = sizeDto
};
return JsonConvert.SerializeObject(src);
}
catch (Exception ex)
{
var error = new ApiResult
{
code = ResultCode.OPERATE_FAILED.Code,
msg = ex.Message,
};
return JsonConvert.SerializeObject(error);
}
}
/// <summary>
/// 查询车辆信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<string> GetCar([FromBody] CommonReq req)
{
try
{
DateTime reqTime = DateTime.MinValue;
if (!string.IsNullOrEmpty(req.updateTime))
{
reqTime = DateTime.Parse(req.updateTime);
}
var carQuery = await _carService.Query(p => p.updateTime >= reqTime);
var src = new ApiResult
{
code = ResultCode.OPERATE_SUCCESS.Code,
msg = ResultCode.OPERATE_SUCCESS.Msg,
data = carQuery
};
return JsonConvert.SerializeObject(src);
}
catch (Exception ex)
{
var error = new ApiResult
{
code = ResultCode.OPERATE_FAILED.Code,
msg = ex.Message,
};
return JsonConvert.SerializeObject(error);
}
}
/// <summary>
/// 查询当前时间信息
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<string> GetTime()
{
DateTime reqTime = DateTime.Now;
return JsonConvert.SerializeObject(reqTime.ToString("yyyy-MM-dd"));
}
/// <summary>
/// 发送消息队列测试
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<string> SendMQ([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] RecordsReq req)
{
await RabbitMQContext.SendMessageAsynce(JsonConvert.SerializeObject(req));
var src = new ApiResult
{
code = ResultCode.OPERATE_SUCCESS.Code,
msg = ResultCode.OPERATE_SUCCESS.Msg
};
return JsonConvert.SerializeObject(src);
}
}
}
...@@ -6,7 +6,7 @@ using Services.Interface; ...@@ -6,7 +6,7 @@ using Services.Interface;
namespace APIs.Controllers namespace APIs.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class MapperController : ControllerBase public class MapperController : ControllerBase
{ {
...@@ -21,17 +21,17 @@ namespace APIs.Controllers ...@@ -21,17 +21,17 @@ namespace APIs.Controllers
} }
[HttpPost] [HttpPost]
public UserDto Test(Users user) public EquipmentTypeDto Test(Users user)
{ {
var userDto = new UserDto(); var userDto = new EquipmentTypeDto();
Mapper.Map(user, userDto); Mapper.Map(user, userDto);
return userDto; return userDto;
} }
[HttpGet] [HttpGet]
public UserDto GetTest() public EquipmentTypeDto GetTest()
{ {
var userDto = new UserDto(); var userDto = new EquipmentTypeDto();
List<Users> aa= _tService.GetData(); List<Users> aa= _tService.GetData();
Mapper.Map(aa, userDto); Mapper.Map(aa, userDto);
return userDto; return userDto;
......
...@@ -3,7 +3,7 @@ using Microsoft.Extensions.Caching.Memory; ...@@ -3,7 +3,7 @@ using Microsoft.Extensions.Caching.Memory;
namespace APIs.Controllers namespace APIs.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class MemoryController : ControllerBase public class MemoryController : ControllerBase
{ {
......
...@@ -10,9 +10,9 @@ using Services.Interface; ...@@ -10,9 +10,9 @@ using Services.Interface;
namespace APIs.Controllers namespace APIs.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class UserController : Controller public class UserController : ControllerBase
{ {
public IMapper Mapper { get; } public IMapper Mapper { get; }
private readonly IPoliceService _policeService; private readonly IPoliceService _policeService;
...@@ -22,27 +22,27 @@ namespace APIs.Controllers ...@@ -22,27 +22,27 @@ namespace APIs.Controllers
Mapper = mapper; Mapper = mapper;
} }
[HttpGet] //[HttpGet]
public virtual async Task<HttpResponseMessage> GetAllPersonnel() //public virtual async Task<HttpResponseMessage> GetAllPersonnel()
{ //{
try // try
{ // {
//var userDto = new UserDto(); // //var userDto = new UserDto();
var police = await _policeService.Query(); // var police = await _policeService.Query();
return JsonManager.ReturnSuccessResponse(police); // return JsonManager.ReturnSuccessResponse(police);
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
ResultInfo info = new ResultInfo() // ResultInfo info = new ResultInfo()
{ // {
Msg = ex.Message, // Msg = ex.Message,
Code = "19999" // Code = "19999"
}; // };
return JsonManager.SimpleStatusResponse(info); // return JsonManager.SimpleStatusResponse(info);
} // }
} //}
......
namespace APIs.Dto
{
public class EquipmentSizeDto
{
public String id { get; set; }
public String name { get; set; }
public String code { get; set; }
public String typeId { get; set; }
public String typeName { get; set; }
public DateTime updateTime { get; set; }
public DateTime createTime { get; set; }
}
}
namespace APIs.Dto;
public class EquipmentTypeDto
{
public String id { get; set; }
public String name { get; set; }
public String code { get; set; }
public DateTime updateTime { get; set; }
public DateTime createTime { get; set; }
}
\ No newline at end of file
namespace APIs.Dto;
public class UserDto
{
public int Id { get; set; }
}
\ No newline at end of file
...@@ -7,7 +7,7 @@ public static class SqlsugarSetup ...@@ -7,7 +7,7 @@ public static class SqlsugarSetup
public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
string dbName = "MySQL") string dbName = "MySQL")
{ {
var a = configuration.GetConnectionString(dbName);
services.AddScoped<ISqlSugarClient>(o => services.AddScoped<ISqlSugarClient>(o =>
{ {
var listConfig = new List<ConnectionConfig>(); var listConfig = new List<ConnectionConfig>();
......
...@@ -8,6 +8,7 @@ public class MapperProfile : Profile ...@@ -8,6 +8,7 @@ public class MapperProfile : Profile
{ {
public MapperProfile() public MapperProfile()
{ {
CreateMap<User, UserDto>().ForMember(dest=>dest.Id,opt=>opt.MapFrom(src=>src.Id)); CreateMap<EquipmentType, EquipmentTypeDto>().ForMember(dest=>dest.id,opt=>opt.MapFrom(src=>src.id));
CreateMap<EquipmentSize, EquipmentSizeDto>().ForMember(dest =>dest.id,opt => opt.MapFrom(src => src.id));
} }
} }
\ No newline at end of file
...@@ -6,6 +6,7 @@ using System.Xml.Linq; ...@@ -6,6 +6,7 @@ using System.Xml.Linq;
using APIs; using APIs;
using APIs.Extensions; using APIs.Extensions;
using APIs.Profiles; using APIs.Profiles;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Common; using Common;
using FluentValidation.AspNetCore; using FluentValidation.AspNetCore;
...@@ -32,12 +33,15 @@ public class Program ...@@ -32,12 +33,15 @@ public class Program
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try try
{ {
logger.Debug("--------------init main--------------"); Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}]"+ "--------------init main--------------");
Console.WriteLine("ɹ");
CreateHostBuilder(args).Build().Run(); CreateHostBuilder(args).Build().Run();
} }
catch (Exception exception) catch (Exception exception)
{ {
logger.Error(exception, "--------------Stopped program because of exception--------------"); logger.Error(exception, "--------------Stopped program because of exception--------------");
Console.WriteLine(""+exception);
throw; throw;
} }
finally finally
...@@ -46,17 +50,30 @@ public class Program ...@@ -46,17 +50,30 @@ public class Program
} }
} }
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
public static IHostBuilder CreateHostBuilder(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.Build();
return Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) .UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder => .ConfigureWebHostDefaults(webBuilder =>
{ {
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();
webBuilder.UseUrls(configuration["Launch"]);
}) })
.ConfigureLogging(logging => .ConfigureLogging(logging =>
{ {
logging.ClearProviders(); logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace); logging.SetMinimumLevel(LogLevel.Trace);
}) })
.UseNLog(); .UseNLog();
}
} }
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>false</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net6.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<ProjectGuid>50472ac8-0769-43fd-9559-dfaf7c616b47</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>
\ No newline at end of file
{ 
"$schema": "https://json.schemastore.org/launchsettings.json",
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5133",
"sslPort": 5133
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": { "profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5133;http://localhost:5143;"
},
"APIs": { "APIs": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"applicationUrl": "http://localhost:5133",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} },
"applicationUrl": "http://localhost:5133;http://localhost:5143;"
} }
} }
} }
namespace APIs.Req
{
public class CommonReq
{
public String updateTime { get; set; }
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace APIs.Req
{
public class RecordsReq
{
public String id { get; set; }
public DateTime useTime { get; set; }
public String userName { get; set; }
public String type { get; set; }
public String equipments { get; set; }
[FromBody]
public List<EquipmentList> equipmentList { get; set; }
[FromBody]
public List<CarList> carList { get; set; }
//
}
public class EquipmentList
{
public String epc { get; set; }
public String equipmentName { get; set; }
public String equipmentSize { get; set; }
public String outInState { get; set; }
public String errorState { get; set; }
}
public class CarList
{
public String carId { get; set; }
public String outInState { get; set; }
public String errorState { get; set; }
}
}
...@@ -14,6 +14,9 @@ using APIs.Extensions; ...@@ -14,6 +14,9 @@ using APIs.Extensions;
using FluentValidation.AspNetCore; using FluentValidation.AspNetCore;
using Repositories.IRepository.IUnitOfWork; using Repositories.IRepository.IUnitOfWork;
using Repositories.Repository.UnitOfWork; using Repositories.Repository.UnitOfWork;
using Common.Utility.RabbitMQ;
using Common.Global;
using System.Xml.Linq;
namespace APIs namespace APIs
{ {
...@@ -47,12 +50,21 @@ namespace APIs ...@@ -47,12 +50,21 @@ namespace APIs
services.AddScoped<IPoliceService, PoliceService>(); services.AddScoped<IPoliceService, PoliceService>();
services.AddScoped<ICarService, CarService>(); services.AddScoped<ICarService, CarService>();
services.AddScoped<IEquipmentSizeService, EquipmentSizeService>(); services.AddScoped<IEquipmentSizeService, EquipmentSizeService>();
//services.AddScoped<IEquipmentTypeService, EquipmentTypeService>(); services.AddScoped<IEquipmentTypeService, EquipmentTypeService>();
services.AddScoped<IPoliceRepository, PoliceRepository>(); services.AddScoped<IPoliceRepository, PoliceRepository>();
services.AddScoped<ICarRepository, CarRepository>(); services.AddScoped<ICarRepository, CarRepository>();
services.AddScoped<IEquipmentSizeRepository, EquipmentSizeRepository>(); services.AddScoped<IEquipmentSizeRepository, EquipmentSizeRepository>();
services.AddScoped<IEquipmentTypeRepository, EquipmentTypeRepository>(); services.AddScoped<IEquipmentTypeRepository, EquipmentTypeRepository>();
#region 注册RabbitMQ消费者
services.AddHostedService<RabbitMQCustomContext>();
#endregion
#region 初始化全局配置信息
InitConfiguration(Configuration);
#endregion
services.AddFluentValidation(options => services.AddFluentValidation(options =>
{ {
options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()); options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
...@@ -76,7 +88,25 @@ namespace APIs ...@@ -76,7 +88,25 @@ namespace APIs
} }
#region 初始化全局静态配置
/// <summary>
/// 初始化全局静态配置
/// </summary>
private void InitConfiguration(IConfiguration configuration)
{
RabbitMQConfig rabbits = new RabbitMQConfig();
rabbits.Port = int.Parse(configuration.GetSection("RabbitMQConfig:Port").Value);
rabbits.QueueName = configuration.GetSection("RabbitMQConfig:QueueName").Value;
rabbits.HostName = configuration.GetSection("RabbitMQConfig:HostName").Value;
rabbits.ExchangeName = configuration.GetSection("RabbitMQConfig:ExchangeName").Value;
rabbits.UserName = configuration.GetSection("RabbitMQConfig:UserName").Value;
rabbits.Password = configuration.GetSection("RabbitMQConfig:Password").Value;
AdminGlobalContext.RabbitMQConfig = rabbits;
}
#endregion
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
......
{ {
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Debug",
"Microsoft.AspNetCore": "Warning" "Microsoft": "Information",
"Information": "Information"
} }
}, },
"Launch": "http://*:5233;http://*:5243",
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"MySQL": "server=192.168.3.128;port=3306;Database=xuzhou;Uid=junmp;Pwd=123456;" "MySQL": "server=192.168.3.128;port=3306;Database=xuzhou;Uid=junmp;Pwd=123456;"
//RabbitMQ配置
},
"RabbitMQConfig": {
//用户名
"UserName": "root",
//密码
"Password": "123456",
//ip地址,多个时以英文“,”分割
"HostName": "192.168.3.188",
//端口
"Port": 5672,
//虚拟队列名称
"QueueName": "cabinet",
//虚拟交换机名称
"ExchangeName": "uploadRecords"
},
"RabbitMQConfigCreate": {//生产者消息队列,后期可以建设多个队列名称
//用户名
"UserName": "root",
//密码
"Password": "123456",
//ip地址,多个时以英文“,”分割
"HostName": "192.168.3.188",
//端口
"Port": 5672,
//虚拟队列名称
"QueueName": "cabinet",
//虚拟交换机名称
"ExchangeName": "uploadRecords"
} }
//"Jwt": {
// "Secret": "f30386a4fc41d3c1a75cd7f3de54c48c",
// "Issuer": "Atlantis",
// "Audience": "Atlantis"
//}
} }
...@@ -7,8 +7,10 @@ ...@@ -7,8 +7,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.8.0" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.8.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RabbitMQ.Client" Version="6.5.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
</ItemGroup> </ItemGroup>
......
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Global
{
/// <summary>
/// 全局配置
/// </summary>
public class AdminGlobalContext
{
/// <summary>
/// RabbitMQ配置
/// </summary>
public static RabbitMQConfig RabbitMQConfig { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Global
{
/// <summary>
/// RabbitMQ配置
/// </summary>
public class RabbitMQConfig
{
/// <summary>
/// 用户名
/// </summary>
public String? UserName { get; set; }
/// <summary>
/// 密码
/// </summary>
public String? Password { get; set; }
/// <summary>
/// ip地址,多个时以英文“,”分割
/// </summary>
public String? HostName { get; set; }
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 虚拟队列名称
/// </summary>
public String? QueueName { get; set; }
/// <summary>
/// 虚拟交换机名称
/// </summary>
public String? ExchangeName { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Utility.Model
{
public class RecordsReq
{
public String id { get; set; }
public DateTime useTime { get; set; }
public String userName { get; set; }
public String type { get; set; }
public String equipments { get; set; }
public List<EquipmentList> equipmentList { get; set; }
public List<CarList> carList { get; set; }
//
}
public class EquipmentList
{
public String epc { get; set; }
public String equipmentName { get; set; }
public String equipmentSize { get; set; }
public String outInState { get; set; }
public String errorState { get; set; }
}
public class CarList
{
public String carId { get; set; }
public String outInState { get; set; }
public String errorState { get; set; }
}
}
using Common.Global;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Utility.RabbitMQ
{
/// <summary>
/// RabbitMQ工具类
/// </summary>
public class RabbitMQContext
{
/// <summary>
/// 私有化构造函数
/// 用于单例模式
/// </summary>
private RabbitMQContext() { }
/// <summary>
/// Lazy对象
/// </summary>
private static readonly Lazy<IConnection> LazyConnection = new Lazy<IConnection>(() =>
{
ConnectionFactory factory = null;
IConnection connection = null;
#region 初始工厂类
if (AdminGlobalContext.RabbitMQConfig.HostName.Contains(","))
{
//创建连接对象工厂
factory = new ConnectionFactory()
{
UserName = AdminGlobalContext.RabbitMQConfig.UserName,
Password = AdminGlobalContext.RabbitMQConfig.Password,
AutomaticRecoveryEnabled = true,//如果connection挂掉是否重新连接
TopologyRecoveryEnabled = true//连接恢复后,连接的交换机,队列等是否一同恢复
};
//创建连接对象
connection = factory.CreateConnection(AdminGlobalContext.RabbitMQConfig.HostName.Split(','));
}
else
{
//创建连接对象工厂
factory = new ConnectionFactory()
{
UserName = AdminGlobalContext.RabbitMQConfig.UserName,
Password = AdminGlobalContext.RabbitMQConfig.Password,
HostName = AdminGlobalContext.RabbitMQConfig.HostName,
Port = AdminGlobalContext.RabbitMQConfig.Port,
RequestedHeartbeat = TimeSpan.FromSeconds(30), //心跳包
AutomaticRecoveryEnabled = true, //自动重连
TopologyRecoveryEnabled = true, //拓普重连
NetworkRecoveryInterval = TimeSpan.FromSeconds(10)
};
//创建连接对象
connection = factory.CreateConnection();
}
#endregion
return connection;
});
/// <summary>
/// 单例对象
/// </summary>
public static IConnection ConnectionInstance { get { return LazyConnection.Value; } }
/// <summary>
/// 是否已创建
/// </summary>
public static bool IsConnectionInstanceCreated { get { return LazyConnection.IsValueCreated; } }
/// <summary>
/// 发送消息
/// </summary>
/// <param name="message">消息体</param>
public static void SendMessage(string message)
{
IConnection connection = ConnectionInstance;
//定义通道
var channel = connection.CreateModel();
//如果只有生产者,则使用以下注释内容,作为单例使用
//定义交换机
//channel.ExchangeDeclare(AdminGlobalContext.RabbitMQConfig.ExchangeName, ExchangeType.Fanout, true, false);
////定义队列
//channel.QueueDeclare(AdminGlobalContext.RabbitMQConfig.QueueName, false, false, false, null);
////将队列绑定到交换机
//channel.QueueBind(AdminGlobalContext.RabbitMQConfig.QueueName, AdminGlobalContext.RabbitMQConfig.ExchangeName, "", null);
//发布消息
channel.BasicPublish(AdminGlobalContext.RabbitMQConfig.ExchangeName, "", null, Encoding.Default.GetBytes(message));
}
/// <summary>
/// 异步发送消息
/// </summary>
/// <param name="message">消息体</param>
/// <returns></returns>
public static async Task SendMessageAsynce(string message)
{
await Task.Run(() => SendMessage(message));
}
}
}
using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Common.Global;
using Newtonsoft.Json;
using Common.Utility.Model;
namespace Common.Utility.RabbitMQ
{
public class RabbitMQCustomContext : BackgroundService
{
ConnectionFactory factory = null;
IConnection connection = null;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
//创建连接对象工厂
factory = new ConnectionFactory()
{
UserName = AdminGlobalContext.RabbitMQConfig.UserName,
Password = AdminGlobalContext.RabbitMQConfig.Password,
HostName = AdminGlobalContext.RabbitMQConfig.HostName,
Port = AdminGlobalContext.RabbitMQConfig.Port,
RequestedHeartbeat = TimeSpan.FromSeconds(30), //心跳包
AutomaticRecoveryEnabled = true, //自动重连
TopologyRecoveryEnabled = true, //拓普重连
NetworkRecoveryInterval = TimeSpan.FromSeconds(10)
};
//创建连接对象
connection = factory.CreateConnection();
IModel channel = connection.CreateModel();
channel.ExchangeDeclare(AdminGlobalContext.RabbitMQConfig.ExchangeName, ExchangeType.Fanout);
channel.QueueDeclare(AdminGlobalContext.RabbitMQConfig.QueueName, false, false, false, null);
channel.QueueBind(AdminGlobalContext.RabbitMQConfig.QueueName, AdminGlobalContext.RabbitMQConfig.ExchangeName, "", null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (ch, ea) =>
{
var body = ea.Body.ToArray();
string str = Encoding.UTF8.GetString(body);
RecordsReq req= JsonConvert.DeserializeObject<RecordsReq>(str);
Console.WriteLine("接受到的mq消息:" + str);
channel.BasicAck(ea.DeliveryTag, false);
//Thread.Sleep(1000);
};
string consumerTag = channel.BasicConsume(AdminGlobalContext.RabbitMQConfig.QueueName, false, consumer);
}
catch (Exception)
{
throw;
}
}
}
}
...@@ -18,11 +18,10 @@ namespace Models.SqlModel ...@@ -18,11 +18,10 @@ namespace Models.SqlModel
public String code { get; set; } public String code { get; set; }
public String unit { get; set; }
[SugarColumn(ColumnName = "type_id")] [SugarColumn(ColumnName = "type_id")]
public String? typeId { get; set; } public String? typeId { get; set; }
[SugarColumn(ColumnName = "name")]
public String? name { get; set; } public String? typeName { get; set; }
public String? note { get; set; } public String? note { get; set; }
......
...@@ -10,21 +10,16 @@ namespace Models.ToolsModel ...@@ -10,21 +10,16 @@ namespace Models.ToolsModel
{ {
public ApiResult() public ApiResult()
{ {
IsSuccess = true;
code = "200"; code = "200";
msg = ""; msg = "";
data = ""; data = "";
} }
public bool IsSuccess { get; set; }
public string code { get; set; } public string code { get; set; }
//public int statusCode { get; set; } //public int statusCode { get; set; }
public object data { get; set; } public object data { get; set; }
public string msg { get; set; } public string msg { get; set; }
#region list info #region list info
public int page { get; set; }
public int count { get; set; }
public int total { get; set; }
#endregion #endregion
......
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "APIs", "APIs\APIs.csproj", "{50472AC8-0769-43FD-9559-DFAF7C616B47}" # Visual Studio Version 17
VisualStudioVersion = 17.5.33414.496
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIs", "APIs\APIs.csproj", "{50472AC8-0769-43FD-9559-DFAF7C616B47}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Models", "Models\Models.csproj", "{7E5B59D3-5DFA-460F-8DC4-C2A10C7E555E}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Models", "Models\Models.csproj", "{7E5B59D3-5DFA-460F-8DC4-C2A10C7E555E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repositories", "Repositories\Repositories.csproj", "{73D6C350-8596-424A-B52B-D5DEBEE196C4}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Repositories", "Repositories\Repositories.csproj", "{73D6C350-8596-424A-B52B-D5DEBEE196C4}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Services", "Services\Services.csproj", "{076E47FF-99EB-4C5B-82D8-272AD9DBE6AC}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{076E47FF-99EB-4C5B-82D8-272AD9DBE6AC}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{094E8D69-7AFA-4C76-9419-83F1DFF4944D}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "Common\Common.csproj", "{094E8D69-7AFA-4C76-9419-83F1DFF4944D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{7442AAAF-4E95-4765-AF7A-51907D6E09BA}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
...@@ -37,4 +45,7 @@ Global ...@@ -37,4 +45,7 @@ Global
{094E8D69-7AFA-4C76-9419-83F1DFF4944D}.Release|Any CPU.ActiveCfg = Release|Any CPU {094E8D69-7AFA-4C76-9419-83F1DFF4944D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{094E8D69-7AFA-4C76-9419-83F1DFF4944D}.Release|Any CPU.Build.0 = Release|Any CPU {094E8D69-7AFA-4C76-9419-83F1DFF4944D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal EndGlobal
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论