【愚公系列】2022年05月 .NET架构班 063-分布式中间件 .NET Core下Elasticsearch的基本使用

举报
愚公搬代码 发表于 2022/05/10 00:08:03 2022/05/10
【摘要】 一、.NET Core下Elasticsearch的基本使用 1.前提 1.1 jdkjava是当前比较流行的一种编程语言,当我们开始学习java的时候肯定会先要安装jdk,然后进行环境变量控制。JRE(Java Runtime Environment ) Java运行环境,用来运行JAVA程序的。JDK(Java Development Kit) Java开发工具包,包含JRE。因此只...

一、.NET Core下Elasticsearch的基本使用

1.前提

1.1 jdk

java是当前比较流行的一种编程语言,当我们开始学习java的时候肯定会先要安装jdk,然后进行环境变量控制。

  • JRE(Java Runtime Environment ) Java运行环境,用来运行JAVA程序的。
  • JDK(Java Development Kit) Java开发工具包,包含JRE。因此只需要下载安装JDK即可中。
  • JDK是Sun Microsystems针对Java开发员的产品,JSP运行环境需要JDK的支持。
  • JDK 是整个Java的核心,包括了Java运行环境,Java工具和Java基础的类库。

java官网:http://www.oracle.com/
在这里插入图片描述
依次点击:资源》下载》JDK
在这里插入图片描述
选择最新版本进行安装就可以了
在这里插入图片描述
安装完记得设置变量环境。输入:java -version验证是否安装成功
在这里插入图片描述

1.2 Elasticsearch准备

Elasticsearch官网:​https://www.elastic.co/cn/downloads/elasticsearch
在这里插入图片描述
先进入到Elasticsearch中,进入到config目录中
在这里插入图片描述

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: my-application-cluster
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: localhost
#
# Set a custom port for HTTP:
#
http.port: 9200
cluster.routing.allocation.disk.threshold_enabled: false
http.cors.enabled: true
http.cors.allow-origin: "*"
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true

elasticsearch.bat
在这里插入图片描述
在这里插入图片描述

1.3 可视化工具kibana下载

地址:https://www.elastic.co/cn/downloads/past-releases/

在这里插入图片描述
启动kibana
在这里插入图片描述
登录kibana
在这里插入图片描述
查看kibana
在这里插入图片描述

2.使用

2.1 nuget安装包

NEST和Elasticsearch版本对应上

NEST

2.2 相关接口和类

Product模型类

/// <summary>
/// 商品
/// </summary>
public class Product
{
    public string Id { set; get; }
    public string ProductCode { set; get; }    //商品编码
    public string ProductUrl { set; get; }         // 商品主图 text
    public string ProductTitle { set; get; }       //商品标题
    public string ProductDescription { set; get; }     // 图文描述
    public decimal ProductVirtualprice { set; get; } // 商品虚拟价格
    public decimal ProductPrice { set; get; }       //价格
    public int ProductSort { set; get; }    //商品序号
    public int ProductSold { set; get; }        //已售件数
    public int ProductStock { set; get; }       //商品库存
    public string ProductStatus { set; get; } // 商品状态
    public int score { set; get; } //商品级别
}

ProductService服务类

/// <summary>
/// 商品服务实现
/// </summary>
public class ProductService : IProductService
{
    private readonly IMongoCollection<Product> _products;

    public ProductService()
    {
        #region 1、单实例连接
            {
                var node = new Uri("http://localhost:9200");
                // var defaultIndex = "products";

                var settings = new ConnectionSettings(node);
                //.DefaultIndex(defaultIndex);

                elasticClient = new ElasticClient(settings);
            }
            #endregion
     
    }

    public void Create(Product Product)
    {
        elasticClient.Index(Product,idx => idx.Index("products"));
    }
 }

2.3 使用

/// <summary>
/// 商品控制器
/// </summary>
[ApiController]
[Route("Product")]
public class ProductController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    } 
    /// <summary>
    /// 添加商品
    /// </summary>
    /// <param name="product"></param>
    /// <returns></returns>
    [HttpPost]
    public ActionResult<Product> PostProduct(Product product)
    {
        _productService.Create(product);
        return CreatedAtAction("GetProduct", new { id = product.Id }, product);
    }
}

总结

Elasticsearch是依赖于java开发的,所以必须得有java环境才能运行,但Elasticsearch是支持多语言的完全适用于.NET Core。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。