public class SearchRequestHandler : IConsumer<SearchRequest>
{
private readonly AddDbContext _dbContext;
private readonly ILogger<SearchRequestHandler> _logger;
public SearchRequestHandler(AddDbContext dbContext, ILogger<SearchRequestHandler> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task Consume(ConsumeContext<SearchRequest> context)
{
var searchRequest = context.Message;
_logger.LogInformation("Получен запрос на поиск: {Text}", searchRequest.Text);
var searchResult = await PerformSearch(searchRequest.Text);
_logger.LogInformation("Поиск завершен. Найдено {Count} результатов", searchResult.Count);
var searchResponse = new SearchResponse { Data = searchResult };
await context.RespondAsync(searchResponse);
}
private async Task<List<object>> PerformSearch(string searchText)
{
var users = await _dbContext.Users
.Where(p => p.Username.Contains(searchText, StringComparison.OrdinalIgnoreCase))
.ToListAsync();
var results = users.Select(p => new { p.Username }).Cast<object>().ToList();
return results;
}
}
public class SearchRequest
{
public string Text { get; set; }
}
public class SearchResponse
{
public List<object> Data { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "UserService", Version = "v1" });
});
services.AddDbContext<AddDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("UserConnection"),
sqlOptions => sqlOptions.CommandTimeout(60)));
services.AddScoped<UserServices>();
services.AddMassTransit(config =>
{
config.AddConsumer<SearchRequestHandler>();
config.UsingRabbitMq((context, cfg) =>
{
var rabbitMqConfig = Configuration.GetSection("RabbitMQ");
cfg.Host(new Uri(rabbitMqConfig["Hostname"]), h =>
{
h.Username(rabbitMqConfig["Username"]);
h.Password(rabbitMqConfig["Password"]);
});
cfg.ConfigureEndpoints(context);
});
});
services.AddScoped<IPublishEndpoint>(provider =>
{
var busControl = provider.GetRequiredService<IBusControl>();
return busControl;
});
Log.Logger = new LoggerConfiguration()
.WriteTo.File("logses.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddSerilog();
});
}