在 Spring Boot 中通过定时任务实现本地 Redis 数据同步到阿里云 Redis

  • 添加依赖 在项目的 pom.xml 文件中,添加 Spring Boot Starter 和 Redis 相关的依赖。
<!-- Spring Boot Starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- Spring Boot Starter for Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • 配置本地和阿里云 Redis 连接信息

  在 application.yml 文件中,配置本地和阿里云 Redis 的连接信息。  

spring:
  redis:
    host: localhost
    port: 6379
    aliyun-host: x.x.x.x
    aliyun-port: 6379
    aliyun-password: xxxxxx
  • 创建定时任务类

  创建一个定时任务类,用于执行本地 Redis 数据同步到阿里云 Redis 的操作。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class RedisSyncTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
  
    @Scheduled(fixedRate = 30000) // 每30秒执行一次
    public void syncDataToAliyunRedis() {
        String data = redisTemplate.opsForValue().get("myKey");
        
        // 将数据推送到阿里云 Redis
        redisTemplate.opsForValue().set("aliyun-myKey", data);
    }
}
  • 启用定时任务

  在主应用程序类中添加 @EnableScheduling 注解,以启用定时任务。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class RedisSyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisSyncApplication.class, args);
    }
}
  • 运行和验证

  补充:

 /**
     * @Scheduled(cron = "0/30 * * * * ?")
     * 解释如下
     * 秒:0/30 表示从0秒开始,每隔30秒执行一次。
     * 分:* 表示每分钟都执行。
     * 小时:* 表示每小时都执行。
     * 日期:* 表示每天都执行。
     * 月份:* 表示每个月都执行。
     * 星期:? 表示不关心星期几,因为日期已经指定了。
     * 年份:未指定,表示不考虑年份。
     */
    //@Scheduled(fixedRate = 30000) // 每30秒执行一次

 

 

/**
* @Scheduled(cron = "0/30 * * * * ?")
* 解释如下
* 秒:0/30 表示从0秒开始,每隔30秒执行一次。
* 分:* 表示每分钟都执行。
* 小时:* 表示每小时都执行。
* 日期:* 表示每天都执行。
* 月份:* 表示每个月都执行。
* 星期:? 表示不关心星期几,因为日期已经指定了。
* 年份:未指定,表示不考虑年份。
*/
//@Scheduled(fixedRate = 30000) // 30秒执行一次
posted @ 2023-08-17 21:37  小张在搬砖  阅读(135)  评论(0编辑  收藏  举报