springboot如何在redis里存入HashMap又取出HashMap
在Spring Boot中使用Redis存储HashMap可以通过使用RedisTemplate来实现。以下是一个示例:
- 首先,在pom.xml文件中添加Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 在application.properties中配置Redis连接信息:
spring.redis.host=localhost
spring.redis.port=6379
- 创建一个Redis配置类,用于配置RedisTemplate:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// 设置value的序列化器
template.setValueSerializer(jacksonSerializer);
template.setDefaultSerializer(jacksonSerializer);
template.afterPropertiesSet();
return template;
}
}
- 创建一个Service类,用于操作Redis:
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void saveHashMap(String key, HashMap<String, Object> hashMap) {
redisTemplate.opsForHash().putAll(key, hashMap);
}
public HashMap<String, Object> getHashMap(String key) {
return (HashMap<String, Object>) redisTemplate.opsForHash().entries(key);
}
}
- 在Controller中使用RedisService:
@RestController
public class MyController {
@Autowired
private RedisService redisService;
@PostMapping("/saveHashMap")
public void saveHashMap() {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
redisService.saveHashMap("myHashMap", hashMap);
}
@GetMapping("/getHashMap")
public HashMap<String, Object> getHashMap() {
return redisService.getHashMap("myHashMap");
}
}
这样,当调用/saveHashMap接口时,会将HashMap存储到Redis中;而调用/getHashMap接口时,会从Redis中取出HashMap
原文地址: http://www.cveoy.top/t/topic/iPgx 著作权归作者所有。请勿转载和采集!