springboot读取resources下的文件并写入redis

此代码示例展示了如何在SpringBoot应用中,定时从resources目录的`test/ezCar`文件中读取内容,查找包含"B1"和"B2"的行,并将找到的数据存入Redis缓存中。
摘要由CSDN通过智能技术生成

    public static void testBrake(){
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
        executorService.scheduleWithFixedDelay(new Runnable() {
            @SneakyThrows
            @Override
            public void run(){
                ClassPathResource classPathResource = new ClassPathResource("test/ezCar");
                InputStream inputStream = classPathResource.getInputStream();
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader br = new BufferedReader(isr);
                String data = null;
                String B1 = "";
                String B2 = "";
                while((data = br.readLine()) != null) {
                    if(data.contains("B1")){
              

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot项目启动时写入Redis,可以使用Spring Boot的启动事件来实现。下面是一个示例代码: 首先,创建一个监听器类,实现`ApplicationListener`接口,监听`ApplicationReadyEvent`事件,在项目启动完成后执行相应的操作: ```java import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisInitializer implements ApplicationListener<ApplicationReadyEvent> { private final RedisTemplate<String, String> redisTemplate; public RedisInitializer(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public void onApplicationEvent(ApplicationReadyEvent event) { // 在这里进行Redis写入操作 redisTemplate.opsForValue().set("key", "value"); } } ``` 在上面的代码中,我们使用了`RedisTemplate`来进行Redis的操作。你可以根据实际需求修改`set`方法的参数来写入不同的数据。 然后,确保你已经正确配置了Redis相关的依赖和连接信息。在`application.properties`(或`application.yml`)文件中,添加Redis的连接配置信息,例如: ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 最后,在你的Spring Boot项目中添加上述的监听器类,它会在项目启动完成后自动执行Redis写入操作。 这样,每次启动Spring Boot项目时,都会将数据写入Redis中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值