编写一个Map入参构建的工具类

本文介绍了在编程中遇到需要构建Map作为参数的场景时,如何通过编写工具类来提高代码的优雅性和可读性。首先展示了传统方式构建Map的不便利,然后提出并实现了一个简单的工具类,利用Builder模式隐藏内部Map的操作,避免直接暴露put和remove方法,同时也防止该工具类被继承。这种实践来源于《Effective Java》一书中的知识,旨在提升编码深度和设计模式的应用。
摘要由CSDN通过智能技术生成

使用场景
       比如我们在调用某个Http业务接口,或者调用一个入参为Map类型参数方法根据条件查询数据,对于此种情况,Map中的key值得个数是根据业务需求而不同的,而且当需要向业务接口或者方法参数多个条件的时候,这时我们使用原生的map.put()就显得代码不优雅,可能我们的代码会是类似下面这样:

Map<String, String> mapParam = new HashMap<>();
mapParam.put("key1", "value1");
mapParam.put("key2", "value2");
mapParam.put("key3", "value3");
mapParam.put("key4", "value4");
mapParam.put("key5", "value5");
mapParam.put("key6", "value6");

下面编写一个简单的工具类来使得构建map参数的过程变得优雅好看些,代码如下

package com.zhegui.utils.builders;

import java.util.HashMap;
import java.util.Map;

/**
 * 一个简单的mapParam构建器
 * @author Zhegui
 *
 * @param <K>
 * @param <V>
 */
public class MapParamBuilder<K, V>{
   

    private Map<K,V> mapParam;

    /**
     * 默认构造函数
     */
    public MapParamBuilder(){
        mapParam = ne
好的,以下是一个简单的操作 Elasticsearch 的工具类,使用的是 Elasticsearch 官方提供的 Java 客户端——Elasticsearch Rest High Level Client。 首先,需要添加 Elasticsearch Rest High Level Client 的依赖: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.10.2</version> </dependency> ``` 然后,就可以编写 Elasticsearch 操作的工具类了: ```java import org.apache.http.HttpHost; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import java.util.List; public class ElasticsearchUtil { private RestHighLevelClient client; public ElasticsearchUtil(String host, int port) { client = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port))); } /** * 插入数据 * * @param index 索引名称 * @param id 文档ID * @param document 文档内容,可以是 JSON 字符串或者 Map、XContentBuilder 对象 * @return 插入结果 */ public IndexResponse insert(String index, String id, Object document) throws IOException { IndexRequest request = new IndexRequest(index).id(id).source(document, XContentType.JSON); return client.index(request); } /** * 更新数据 * * @param index 索引名称 * @param id 文档ID * @param document 文档内容,可以是 JSON 字符串或者 Map、XContentBuilder 对象 * @return 更新结果 */ public UpdateResponse update(String index, String id, Object document) throws IOException { UpdateRequest request = new UpdateRequest(index, id).doc(document, XContentType.JSON); return client.update(request); } /** * 删除数据 * * @param index 索引名称 * @param id 文档ID * @return 删除结果 */ public DeleteResponse delete(String index, String id) throws IOException { DeleteRequest request = new DeleteRequest(index, id); return client.delete(request); } /** * 根据ID查询数据 * * @param index 索引名称 * @param id 文档ID * @return 查询结果 */ public GetResponse getById(String index, String id) throws IOException { GetRequest request = new GetRequest(index, id); return client.get(request); } /** * 根据条件查询数据 * * @param index 索引名称 * @param query 查询条件,可以使用 QueryBuilders 类构建 * @return 查询结果 */ public SearchResponse search(String index, QueryBuilders query) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(query); SearchRequest request = new SearchRequest(index).source(searchSourceBuilder); return client.search(request); } /** * 批量插入数据 * * @param index 索引名称 * @param documents 文档列表,每个元素可以是 JSON 字符串或者 Map、XContentBuilder 对象 * @param batchSize 批量大小 * @param retryTimes 失败重试次数 * @return 批量插入结果 */ public BulkResponse bulkInsert(String index, List<Object> documents, int batchSize, int retryTimes) throws IOException { BulkRequest request = new BulkRequest(); for (int i = 0; i < documents.size(); i++) { request.add(new IndexRequest(index).source(documents.get(i), XContentType.JSON)); if ((i + 1) % batchSize == 0 || i == documents.size() - 1) { boolean success = false; int retry = 0; while (!success && retry < retryTimes) { BulkResponse response = client.bulk(request); if (response.hasFailures()) { retry++; } else { success = true; return response; } } request.requests().clear(); } } return null; } /** * 关闭 Elasticsearch 客户端 */ public void close() throws IOException { client.close(); } } ``` 使用时只需要创建一个 ElasticsearchUtil 对象,然后调用相应的方法即可: ```java public static void main(String[] args) throws IOException { ElasticsearchUtil util = new ElasticsearchUtil("localhost", 9200); // 插入数据 String document = "{\"name\":\"张三\",\"age\":20}"; IndexResponse response = util.insert("test", "1", document); System.out.println(response.getResult().name()); // 更新数据 document = "{\"name\":\"李四\",\"age\":25}"; UpdateResponse updateResponse = util.update("test", "1", document); System.out.println(updateResponse.getResult().name()); // 查询数据 GetResponse getResponse = util.getById("test", "1"); System.out.println(getResponse.getSourceAsString()); // 删除数据 DeleteResponse deleteResponse = util.delete("test", "1"); System.out.println(deleteResponse.getResult().name()); // 条件查询数据 QueryBuilders query = QueryBuilders.matchQuery("name", "张三"); SearchResponse searchResponse = util.search("test", query); System.out.println(searchResponse.getHits().getTotalHits().value); // 批量插入数据 List<Object> documents = new ArrayList<>(); for (int i = 0; i < 10000; i++) { documents.add("{\"name\":\"张三\",\"age\":20}"); } BulkResponse bulkResponse = util.bulkInsert("test", documents, 100, 3); System.out.println(bulkResponse.hasFailures()); util.close(); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值