Elasticsearch 8.7.1 with Spring
Elasticsearch是一個(gè)基于Lucene的搜索引擎,提供了分布式、多租戶的全文搜索引擎功能。它可以快速地存儲(chǔ)、搜索和分析大量數(shù)據(jù),適用于各種類型的應(yīng)用程序,如日志分析、實(shí)時(shí)搜索等。
使用Docker啟動(dòng)Elasticsearch & Kibana
運(yùn)行命令啟動(dòng)Elasticsearch
docker run --name elasticsearch --net example-elastic-network -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -t docker.elastic.co/elasticsearch/elasticsearch:8.7.1
成功后會(huì)提示
? Elasticsearch security features have been automatically configured!
? Authentication is enabled and cluster connections are encrypted.
?? Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
這是密碼
?? HTTP CA certificate SHA-256 fingerprint:
74226f5fe0e9faefbe2b3d7f696fe1157979f164344081537679d681bd5c98a0
?? Configure Kibana to use this cluster:
? Run Kibana and click the configuration link in the terminal when Kibana starts.
? Copy the following enrollment token and paste it into Kibana in your browser (valid for the next 30 minutes):
這是Kibana的token
?? Configure other nodes to join this cluster:
? Copy the following enrollment token and start new Elasticsearch nodes with `bin/elasticsearch --enrollment-token <token>` (valid for the next 30 minutes):
這是配置其他節(jié)點(diǎn)用的token
If you re running in Docker, copy the enrollment token and run:
`docker run -e "ENROLLMENT_TOKEN=<token>" docker.elastic.co/elasticsearch/elasticsearch:8.7.1`
運(yùn)行命令啟動(dòng)Kibana
docker run --name kibana --net example-elastic-network -p 5601:5601 docker.elastic.co/kibana/kibana:8.7.1
成功后會(huì)提示如下信息
...
i Kibana has not been configured.
Go to http://0.0.0.0:5601/?code=794975 to get started.
...
這個(gè)鏈接如果不行換成將ip地址改為localhost試試。
Kibana是Elasticsearch的可視化工具,以圖表、表格和地圖等形式輕松地分析和可視化Elasticsearch中存儲(chǔ)的數(shù)據(jù)。
代碼部分
在Spring Boot中使用Elasticsearch可以通過(guò)Spring Data Elasticsearch來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何在Spring Boot中使用Elasticsearch:
-
添加Elasticsearch依賴
在pom.xml文件中添加以下依賴項(xiàng):<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> -
配置application.properties
在application.properties文件中添加以下配置項(xiàng):# 當(dāng)設(shè)置為true時(shí),Spring會(huì)自動(dòng)掃描應(yīng)用程序中的@Repository注解,并創(chuàng)建相應(yīng)的Elasticsearch存儲(chǔ)庫(kù)實(shí)例。 spring.data.elasticsearch.repositories.enabled=true -
添加Java配置
@Configuration public class ClientConfig { @Value("${es.hosts}") private String hosts; @Value("${es.name:elastic}") private String name; @Value("${es.password}") private String password; @Bean public ElasticsearchClient docqaElasticsearchClient() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(name, password)); List<HttpHost> httpHosts = new ArrayList<>(); String[] split = hosts.split(","); for (String s : split) { httpHosts.add(HttpHost.create(s)); } HttpHost[] httpHosts1 = httpHosts.toArray(new HttpHost[0]); SSLContext sslContext; try { sslContext = readCrtFile("src/main/resources/elastic.crt"); } catch (Exception e) { throw new RuntimeException(e); } RestClient client = RestClient .builder(httpHosts1) .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider).setKeepAliveStrategy((response, context) -> 180 * 1000)) .build(); ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper()); return new ElasticsearchClient(transport); } public static SSLContext readCrtFile(String crtFilePath) throws Exception { // 讀取crt文件 InputStream inputStream = new FileInputStream(crtFilePath); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream); // 創(chuàng)建KeyStore并將crt文件添加到KeyStore中 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("cert", certificate); // 創(chuàng)建TrustManagerFactory并初始化KeyStore TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); // 創(chuàng)建KeyManagerFactory并初始化KeyStore KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, null); // 創(chuàng)建SSLContext并初始化TrustManager和KeyManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return sslContext; } }注意!注意!注意!
Elastic使用了https,而本地的jdk\lib\security\cacerts中沒(méi)有對(duì)應(yīng)certification,會(huì)導(dǎo)致鏈接時(shí)報(bào)錯(cuò),PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target ... unable to find valid certification path to requested target所以要通過(guò)訪問(wèn)
https://localhost:9200使用瀏覽器導(dǎo)出Elastic的證書。
下面列出兩種方法解決:- 使用命令將下載的
.crt文件信息導(dǎo)入到本地的cacerts中:keytool -keystore path\to\jdk\cacerts -import -alias xxCert -file "path\to\xx.crt" - 通過(guò)上述
readCrtFile方法加載crt信息。
- 使用命令將下載的
-
創(chuàng)建實(shí)體類
創(chuàng)建一個(gè)Java類,用于映射Elasticsearch索引中的文檔。例如:@Data @Document(indexName = "employee") public class Employee { @Id private String id; private String firstName; private String lastName; private String department; // Getters and setters } -
創(chuàng)建Elasticsearch存儲(chǔ)庫(kù)
創(chuàng)建一個(gè)接口,擴(kuò)展ElasticsearchRepository接口,用于訪問(wèn)Elasticsearch索引。例如:// ElasticsearchRepository類中有定義好的很多方法 public interface EmployeeRepository extends ElasticsearchRepository<Employee, String> {} -
使用Elasticsearch存儲(chǔ)庫(kù)
@RestController @RequestMapping("/api/employees") public class EmployeeController { // 使用自動(dòng)注入的`MyDocumentRepository`訪問(wèn)Elasticsearch @Autowired private EmployeeRepository repository; @PostMapping public Employee create(@RequestBody Employee employee) { return repository.save(employee); } @GetMapping("/{id}") public Optional<Employee> findById(@PathVariable String id) { return repository.findById(id); } @GetMapping public Iterable<Employee> findAll() { return repository.findAll(); } @PutMapping("/{id}") public Employee update(@PathVariable String id, @RequestBody Employee employee) { employee.setId(id); return repository.save(employee); } @DeleteMapping("/{id}") public void delete(@PathVariable String id) { repository.deleteById(id); } }
posted on 2023-11-15 20:11 東方來(lái)客 閱讀(127) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)