SpringBoot读取配置文件中的数据到map和list

之前使用过@Value("${name}")来读取springboot配置文件中的配置信息,比如:

  @Value("${server.port}")
  private Integer port;

后面遇到一个新问题,如果我要把配置文件中的一系列数据一下子读出来到同一个数据结构中怎么办呢?
比如说读取配置信息到map或者list
下面来讲述一下如何实现这个功能。


springboot读取配置文件中的配置信息到map

首先看配置文件要读到map中的信息:

test:
  limitSizeMap:
    baidu: 1024
    sogou: 90
    hauwei: 4096
    qq: 1024

接着我们需要再maven的pom.xml文件中添加如下依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

然后定义一个配置类,代码如下:

package com.eknows.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

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

/**
 * 配置类
 * 从配置文件中读取数据映射到map
 * 注意:必须实现set方法
 * @author eknows
 * @version 1.0
 * @since 2019/2/
  • 8
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,这是一个比较复杂的问题,需要分步骤来进行回答。 首先需要在Spring Boot添加Kafka和MySQL的依赖,可以在pom.xml文件添加以下代码: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.2.7.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> ``` 接着需要在application.properties文件配置Kafka和MySQL的相关信息,例如: ```properties # Kafka配置 spring.kafka.bootstrap-servers=localhost:9092 spring.kafka.consumer.group-id=my-group # MySQL配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root ``` 然后在代码创建Kafka消费者,并使用@KafkaListener注解来监听指定的Topic主题,例如: ```java @Component public class KafkaConsumer { @Autowired private JdbcTemplate jdbcTemplate; @KafkaListener(topics = "my-topic", groupId = "my-group") public void consume(List<String> messages) { // 将数据分批写入MySQL数据库 int batchSize = 1000; int totalSize = messages.size(); for (int i = 0; i < totalSize; i += batchSize) { int endIndex = Math.min(i + batchSize, totalSize); List<String> batchMessages = messages.subList(i, endIndex); jdbcTemplate.batchUpdate("INSERT INTO my_table (message) VALUES (?)", batchMessages.stream().map(msg -> new Object[]{msg}).collect(Collectors.toList())); } } } ``` 最后在启动类添加@EnableKafka注解来启用Kafka消费者,例如: ```java @SpringBootApplication @EnableKafka public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ``` 这样就完成了多消费者从Kafka同一Topic主题批量读取数据,然后将数据分批写入到MySQL数据库的功能。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值