Advertisement

ElasticSearch安装和简单应用

阅读量:

安装elasticsearch

前置操作

elasticsearch依赖于jdk软件,并且在该系统中不允许以root账户登录。若采用root账户登录时会遇到问题。

复制代码
    Exception in thread "main" java.lang.RuntimeException: don't run elasticsearch as root.
    at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:93)
    at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:144)
    at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:270)
    at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)
    Refer to the log for complete error details.

所以需要保证你的集群中安装了jdk且能够被非root用户访问。

检查jdk的路径和权限配置。

上传elasticsearch安装包,解压

复制代码
    tar -xzvf elasticsearch-6.3.1.tar.gz

修改配置文件

更新Elasticsearch集群JVM参数设置和整体配置参数设置

复制代码
    vim elasticsearch-6.3.1/config/elasticsearch.yml
    
    #找到network并取消注释,把IP地址改为本机IP
    network.host: hadoop01
    
    vim elasticsearch-6.3.1/config/jvm.options
    
    #这里是jvm虚拟机的配置,根据实际集群性能配置
    -Xms1g
    -Xmx1g

修改系统配置

elasticsearch在系统配置方面有特定要求,在最大存储空间方面有一定限制,默认情况下系统会将最大允许创建的文件数量设定为65536。如果未进行相关参数设置,则会导致程序运行时出现错误提示信息。

复制代码
    for elasticsearch process is too low, increase to at least [65536]

修改两个系统配置文件。

复制代码
    vim /etc/security/limits.conf
    
    #在END OF FILE前添加
    * hard nofile 655360
    * soft nofile 131072
    * hard nproc 4096
    * soft nproc 2048
    
    source /etc/security/limits.conf

这里source会报四个找不到位置之类的,忽视掉。

复制代码
    vim /etc/sysctl.conf
    
    #在文件末尾添加
    vm.max_map_count=655360
    fs.file-max=655360
    
    sysctl -p

启动elasticsearch

从非root用户的视角重新启动系统,则可创建一个新的用户账户;访问Elasticsearch的安装路径

复制代码
    adduser elk
    passwd elk
    su elk
    cd bin/
    ./elasticsearch

等待日志打印完成后,访问IP:9200端口,会返回一条Json数据,则为启动成功。

复制代码
    http://hadoop01:9200
    
    #返回一条Json数据
    {
      "name" : "bU3-0bt",
      "cluster_name" : "elasticsearch",
      "cluster_uuid" : "kw0nLVTDS9ivVvQTL_Q-lQ",
      "version" : {
    "number" : "6.3.1",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "eb782d0",
    "build_date" : "2018-06-29T21:59:26.107521Z",
    "build_snapshot" : false,
    "lucene_version" : "7.3.1",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
      },
      "tagline" : "You Know, for Search"
    }
    
    
    http://hadoop01:9200/_cat/indices?v
    
    #返回一个表格(索引列表),新安装的时候应该为空。
    health status index uuid pri rep docs.count docs.deleted store.size pri.store.size

安装kibana

解压

为了方便可以把kibana和elasticsearch解压在同一个主目录下。

复制代码
    tar -xzvf kibana-6.3.1-linux-x86_64.tar.gz

一个纯前端的工具。

配置

只有一个配置文件,很简单

复制代码
    vim kibana-6.3.1-linux-x86_64/config/kibana.yml

把这三行的注释取消掉,并且把IP地址改为自己的IP地址

复制代码
    server.host: "hadoop01"
    elasticsearch.url: "http://hadoop01:9200"
    kibana.index: ".kibana"

启动

前往kibana的binary文件夹位置,在启动KIBANA应用程序时,请注意该程序运行速度较慢,请确保至少等待1至3分钟才能完成启动过程。

复制代码
    cd ../bin
    nohup ./kibana &

访问http://hadoop01:5601/,访问到kibana既启动成功。

elasticsearch使用

复制代码
    #创建movie索引库 
    PUT /movie_index
    #查询movie库 
    GET /movie_index
    #插入一条数据 
    PUT movie_index/movie/1
    {
      "movie_name":"red sea action",
      "price":1000.00,
      "time":"2018-10-10",
      "actors":[
    {"name":"zhang han yu","sex":1},{"name":"peng yu yan","sex":0},{"name":"zhang yi","sex":0}]
    }
    #插入一条数据 
    PUT movie_index/movie/2
    {
      "movie_name":"red sea event",
      "price":200.00,
      "time":"2018-01-05",
      "actors":[
    {"name":"zhang yu","sex":1},{"name":"zhang san","sex":0},{"name":"zhang yi","sex":0}]
    }
    #关键字查询 
    GET /movie_index/movie/_search
    {
      "query": {
    "match": {
      "movie_name": "red event"
    }
      }
    }
    #删除一条数据  
    DELETE movie_index/movie/1
    #创建movie索引库 
    PUT /movie_index1
    #插入一条数据 
    PUT movie_index1/movie/1
    {
      "movie_name":"红海行动 ",
      "price":100.00,
      "time":"2018-01-05",
      "actors":[
    {"name":"张涵予","sex":1},{"name":"张三","sex":0},{"name":"张毅","sex":0}],
    "movie_business":["1","2","842"]
    }
    #插入一条数据 
    PUT movie_index1/movie/2
    {
      "movie_name":"红海事件",
      "price":200.00,
      "time":"2018-01-05",
      "actors":[
    {"name":"张涵予","sex":1},{"name":"李四","sex":0}],
    "movie_business":["2","3","843"]
    }
    #关键字复合查询 
    GET /movie_index1/movie/_search
    {
      "query": {
    "match": {
      "movie_name": "红"
    }
      }
    }
    #分词测试
    GET _analyze
    {
      "text":"我是中国人",
      "analyzer":"ik_max_word"
    }

MySQL数据导入

编写一个Springboot程序进行批量导入。

pom依赖

复制代码
    <dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-jdbc</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.mybatis.spring.boot</groupId>
    			<artifactId>mybatis-spring-boot-starter</artifactId>
    			<version>1.3.4</version>
    		</dependency>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<scope>runtime</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<!-- 通用mapper -->
    		<dependency>
    			<groupId>tk.mybatis</groupId>
    			<artifactId>mapper-spring-boot-starter</artifactId>
    			<version>1.2.3</version>
    			<exclusions>
    				<exclusion>
    					<groupId>org.springframework.boot</groupId>
    					<artifactId>spring-boot-starter-jdbc</artifactId>
    				</exclusion>
    			</exclusions>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    		</dependency>
    		<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
    		<dependency>
    			<groupId>io.searchbox</groupId>
    			<artifactId>jest</artifactId>
    			<version>5.3.3</version>
    		</dependency>
    		<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
    		<dependency>
    			<groupId>net.java.dev.jna</groupId>
    			<artifactId>jna</artifactId>
    			<version>4.5.1</version>
    		</dependency>
    	</dependencies>

application.properties配置文件

复制代码
    # tomcat端口号
    server.port=8080
    # 数据源
    spring.datasource.url=jdbc:mysql://hadoop01:3306/elasticsearch
    spring.datasource.username=root
    spring.datasource.password=root
    
    # mybatis
    mybatis.mapper-locations=classpath:mapper/*Mapper.xml
    mybatis.configuration.map-underscore-to-camel-case=true
    
    # es配置
    spring.elasticsearch.jest.uris=http://hadoop01:9200

批量插入方法

复制代码
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DemoApplicationTests {
    
    	@Autowired
    	SkuInfoMapper skuInfoMapper;
    
    	@Autowired
    	JestClient jestClient;
    
    	@Test
    	public void inputTest() throws IOException {
    
    			// 查询出mysql中的商品数据
    			// 封装成java对象
    			List<SkuInfo> skuInfos = skuInfoMapper.selectAll();
    
    			System.out.print(skuInfos.size());
    
    			// 打开es链接
       	    	 // 封装es命令对象
    			for (SkuInfo skuInfo : skuInfos) {
    				Index index = new 				Index.Builder(skuInfo).index("gmall").type("SkuInfo").id(skuInfo.getId()).build();
    				// 导入es数据
    				jestClient.execute(index);//es的命令
    			}
       		}	
    }

这段描述较为简短但信息量大。 es目前并未提供直接的批量导入功能 , 仅能借助spring程序 来完成相关操作 。 具体流程是 首先调用javabean 对mysql数据进行封装处理 , 然后依次调用es的api 进行数据插入操作 。 这段代码完全照搬自标准 spring 模板库 , 整个项目的实现过程相当简单 。

安装tomcat和nginx

安装配置tomcat

tomcat下载安装包解压,随便一个版本能用就行。

复制代码
    tar -xzvf apache-tomcat-7.0.47.tar.gz

修改配置文件。

复制代码
    vim apache-tomcat-7.0.47/conf/server.xml

在标签块的最后一行插入一个新的标签, 相当于重新指定网页资源目录及其访问路径

复制代码
    <Context path = "/manager" docBase = "/usr/elk/project/manager-test" debug = "0" privileged = "true"/>

启动并运行 Tomcat,并连接至 hadoop01:8080 进入 tomcat 网页;即可确认配置状态

复制代码
    ./apache-tomcat-7.0.47/bin/startup.sh

安装配置nginx

nginx可以直接yum

复制代码
    yum install nginx
    systemctl start nginx

此时访问hadoop01为nginx的主页。

修改nginx的配置文件设置反向代理

复制代码
    vim /etc/nginx/conf.d/default.conf

修改location / {}并在server外增加一条

复制代码
    upstream manager {
    #上游代理tomcat的8080端口
        server localhost:8080 weight=10;
    }
    server{
    	#...
    location / {
    #访问hadoop01:80/的时候转发至代理路径
        proxy_pass http://manager:8080;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    
    }
    #...
    }

重启nginx,访问hadoop01为tomcat主页,

复制代码
    systemctl restart nginx

nginx报错

在实际操作过程中遇到Nginx在反向代理过程中无法正确显示代理页面的问题,并返回了HTTP 403错误代码.

复制代码
    An error occurred.
    Sorry, the page you are looking for is currently unavailable.
    Please try again later.
    
    If you are the system administrator of this resource then you should check the error log for details.
    
    Faithfully yours, nginx.

查看nginx的日志

复制代码
    cat /var/log/nginx/error.log
    
    [crit] 10478#10478: *1 connect() to 192.168.15.101:8080 failed (13: Permission denied) while connecting to upstream, client: 192.168.15.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://192.168.15.101:8080/", host: "hadoop01"

遇到权限不足的问题后进行调查时发现可能是因为SELINUX被启用所致,在此情况下建议将SELINUX参数设置为禁用状态

复制代码
    vim /etc/selinux/config

修改内容为

复制代码
    #SELINUX=enforcing
    SELINUX=disabled

重启机器reboot,成功解决。

安装logstash

上传解压安装包

复制代码
    tar -xzvf logstash-6.3.1.tar.gz

修改配置文件,新建一个test.conf

复制代码
    vim logstash-6.3.1/config/test.conf

插入内容

复制代码
    input {
      stdin { }
    }
    output {
    stdout {codec=>"rubydebug"}
    }

调用logstash服务程序运行较慢。遇到错误时可以在命令行追加-t参数并查看配置文件。如果没有错误发生,则可以通过终端输入相应内容,并返回一个由Ruby编写的字符串。

复制代码
    ./logstash-6.3.1/bin/logstash -f logstash-6.3.1/config/test.conf

配置logstash

新的配置文件,读取nginx的日志文件,并且输出到elasticsearch中。

复制代码
    input {
        file {
                path => ["/var/log/nginx/access.log"]
                type => "nginx_access"
                #start_position => "beginning"
        }
    }
    filter {
        if [type] == "nginx_access" {
                grok {
                        patterns_dir => "/usr/elk/project/patterns/"
                        match => {
                                "message" => "%{NGINXACCESS}"
                        }
                }
    
                date {
                        match => ["timestamp","dd/MMM/YYY:HH:mm:ss Z"]
                }
    
                if [param] {
                        ruby {
                                init => "@kname = ['quote','url_args']"
                                code => "
                                        new_event =
                                        LogStash::Event.new(Hash[@kname.zip(event.get('param').split('?'))])
                                        new_event.remove('@timestamp')
                                        event.append(new_event)
                                "
                        }
                }
    
                if [url_args] {
                        ruby {
                                init => "@kname = ['key','value']"
                                code => "event.set('nested_args',event.get('url_args').split('&').cllect{|i| Hash[@kname.zip(i.split('='))]})"
                                remove_field => ["url_args","param","quote"]
                        }
                }
    
                mutate {
                        convert => ["response","integer"]
                        remove_field => "timestamp"
                }
        }
    }
    output {
        stdout {
                codec => rubydebug
        }
    
        elasticsearch {
                hosts => ["http://hadoop01:9200"]
                index => "logstash-%{type}-%{+YYYY.MM.dd}"
        }
    }

在配置中指定 patterns_dir 设置为 /usr/elk/project/patterns/ ,该路径下的内容表示 nginx 的日志解析格式,并且是正则表达式形式;要求在该目录下生成一个名为 nginx 的日志解析配置文件。

复制代码
    NGINXACCESS %{IPORHOST:clientip} %{HTTPDUSER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion})?|%{DATA:rawrequest})" %{NUMBER:response} (?:%{NUMBER:bytes}|-)
    NGINXACCESSLOG %{COMMONAPACHELOG} %{QS:referrer} %{QS:agent}

启动logstash

复制代码
    ./logstash-6.3.1/bin/logstash -f logstash-6.3.1/config/elasticDemo.conf

通过将 nginx 服务器上的所有响应内容进行转发操作时,在访问任何被转发的网页链接时,请注意控制台将会自动显示相关信息。

kibana可视化

先获取一下索引列表看看索引是否创建成功。

复制代码
    GET _cat/indices

可以看到一个logstash-nginx_access_[日期]的索引,查找这个索引的内容。

复制代码
    GET logstash-nginx_access-2020.10.13/_search

kibana->ManageMnet->Index Patterns->Create

生成一个新的索引数据结构,基于Elasticsearch的数据架构设计即可。例如,在一个手机销售模拟系统中

创建成功后kibana->Visualize-Create选择一个合适的图表模式。

以Pie饼状图为例,点击Pie后选择之前添加的索引数据集。

进入Metrics页面后,在Slice Size选项卡中设置聚合方式时,请选择Count、Max、Sum等常见聚合模式中的任意一种以满足需求

点击buckets导航至Split Slices选项卡,并选择Filters功能;在弹出的Filters对话框中输入所需查询字段;随后添加更多所需的字段信息;单击Metrics部分的小三角符号并执行操作;随后即可生成图表界面,并将图表保存到指定位置。

全部评论 (0)

还没有任何评论哟~