.NET 使用Elasticsearch
centos7使用使用国内镜像源快速安装docker-compose
docker-compose中启动elk的yml文件
点击查看代码
version: '3.1'
services:
elasticsearch:
container_name: elasticsearch
hostname: elasticsearch
image: docker.elastic.co/elasticsearch/elasticsearch:7.9.2
restart: always
ports:
- 9200:9200
- 9300:9300
volumes:
- elasticsearch-data:/usr/share/elasticsearch/data
environment:
- xpack.monitoring.enabled=true
- xpack.watcher.enabled=false
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- discovery.type=single-node
kibana:
container_name: kibana
hostname: kibana
image: docker.elastic.co/kibana/kibana:7.9.2
restart: always
ports:
- 5601:5601
depends_on:
- elasticsearch
environment:
- ELASTICSEARCH_URL=http://localhost:9200
volumes:
elasticsearch-data:
docker-compose 相关命令
构建启动容器 -d 后台运行
docker-compose up -d
停止up 命令所启动的容器,并移除网络
docker-compose down
1、使用curl到国内镜像源下载docker-compose(路径中的版本好自己到对应官网替换)
curl -L https://get.daocloud.io/docker/compose/releases/download/1.22.0/docker-compose-
uname -s-
uname -m > /usr/local/bin/docker-compose
2、修改docker-compose的权限
chmod +x /usr/local/bin/docker-compose
3、查看docker-compose是否安装成功
docker-compose -v
显示版本号即代表成功
接入使用
1.创建一个webapi项目ElasticsearchNetDemo
安装一个包
Install-Package NEST
创建一个实体类:VisitLog
点击查看代码
using System;
namespace ElasticsearchNetDemo.Domain
{
public class VisitLog
{
public string Id { get; set; }
/// <summary>
/// UserAgent
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// Method
/// </summary>
public string Method { get; set; }
/// <summary>
/// Url
/// </summary>
public string Url { get; set; }
/// <summary>
/// Referrer
/// </summary>
public string Referrer { get; set; }
/// <summary>
/// IpAddress
/// </summary>
public string IpAddress { get; set; }
/// <summary>
/// Milliseconds
/// </summary>
public int Milliseconds { get; set; }
/// <summary>
/// QueryString
/// </summary>
public string QueryString { get; set; }
/// <summary>
/// Request Body
/// </summary>
public string RequestBody { get; set; }
/// <summary>
/// Cookies
/// </summary>
public string Cookies { get; set; }
/// <summary>
/// Headers
/// </summary>
public string Headers { get; set; }
/// <summary>
/// StatusCode
/// </summary>
public int StatusCode { get; set; }
/// <summary>
/// Response Body
/// </summary>
public string ResponseBody { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
}
3.添加一个接口类IElasticsearchProvider
点击查看代码
using Nest;
namespace ElasticsearchNetDemo.Elasticsearch
{
public interface IElasticsearchProvider
{
IElasticClient GetClient();
}
}
4.在ElasticsearchProvider中实现IElasticsearchProvider接口
点击查看代码
using Nest;
namespace ElasticsearchNetDemo.Elasticsearch
{
public class ElasticsearchProvider: IElasticsearchProvider
{
public IElasticClient GetClient()
{
var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"));
return new ElasticClient(connectionSettings);
}
}
}
5.添加Elasticsearch仓储基类,ElasticsearchRepositoryBase
点击查看代码
using Nest;
namespace ElasticsearchNetDemo.Elasticsearch
{
public abstract class ElasticsearchRepositoryBase
{
private readonly IElasticsearchProvider _elasticsearchProvider;
public ElasticsearchRepositoryBase(IElasticsearchProvider elasticsearchProvider)
{
_elasticsearchProvider = elasticsearchProvider;
}
protected IElasticClient Client => _elasticsearchProvider.GetClient();
protected abstract string IndexName { get; }
}
}
6.新建一个IVisitLogRepository仓储接口
点击查看代码
using ElasticsearchNetDemo.Domain;
namespace ElasticsearchNetDemo.Repositories
{
public interface IVisitLogRepository
{
Task InsertAsync(VisitLog visitLog);
Task DeleteAsync(string id);
Task UpdateAsync(VisitLog visitLog);
Task<Tuple<int, IList<VisitLog>>> QueryAsync(int page, int limit);
}
}
7.新建一个VisitLogRepository 仓储
点击查看代码
using ElasticsearchNetDemo.Domain;
using ElasticsearchNetDemo.Elasticsearch;
namespace ElasticsearchNetDemo.Repositories
{
public class VisitLogRepository : ElasticsearchRepositoryBase, IVisitLogRepository
{
public VisitLogRepository(IElasticsearchProvider elasticsearchProvider) : base(elasticsearchProvider)
{
}
protected override string IndexName => "visitlogs";
public async Task InsertAsync(VisitLog visitLog)
{
await Client.IndexAsync(visitLog, x => x.Index(IndexName));
}
public async Task DeleteAsync(string id)
{
await Client.DeleteAsync<VisitLog>(id, x => x.Index(IndexName));
}
public async Task UpdateAsync(VisitLog visitLog)
{
await Client.UpdateAsync<VisitLog>(visitLog.Id, x => x.Index(IndexName).Doc(visitLog));
}
public async Task<Tuple<int, IList<VisitLog>>> QueryAsync(int page, int limit)
{
var query = await Client.SearchAsync<VisitLog>(x => x.Index(IndexName)
.From((page - 1) * limit)
.Size(limit)
.Sort(x => x.Descending(v => v.CreatedAt)));
return new Tuple<int, IList<VisitLog>>(Convert.ToInt32(query.Total), query.Documents.ToList());
}
}
}
8.新建一个VisitLogController 控制器
点击查看代码
using ElasticsearchNetDemo.Domain;
using ElasticsearchNetDemo.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
namespace ElasticsearchNetDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class VisitLogController : ControllerBase
{
private readonly IVisitLogRepository _visitLogRepository;
public VisitLogController(IVisitLogRepository visitLogRepository)
{
_visitLogRepository = visitLogRepository;
}
[HttpGet]
public async Task<IActionResult> QueryAsync(int page = 1, int limit = 10)
{
var result = await _visitLogRepository.QueryAsync(page, limit);
return Ok(new
{
total = result.Item1,
items = result.Item2
});
}
[HttpPost]
public async Task<IActionResult> InsertAsync([FromBody] VisitLog visitLog)
{
await _visitLogRepository.InsertAsync(visitLog);
return Ok("新增成功");
}
[HttpDelete]
public async Task<IActionResult> DeleteAsync([Required] string id)
{
await _visitLogRepository.DeleteAsync(id);
return Ok("删除成功");
}
[HttpPut]
public async Task<IActionResult> UpdateAsync([FromBody] VisitLog visitLog)
{
await _visitLogRepository.UpdateAsync(visitLog);
return Ok("修改成功");
}
}
}
9.大功告成,最后一步不要忘记在Startup.cs中添加服务,不然无法使用依赖注入
点击查看代码
builder.Services.AddSingleton<IElasticsearchProvider, ElasticsearchProvider>();
builder.Services.AddSingleton<IVisitLogRepository, VisitLogRepository>();
如果你安装了 kibana ,可以去查看你的数据了
GET _cat/indices
GET visitlogs/_search
越是无知的人越是觉得自己无所不知(之前的自己)
越是学习的人越是觉得自己会的太少了(现在的自己)
共勉