redisTemplate.opsForHash().entries("stars")利用springboot如何遍历写入MySQL
时间: 2023-05-24 16:06:44 浏览: 131
首先,需要获取RedisTemplate实例,可以在配置文件中进行配置:
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setDefaultSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
return redisTemplate;
}
}
```
然后定义一个服务类,用来处理Redis操作:
```
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
}
```
接着,定义一个DAO类,用来将Redis中的数据写入MySQL:
```
@Repository
public class StarDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void save(Map<Object, Object> map) {
String sql = "insert into stars(name, age, gender) values(?,?,?)";
for (Map.Entry<Object, Object> entry : map.entrySet()) {
HashMap<String, Object> star = (HashMap<String, Object>) entry.getValue();
jdbcTemplate.update(sql, star.get("name"), star.get("age"), star.get("gender"));
}
}
}
```
最后,在Controller中调用RedisService获取Redis中的数据,并将数据传递给DAO进行存储:
```
@RestController
public class StarController {
@Autowired
private RedisService redisService;
@Autowired
private StarDao starDao;
@GetMapping("/save-to-mysql")
public String saveToMysql() {
Map<Object, Object> map = redisService.getHash("stars");
starDao.save(map);
return "Success";
}
}
```
这样就可以成功将Redis中的数据写入到MySQL中。
阅读全文