Redis数据同步到Mysql

概述

秒杀系统中总需要在启动时将数据放到redis中,即缓存预热,在秒杀开始时则需要通过redis进行库存的扣减,为保证redis和mysql数据一致性,通过可通过定时任务将redis中的数据同步回mysql中

demo

我们知道Redis数据的key通常以类名:midKey:商品id进行设计,为此我们根据key取出数据来,更新到数据库即可

@Component
public class RedisToMySqlScheduled implements ApplicationRunner {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisUtil redisUtil;
	//map用来做数据的缓存
    private Map<Long,Boolean> map = new ConcurrentHashMap<>();

    @Scheduled(cron = "15 05 11 * * ? ")
    public void redisDataToMySql(){

        if (!map.isEmpty()){
            map.entrySet().forEach(entry->{

                Integer count = redisUtil.get(GoodsKey.getSecondKillGoodsStock, ":" + entry.getKey(), Integer.class);
                goodsService.redisToMysql(count,entry.getKey());
            });
        }

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
		//取出全部数据
        List<GoodsVo> goodsVos = goodsService.listGoodsVo();

        goodsVos.forEach(e->{
            map.put(e.getId(),false);
        });

    }
}

service

public int redisToMysql(Integer count,Long goodId){
		return goodsDao.redisDataToMysql(count,goodId);
	}

mapper

@Update("update second_goods set stock_count = #{stockCount} where goods_id = #{goodsId}")
	int redisDataToMysql(@Param("stockCount")Integer stockCount,@Param("goodsId")Long goodsId);

demo地址

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:使用springboot实现将redis数据同步MySQL可以采取以下步骤: 1. 配置pom.xml依赖,引入redisMySQL驱动。 2. 编写RedisRepository类,继承RedisTemplate,并实现将Redis数据转为MySQL数据的方法。 3. 编写MySQLRepository类,使用JdbcTemplate进行MySQL数据操作。 4. 编写同步服务类,使用注解@Scheduled定时任务,从RedisRepository获取Redis数据并转成MySQL数据,再存储到MySQLRepository中。 5. 在Springboot启动类中添加@EnableScheduling注解开启定时任务。 6. 运行程序,即可实现将Redis数据同步MySQL。 下面是示例代码: 1. pom.xml依赖配置 ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> </dependencies> ``` 2. RedisRepository类 ```java public class RedisRepository extends RedisTemplate<String, Object> { public RedisRepository(RedisConnectionFactory redisConnectionFactory) { setConnectionFactory(redisConnectionFactory); afterPropertiesSet(); } // 将Redis数据转为MySQL数据 public List<Map<String, Object>> redisToMysqlData() { List<Map<String, Object>> dataList = new ArrayList<>(); Cursor<Map.Entry<String, Object>> cursor = this.opsForHash().scan("redis_key", ScanOptions.NONE); while (cursor.hasNext()) { Map.Entry<String, Object> entry = cursor.next(); Map<String, Object> data = new HashMap<>(); data.put("id", entry.getKey()); data.put("value", entry.getValue()); dataList.add(data); } return dataList; } } ``` 3. MySQLRepository类 ```java public class MySQLRepository{ private final JdbcTemplate jdbcTemplate; public MySQLRepository(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); } // 存储MySQL数据 public void storeMysqlData(List<Map<String, Object>> dataList) { dataList.forEach(data -> { String sql = "INSERT INTO `mysql_table` (`id`, `value`) VALUES (?, ?)"; Object[] params = new Object[]{data.get("id"), data.get("value")}; jdbcTemplate.update(sql, params); }); } } ``` 4. 同步服务类 ```java @Service public class SyncService { private final RedisRepository redisRepository; private final MySQLRepository mySQLRepository; public SyncService(RedisRepository redisRepository, MySQLRepository mySQLRepository) { this.redisRepository = redisRepository; this.mySQLRepository = mySQLRepository; } // 定时任务,每5分钟同步一次 @Scheduled(cron = "0 */5 * * * ?") public void syncRedisToMySQL() { List<Map<String, Object>> dataList = redisRepository.redisToMysqlData(); mySQLRepository.storeMysqlData(dataList); } } ``` 5. 启动类添加@EnableScheduling注解 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样就完成了将Redis数据同步MySQL的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值