Java基础 8.15

1.代码块练习

package com.logic.codeblock_;

public class CodeBlockExercise02 {

}

class Sample {
    Sample(String s) {
        System.out.println(s);
    }

    Sample() {
        System.out.println("Sample默认构造函数被调用");
    }
}

class Test {
    Sample sam1 = new Sample("sam1成员初始化");//注意 这个也是普通代码块
    static Sample sam = new Sample("静态成员sam初始化 ");//

    static {
        System.out.println("static块执行");//
        if (sam == null) System.out.println("sam is null");
    }

    Test()//构造器
    {
        System.out.println("Test默认构造函数被调用");//
    }

    //主方法
    public static void main(String str[]) {
        Test a = new Test();//无参构造器
    }

}



### Elasticsearch 8.15.5 和 Java 集成 #### 客户端库的选择 对于Elasticsearch 8.15.5与Java应用程序集成而言,官方推荐使用高阶客户端——即Elasticsearch JAVA High Level REST Client (HLRC),不过需要注意的是自Elasticsearch 7.16之后,该高级REST客户端已被弃用并建议迁移到新的API客户端[^3]。 #### Maven依赖配置 为了使项目能够顺利连接到Elasticsearch集群,在`pom.xml`文件中加入如下Maven依赖: ```xml <dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.15.5</version> </dependency> <!-- 如果还需要JSON支持 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency> ``` #### 创建Elasticsearch客户端实例 下面是一个简单的例子来展示如何初始化一个新的Elasticsearch API客户端对象用于后续操作: ```java import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; public class EsClientFactory { public static ElasticsearchClient createEsClient() throws Exception { RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http")).build(); // 使用Jackson作为默认的JSON处理器 var mapper = new JacksonJsonpMapper(); // 构建最终使用的ES客户端 return new ElasticsearchClient(mapper); } } ``` #### 执行基本CRUD操作 这里给出一段代码片段用来说明怎样通过上述构建好的客户端执行常见的增删改查命令: ```java // 假设已获得esClient实例 try { // 添加文档 IndexResponse indexResponse = esClient.index(i -> i .index("my-index") .id("1") .document(new MyDocument())); // 查询单个文档 GetResponse<MyDocument> getResponse = esClient.get(g -> g .index("my-index") .id("1"), MyDocument.class); // 更新现有记录 UpdateResponse updateResponse = esClient.update(u -> u .index("my-index") .id("1") .doc(Map.of("fieldToUpdate", newValue))); // 删除指定ID的数据项 DeleteResponse deleteResponse = esClient.delete(d -> d .index("my-index") .id("1")); } catch (IOException e) { throw new RuntimeException(e); } private record MyDocument(String fieldOne, Integer anotherField) {} ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值