日志系统升级之路(.Net客户端的使用)

一、客户端

由于我们的Framework版本基于4.5,所以选取了 NEST 和 Elasticsearch.Net 的版本最高只能选择 6.1.0


二、ES客户端封装

代码比较简单,不再赘述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Nest;
using GFK.Common.Extends;
using GFK.Common.Consts;

namespace GFK.Elasticsearch
{
    /// <summary>
    /// 
    /// </summary>
    public class ESClient
    {
        /// <summary>
        /// 
        /// </summary>
        public ElasticClient esClient = null;

        /// <summary>
        /// 创建ES客户端实例
        /// </summary>
        /// <param name="hostNames">ES服务域名,支持集群</param>
        public ESClient(List<string> hostNames)
        {
            if (!hostNames.HasValue())
            {
                throw new ArgumentNullException("hostNames 至少需要传入一个ES服务");
            }

            var uris = new List<Uri>();
            foreach (var host in hostNames)
            {
                var uri = new Uri(host);
                uris.Add(uri);
            }
            var connectionPool = new SniffingConnectionPool(uris);
            var settings = new ConnectionSettings(connectionPool);
            esClient = new ElasticClient(settings);
        }

        /// <summary>
        /// 索引文档
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="item">实体</param>
        /// <param name="isSuffix">索引名是否添加日期后缀</param>
        /// <returns></returns>
        public IIndexResponse CreateIndex<T>(T item, bool isSuffix = false) where T : class
        {
            if (esClient == null)
            {
                throw new Exception("ES 初始化异常,客户端实例为空");
            }

            var index = item.GetAttribute<ESIndexNameAttribute>();
            if (index == null || index.IndexName.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("item 必须使用 ElasticsearchIndexAttribute 指定索引名");
            }

            var indexName = index.IndexName;
            if (!indexName.IsNullOrWhiteSpace() && isSuffix)
            {
                indexName = string.Format("{0}-{1}", indexName, DateTime.Now.ToString(DateTimeTypeConst.DATE));
            }

            //索引不存在的时候自动创建
            return esClient.Index(item, p => p.Index(indexName));
        }

    }
}


三、ES客户端的使用

日志模型如下:

using GFK.Common.Consts;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace G.Demo
{
    [GFK.Elasticsearch.ESIndexName("log")]
    [ElasticsearchType(Name = "_doc", IdProperty = "id")]
    public class Log
    {
        [Keyword(Name = "id")]
        public string Id { get; set; } = Guid.NewGuid().ToString("N");

        /// <summary>
        /// 系统代码
        /// </summary>
        [Keyword(Name = "system_code")]
        public string SystemCode { get; set; }

        /// <summary>
        /// 系统模块
        /// </summary>
        [Keyword(Name = "source")]
        public string Source { get; set; }

        /// <summary>
        /// 所在机器名
        /// </summary>
        [Text(Name = "machine_name")]
        public string MachineName
        {
            get
            {
                return System.Environment.MachineName;
            }
        }

        /// <summary>
        /// 应用程序域名称
        /// </summary>
        [Text(Name = "appdomain_name")]
        public string AppdomainName
        {
            get
            {
                return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }
        }

        /// <summary>
        /// 文档信息
        /// </summary>
        [Text(Name = "message")]
        public string Message { get; set; }

        /// <summary>
        /// 文档创建时间
        /// </summary>
        [Date(Name = "created_time")]
        public DateTime CreatedTime { get; set; } = DateTime.Now;
    }
}

使用代码比较简单,不再赘述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GFK.Common;
using GFK.Elasticsearch;
using GFK.Common.Extends;

namespace G.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new ESClient(new List<string>() { "http://192.168.17.130:9200" });

            for (int i = 0; i < 5; i++)
            {
                var log = new Log()
                {
                    Message = "让我测试测试" + i,
                    Source = "Program.Main",
                    SystemCode = "G.Demo"
                };
                var rst = client.CreateIndex<Log>(log, true);
                if (rst.Result == Nest.Result.Created)
                {
                    Console.WriteLine("第{0}个文档索引成功", i);
                }
                else
                {
                    Console.WriteLine("第{0}个索引失败,文档内容为:{1}", i, log.ToJson());
                }
            }

            Console.Read();
        }
    }
}


运行后出现下图,即表示索引文档成功。

image.png

posted @ 2020-04-20 15:09  划破黑夜  阅读(107)  评论(0编辑  收藏  举报