.NetCore中Elasticsearch组件NEST的使用
1. 安装Docker
# 安装Docker
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
# 安装完Docker后,打开阿里云,使用阿里提供的镜像加速服务,下面有执行代码,直接拷贝到Linux执行即可。
2. 安装 Elasticsearch
# 创建网络(应该是Kibana使用的)
docker network create elastic
# 拉取镜像
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.14.0
docker run --name es-demo --net elastic -d -p 19200:9200 -p 19300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.14.0
3. 安装NEST组件
使用方式直接看NEST项目的文档
3. 连接配置
-
配置文件
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ElastictsearchOptions": { "Urls": [ "http://localhost:8001", "http://localhost:8002", "http://localhost:8003", "http://localhost:8004" ] } }
-
注入配置
/// <summary> /// Elasticsearch 配置类 /// </summary> public class ElastictsearchOptions { public List<Uri> Urls { get; set; } }
public void ConfigureServices(IServiceCollection services) { services.Configure<ElastictsearchOptions>(Configuration.GetSection(nameof(ElastictsearchOptions))); services.AddSingleton<IESService, ESService>(); }
-
Elasticsearch服务实现类
/// <summary> /// Elasticsearch 服务 /// </summary> public class ESService : IESService { private ElasticClient ESClient { get; } #region 依赖注入 public ESService(IOptionsMonitor<ElastictsearchOptions> esOptionsMonitor) { ElastictsearchOptions option = esOptionsMonitor.CurrentValue; var urls = new StaticConnectionPool(option.Urls); var settings = new ConnectionSettings(urls); ESClient = new ElasticClient(settings); } #endregion }
-
上层应用使用
// 直接注入IESService使用