irc-netcore-api/IRaCIS.Core.Application/MassTransit/Consumer/TestConsumer.cs

155 lines
5.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain;
using IRaCIS.Core.Domain.Share;
using MassTransit;
using MassTransit.Mediator;
using MassTransit.Scheduling;
using Medallion.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.MassTransit.Consumer;
public class MasstransiTestCommand
{
public string value { get; set; }
}
/// <summary>
/// meditor send 的时候,请求流会先到消费者,返回后才会执行后续代码
/// publish 请求流不会先到消费者,发布后,直接执行后续代码
///
/// </summary>
/// <param name="_userRoleRepository"></param>
public class MasstransitTestConsumer(IRepository<UserRole> _userRoleRepository) : IConsumer<MasstransiTestCommand>
{
public async Task Consume(ConsumeContext<MasstransiTestCommand> context)
{
Console.WriteLine(_userRoleRepository._dbContext.GetHashCode());
Console.WriteLine("Now is " + DateTime.Now.ToString());
Console.WriteLine($"MassTransit.Consumer :{context.Message.value}");
await context.RespondAsync<IResponseOutput>(ResponseOutput.Ok());
}
}
[ApiExplorerSettings(GroupName = "Institution")]
public class TestMasstransitService : BaseService
{
public async Task<IResponseOutput> TestMasstransitRequest([FromServices] IMessageScheduler _scheduler,
[FromServices] IRecurringMessageScheduler _recurringMessageScheduler,
[FromServices] IRepository<TestLength> _testLengthRepository,
[FromServices] IRequestClient<MasstransiTestCommand> _requestClient,
[FromServices] IScopedClientFactory _clientFactory,
[FromServices] IScopedMediator _mediatorScoped,
[FromServices] IMediator _mediator)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
Console.WriteLine(_testLengthRepository._dbContext.GetHashCode());
//IScopedMediator 上下文一致, IMediator上下文不一致
//通过命令不获取结果 进入消费者后再返回 数据库上下文 不同
//await _mediator.Send(new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });
////通过命令获取结果 进入消费者后再返回 数据库上下文 相同
//var dd = await _mediatorScoped.CreateRequest(new MasstransiTestCommand() { value = "message at " + DateTime.Now.ToString() })
// .GetResponse<IResponseOutput>();
////发布后,不会立即进入消费者,消费者是另外的线程执行
//await _mediatorScoped.Publish(new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });
await _recurringMessageScheduler.ScheduleRecurringPublish(new QCImageQuestionRecurringSchedule() { CronExpression = "0/3 * * * * ? " }, new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });
//await _scheduler.SchedulePublish(DateTime.Now.AddSeconds(10), new MasstransiTestCommand() { value = "message at " + DateTime.Now.ToString() });
return ResponseOutput.Ok();
}
public async Task<IResponseOutput> TestWordToPdf()
{
var dd = await FileConvertHelper.ThirdStirling_PDFWordToPdfAsync(@"C:\Users\hang\Desktop\test.docx");
string outputFilePath = @"C:\Users\hang\Desktop\test-byte4-output.pdf"; // 保存路径
File.WriteAllBytes(outputFilePath, dd); // 将响应字节数组写入文件
//var envName = Environment.GetEnvironmentVariables()["ASPNETCORE_ENVIRONMENT"]?.ToString();
//// API 地址
//string apiUrl = "http://106.14.89.110:30088/api/v1/convert/file/pdf";
//// 模拟文件路径,假设你有一个内存流的文件,不指定实际文件
//string filePath = @"C:\Users\hang\Desktop\test.docx"; // 本地文件路径或者你可以直接使用流
//var fileBytes = File.ReadAllBytes(@"C:\Users\hang\Desktop\test.docx");
//try
//{
// // 创建 RestClient
// var client = new RestClient(apiUrl);
// // 创建 RestRequest使用 POST 方法
// var request = new RestRequest(apiUrl, Method.Post);
// request.AddHeader("accept", "*/*");
// //new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(filePath), out var contentType);
// // 直接上传文件,无需生成字节数组
// //request.AddFile("fileInput", filePath, contentType);
// // 添加文件流到请求
// request.AddFile("fileInput", fileBytes, "test-byte.docx");
// // 发送请求并获取响应
// var response = await client.ExecuteAsync(request);
// // 检查请求是否成功
// if (response.IsSuccessful)
// {
// // 保存接收到的文件到本地
// string outputFilePath = @"C:\Users\hang\Desktop\test-byte3-output.pdf"; // 保存路径
// File.WriteAllBytes(outputFilePath, response.RawBytes); // 将响应字节数组写入文件
// //如果要文件流,就这样
// //var stream = new MemoryStream(response.RawBytes);
// }
// else
// {
// Console.WriteLine($"上传失败,错误代码: {response.StatusCode}, 错误消息: {response.ErrorMessage}");
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine("发生异常: " + ex.Message);
//}
return ResponseOutput.Ok();
}
}