SpringBoot+Elasticsearch实现数据搜索的方法详解

目录
  • 一、简介
  • 二、代码实践
    • 2.1、导入依赖
    • 2.2、配置环境变量
    • 2.3、创建 elasticsearch 的 config 类
    • 2.4、索引管理
    • 2.5、文档管理
  • 三、小结

一、简介

在上篇 ElasticSearch 文章中,我们详细的介绍了 ElasticSearch 的各种 api 使用。

实际的项目开发过程中,我们通常基于某些主流框架平台进行技术开发,比如 SpringBoot,今天我们就以 SpringBoot 整合

ElasticSearch 为例,给大家详细的介绍 ElasticSearch 的使用!

SpringBoot 连接 ElasticSearch,主流的方式有以下四种方式

  • 方式一:通过Elastic Transport Client客户端连接 es 服务器,底层基于 TCP 协议通过 transport 模块和远程 ES 服务端通信,不过,从 V7.0 开始官方不建议使用,V8.0开始正式移除。
  • 方式二:通过Elastic Java Low Level Rest Client客户端连接 es 服务器,底层基于 HTTP 协议通过 restful API 来和远程 ES 服务端通信,只提供了最简单最基本的 API,类似于上篇文章中给大家介绍的 API 操作逻辑。
  • 方式三:通过Elastic Java High Level Rest Client客户端连接 es 服务器,底层基于Elastic Java Low Level Rest Client客户端做了一层封装,提供了更高级得 API 且和Elastic Transport Client接口及参数保持一致,官方推荐的 es 客户端。
  • 方式四:通过JestClient客户端连接 es 服务器,这是开源社区基于 HTTP 协议开发的一款 es 客户端,官方宣称接口及代码设计比 ES 官方提供的 Rest 客户端更简洁、更合理,更好用,具有一定的 ES 服务端版本兼容性,但是更新速度不是很快,目前 ES 版本已经出到 V7.9,但是JestClient只支持 V1.0~V6.X 版 本的 ES。

还有一个需要大家注意的地方,那就是版本号的兼容!

在开发过程中,大家尤其需要关注一下客户端和服务端的版本号,要尽可能保持一致,比如服务端 es 的版本号是6.8.2,那么连接 es 的客户端版本号,最好也是6.8.2,即使因项目的原因不能保持一致,客户端的版本号必须在6.0.0 ~6.8.2,不要超过服务器的版本号,这样客户端才能保持正常工作,否则会出现很多意想不到的问题,假如客户端是7.0.4的版本号,此时的程序会各种报错,甚至没办法用!

为什么要这样做呢?主要原因就是 es 的服务端,高版本不兼容低版本;es6 和 es7 的某些 API 请求参数结构有着很大的区别,所以客户端和服务端版本号尽量保持一致。

废话也不多说了,直接上代码!

二、代码实践

本文采用的SpringBoot版本号是2.1.0.RELEASE,服务端 es 的版本号是6.8.2,客户端采用的是官方推荐的Elastic Java High Level Rest Client版本号是6.4.2,方便与SpringBoot的版本兼容。

2.1、导入依赖

<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.4.2</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>6.4.2</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.4.2</version>
</dependency>

2.2、配置环境变量

在application.properties全局配置文件中,配置elasticsearch自定义环境变量。

elasticsearch.scheme=http
elasticsearch.address=127.0.0.1:9200
elasticsearch.userName=
elasticsearch.userPwd=
elasticsearch.socketTimeout=5000
elasticsearch.connectTimeout=5000
elasticsearch.connectionRequestTimeout=5000

2.3、创建 elasticsearch 的 config 类

@Configuration
public class ElasticsearchConfiguration {

    private static final Logger log = LoggerFactory.getLogger(ElasticsearchConfiguration.class);

    private static final int ADDRESS_LENGTH = 2;

    @Value("${elasticsearch.scheme:http}")
    private String scheme;

    @Value("${elasticsearch.address}")
    private String address;

    @Value("${elasticsearch.userName}")
    private String userName;

    @Value("${elasticsearch.userPwd}")
    private String userPwd;

    @Value("${elasticsearch.socketTimeout:5000}")
    private Integer socketTimeout;

    @Value("${elasticsearch.connectTimeout:5000}")
    private Integer connectTimeout;

    @Value("${elasticsearch.connectionRequestTimeout:5000}")
    private Integer connectionRequestTimeout;

    /**
     * 初始化客户端
     * @return
     */
    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restClientBuilder() {
        HttpHost[] hosts = Arrays.stream(address.split(","))
                .map(this::buildHttpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
        RestClientBuilder restClientBuilder = RestClient.builder(hosts);
        // 异步参数配置
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setDefaultCredentialsProvider(buildCredentialsProvider());
            return httpClientBuilder;
        });

        // 异步连接延时配置
        restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
            requestConfigBuilder.setSocketTimeout(socketTimeout);
            requestConfigBuilder.setConnectTimeout(connectTimeout);
            return requestConfigBuilder;
        });

        return new RestHighLevelClient(restClientBuilder);
    }

    /**
     * 根据配置创建HttpHost
     * @param s
     * @return
     */
    private HttpHost buildHttpHost(String s) {
        String[] address = s.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            return new HttpHost(ip, port, scheme);
        } else {
            return null;
        }
    }

    /**
     * 构建认证服务
     * @return
     */
    private CredentialsProvider buildCredentialsProvider(){
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName,
                userPwd));
        return credentialsProvider;
    }
}

至此,客户端配置完毕,项目启动的时候,会自动注入到Spring的ioc容器里面。

2.4、索引管理

es 中最重要的就是索引库,客户端如何创建呢?请看下文!

创建索引

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 创建索引(简单模式)
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("cs_index");
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

    /**
     * 创建索引(复杂模式)
     * 可以直接把对应的文档结构也一并初始化
     * @throws IOException
     */
    @Test
    public void createIndexComplete() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest();
        //索引名称
        request.index("cs_index");
        //索引配置
        Settings settings = Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 1)
                .build();
        request.settings(settings);

        //映射结构字段
        Map<String, Object> properties = new HashMap();
        properties.put("id", ImmutableBiMap.of("type", "text"));
        properties.put("name", ImmutableBiMap.of("type", "text"));
        properties.put("sex", ImmutableBiMap.of("type", "text"));
        properties.put("age", ImmutableBiMap.of("type", "long"));
        properties.put("city", ImmutableBiMap.of("type", "text"));
        properties.put("createTime", ImmutableBiMap.of("type", "long"));
        Map<String, Object> mapping = new HashMap<>();
        mapping.put("properties", properties);
        //添加一个默认类型
        System.out.println(JSON.toJSONString(request));
        request.mapping("_doc",mapping);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

}

删除索引

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 删除索引
     * @throws IOException
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("cs_index1");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

}

查询索引

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 查询索引
     * @throws IOException
     */
    @Test
    public void getIndex() throws IOException {
        // 创建请求
        GetIndexRequest request = new GetIndexRequest();
        request.indices("cs_index");
        // 执行请求,获取响应
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

}

查询索引是否存在

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 检查索引是否存在
     * @throws IOException
     */
    @Test
    public void exists() throws IOException {
        // 创建请求
        GetIndexRequest request = new GetIndexRequest();
        request.indices("cs_index");
        // 执行请求,获取响应
        boolean response = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

}

查询所有的索引名称

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 查询所有的索引名称
     * @throws IOException
     */
    @Test
    public void getAllIndices() throws IOException {
        GetAliasesRequest request = new GetAliasesRequest();
        GetAliasesResponse response =  client.indices().getAlias(request,RequestOptions.DEFAULT);
        Map<String, Set<AliasMetaData>> map = response.getAliases();
        Set<String> indices = map.keySet();
        for (String key : indices) {
            System.out.println(key);
        }
    }

}

查询索引映射字段

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 查询索引映射字段
     * @throws IOException
     */
    @Test
    public void getMapping() throws IOException {
        GetMappingsRequest request = new GetMappingsRequest();
        request.indices("cs_index");
        request.types("_doc");
        GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

}

添加索引映射字段

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 添加索引映射字段
     * @throws IOException
     */
    @Test
    public void addMapping() throws IOException {
        PutMappingRequest request = new PutMappingRequest();
        request.indices("cs_index");
        request.type("_doc");

        //添加字段
        Map<String, Object> properties = new HashMap();
        properties.put("accountName", ImmutableBiMap.of("type", "keyword"));
        Map<String, Object> mapping = new HashMap<>();
        mapping.put("properties", properties);
        request.source(mapping);
        PutMappingResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

}

2.5、文档管理

所谓文档,就是向索引里面添加数据,方便进行数据查询,详细操作内容,请看下文!

添加文档

ublic class UserDocument {

    private String id;
    private String name;
    private String sex;
    private Integer age;
    private String city;
    private Date createTime;

    //省略get、set...
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 添加文档
     * @throws IOException
     */
    @Test
    public void addDocument() throws IOException {
        // 创建对象
        UserDocument user = new UserDocument();
        user.setId("1");
        user.setName("里斯");
        user.setCity("武汉");
        user.setSex("男");
        user.setAge(20);
        user.setCreateTime(new Date());

        // 创建索引,即获取索引
        IndexRequest request = new IndexRequest();
        // 外层参数
        request.id("1");
        request.index("cs_index");
        request.type("_doc");
        request.timeout(TimeValue.timeValueSeconds(1));
        // 存入对象
        request.source(JSON.toJSONString(user), XContentType.JSON);
        // 发送请求
        System.out.println(request.toString());
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

}

更新文档

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 更新文档(按需修改)
     * @throws IOException
     */
    @Test
    public void updateDocument() throws IOException {
        // 创建对象
        UserDocument user = new UserDocument();
        user.setId("2");
        user.setName("程咬金");
        user.setCreateTime(new Date());
        // 创建索引,即获取索引
        UpdateRequest request = new UpdateRequest();
        // 外层参数
        request.id("2");
        request.index("cs_index");
        request.type("_doc");
        request.timeout(TimeValue.timeValueSeconds(1));
        // 存入对象
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        // 发送请求
        System.out.println(request.toString());
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

}

删除文档

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 删除文档
     * @throws IOException
     */
    @Test
    public void deleteDocument() throws IOException {
        // 创建索引,即获取索引
        DeleteRequest request = new DeleteRequest();
        // 外层参数
        request.id("1");
        request.index("cs_index");
        request.type("_doc");
        request.timeout(TimeValue.timeValueSeconds(1));
        // 发送请求
        System.out.println(request.toString());
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

}

查询文档是不是存在

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 查询文档是不是存在
     * @throws IOException
     */
    @Test
    public void exists() throws IOException {
        // 创建索引,即获取索引
        GetRequest request = new GetRequest();
        // 外层参数
        request.id("3");
        request.index("cs_index");
        request.type("_doc");
        // 发送请求
        System.out.println(request.toString());
        boolean response = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }
}

通过 ID 查询指定文档

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 通过ID,查询指定文档
     * @throws IOException
     */
    @Test
    public void getById() throws IOException {
        // 创建索引,即获取索引
        GetRequest request = new GetRequest();
        // 外层参数
        request.id("1");
        request.index("cs_index");
        request.type("_doc");
        // 发送请求
        System.out.println(request.toString());
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }
}

批量添加文档

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class DocJunit {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 批量添加文档
     * @throws IOException
     */
    @Test
    public void batchAddDocument() throws IOException {
        // 批量请求
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(10));
        // 创建对象
        List<UserDocument> userArrayList = new ArrayList<>();
        userArrayList.add(new UserDocument("张三", "男", 30, "武汉"));
        userArrayList.add(new UserDocument("里斯", "女", 31, "北京"));
        userArrayList.add(new UserDocument("王五", "男", 32, "武汉"));
        userArrayList.add(new UserDocument("赵六", "女", 33, "长沙"));
        userArrayList.add(new UserDocument("七七", "男", 34, "武汉"));
        // 添加请求
        for (int i = 0; i < userArrayList.size(); i++) {
            userArrayList.get(i).setId(String.valueOf(i));
            IndexRequest indexRequest = new IndexRequest();
            // 外层参数
            indexRequest.id(String.valueOf(i));
            indexRequest.index("cs_index");
            indexRequest.type("_doc");
            indexRequest.timeout(TimeValue.timeValueSeconds(1));
            indexRequest.source(JSON.toJSONString(userArrayList.get(i)), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 执行请求
        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

}

三、小结

本文主要围绕 SpringBoot 整合 ElasticSearch 接受数据的插入和搜索使用技巧,在实际的使用过程中,版本号尤其的重要,不同版本的 es,对应的 api 是不一样的。

以上就是SpringBoot+Elasticsearch实现数据搜索的方法详解的详细内容,更多关于SpringBoot Elasticsearch数据搜索的资料请关注我们其它相关文章!

(0)

相关推荐

  • SpringBoot整合ElasticSearch的示例代码

    ElasticSearch作为基于Lucene的搜索服务器,既可以作为一个独立的服务部署,也可以签入Web应用中.SpringBoot作为Spring家族的全新框架,使得使用SpringBoot开发Spring应用变得非常简单.本文要介绍如何整合ElasticSearch与SpringBoot. 实体设计: 每一本书(Book)都属于一个分类(Classify),都有一个作者(Author). 生成这个三个实体类,并实现其get和set方法. SpringBoot配置修改: 1.修改pom.xm

  • SpringBoot整合ElasticSearch实践

    本节我们基于一个发表文章的案例来说明SpringBoot如何elasticsearch集成.elasticsearch本身可以是一个独立的服务,也可以嵌入我们的web应用中,在本案例中,我们讲解如何将elasticsearch嵌入我们的应用中. 案例背景:每个文章(Article)都要属于一个教程(Tutorial),而且每个文章都要有一个作者(Author). 一.实体设计: Tutorial.java public class Tutorial implements Serializable

  • SpringBoot整合ES-Elasticsearch的实例

    目录 概述 添加Maven依赖 配置application.yml 创建索引对象 SpringBoot操作ES数据的三种方式 实现索引对应的Repository 文档操作 文档保存.查询.删除 分页查询与滚动查询 ES深度分页 vs 滚动查询 SpringBoot集成ES基本使用 在test中测试 概述 本文介绍 Spring Boot 项目中整合 ElasticSearch 并实现 CRUD 操作,包括分页.滚动等功能. 添加Maven依赖 <dependency>       <gr

  • SpringBoot集成Elasticsearch过程实例

    1. 准备工作 需要提前安装好Elasticsearch,访问地址:http://127.0.0.1:9200/ 得到以下结果,得到cluster_name,下面配置使用. { "name" : "O8GslS3", "cluster_name" : "docker-cluster", "cluster_uuid" : "pviTqfXtR3GtnxF-Po-_aA", "ve

  • SpringBoot集成ElasticSearch的示例代码

    目录 一.Elasticseach介绍 1.简单介绍 2.对比关系: 3.详细说明: 4.查出数据的解释 二.SpringBoot集成Elasticseach 1.引入依赖 2.添加配置 3.创建pojo类与索引对应 4.SpringData封装了基础的增删改查,自定义增删改查 5.测试方法--增删改查 一.Elasticseach介绍 1.简单介绍 官网:开源搜索:Elasticsearch.ELK Stack 和 Kibana 的开发者 | Elastic https://www.elast

  • SpringBoot+Elasticsearch实现数据搜索的方法详解

    目录 一.简介 二.代码实践 2.1.导入依赖 2.2.配置环境变量 2.3.创建 elasticsearch 的 config 类 2.4.索引管理 2.5.文档管理 三.小结 一.简介 在上篇 ElasticSearch 文章中,我们详细的介绍了 ElasticSearch 的各种 api 使用. 实际的项目开发过程中,我们通常基于某些主流框架平台进行技术开发,比如 SpringBoot,今天我们就以 SpringBoot 整合 ElasticSearch 为例,给大家详细的介绍 Elast

  • SpringBoot+WebSocket实现即时通讯的方法详解

    目录 环境信息 服务端实现 导入依赖 创建配置类 创建一个注解式的端点并在其中通过配套注解声明回调方法 服务端主动发送消息给客户端 客户端实现 Java客户端实现 在前端环境(vue)中使用websocket 环境信息 名称 版本号 Spring Boot 2.4.5 Idea 2021.3.2 服务端实现 导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp

  • SpringBoot使用freemarker导出word文件方法详解

    目录 1.前言 2.需求说明 3.编码 3.1.导入依赖 3.2.接口编写 3.3.工具类 3.4.ftl文件 3.5.测试 4.word转pdf 5.总结 1.前言 在项目中我们有时间需要根据一个word模板文档,批量生成其他的word文档,里面的有些值改变一下而已,那怎么做呢? 2.需求说明 假如说,现在我有个模板文档,内容如下: 现在上面文档里面有如下变量: username:员工姓名 idno:身份证号码 hireDate:入职日期 work:职位 endDate:离职日期 现在我需要针

  • SpringBoot注入配置文件的3种方法详解

    这篇文章主要介绍了SpringBoot注入配置文件的3种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 方案1:@ConfigurationProperties+@Component 定义spring的一个实体bean装载配置文件信息,其它要使用配置信息是注入该实体bean /** * 将配置文件中配置的每一个属性的值,映射到这个组件中 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配

  • SpringBoot结合Redis实现序列化的方法详解

    目录 前言 配置类 配置 Jackson2JsonRedisSerializer 序列化策略 配置  RedisTemplate 配置缓存策略 测试代码 完整代码 前言 最近在学习Spring Boot结合Redis时看了一些网上的教程,发现这些教程要么比较老,要么不知道从哪抄得,运行起来有问题.这里分享一下我最新学到的写法 默认情况下,Spring 为我们提供了一个 RedisTemplate 来进行对 Redis 的操作,但是 RedisTemplate 默认配置的是使用Java本机序列化.

  • SpringBoot实现登录拦截器的方法详解

    在项目目录下建立两个包:inter 与contsfig 在inter新建层中实现HandlerInterceptor的继承类 package com.example.gameboxadminserver.inter; import com.example.gameboxadminserver.entity.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.

  • Spring中自定义数据类型转换的方法详解

    目录 类型转换服务 实现Converter接口 实现ConverterFactory接口 实现GenericConverter接口 环境:Spring5.3.12.RELEASE. Spring 3引入了一个core.onvert包,提供一个通用类型转换系统.系统定义了一个SPI来实现类型转换逻辑,以及一个API来在运行时执行类型转换.在Spring容器中,可以使用这个系统作为PropertyEditor实现的替代,将外部化的bean属性值字符串转换为所需的属性类型.还可以在应用程序中需要类型转

  • SpringBoot注入自定义的配置文件的方法详解

    目录 一.简介 二.代码实践 2.1 通过@value注解实现参数加载 2.2 通过@ConfigurationProperties注解实现参数加载 2.3 通过@PropertySource注解实现配置文件加载 2.4 通过自定义环境处理类,实现配置文件的加载 2.5 最后,我们来介绍一下yml文件读取 一.简介 在实际的项目开发过程中,我们经常需要将某些变量从代码里面抽离出来,放在配置文件里面,以便更加统一.灵活的管理服务配置信息.比如,数据库.eureka.zookeeper.redis.

  • Java实现自定义Excel数据排序的方法详解

    目录 1.引入jar包 2.自定义排序 通常,我们可以在Excel中对指定列数据执行升序或者降序排序,排序时可依据单元格中的数值.单元格颜色.字体颜色或图标等.在需要自定义排序情况下,我们也可以自行根据排序需要编辑数据排列顺序.本文,将通过Java应用程序来实现如何自定义排序. 1.引入jar包 使用jar包:Spire.Xls.jar version: 12.8.4 导入方法1:手动下载jar到本地,解压,然后找到lib文件夹下的Spire.Xls.jar文件.然后在IDEA中打开“Proje

  • SpringBoot实现项目文件上传的方法详解

    目录 一.首先抛出问题 二.解决思路 三.直接看源码就懂了,下面是controller 四.结尾 一.首先抛出问题 以阿里云oss文件上传为例,假设我的需求是这样的,我需要发布一条动态,这条动态呢可以是图片.语音.视频,3种类型,每种类型的上传我必须要限制它的文件大小,超过了我就不能让他上传的.如果传统的方式,那就是创建3个上传类型bucket对应图片.语音和视频,其实这种做法是可以的,但是怎么说呢,还不够优雅,如果当这个动态有越来越多种类型,你是不是要建立N个类型对应呢,所以就会使得bucke

随机推荐