SpringBoot框架无需进行复杂整合,可使用SpringBoot依赖所引入的 org.springframework.data.redis.core.RedisTemplate来直接进行操作,但需要一些特殊的配置:
配置类中,实例化时需要进行序列化配置:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.connection.RedisConnectionFactory; @Configuration public class RedisConfig { /** * 实例化 RedisTemplate 对象 * * @return */ @Bean public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); initDomainRedisTemplate(redisTemplate, redisConnectionFactory); return redisTemplate; } /** * 设置数据存入 redis 的序列化方式,并开启事务 * * @param redisTemplate * @param factory */ private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) { // 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String! redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 开启事务 redisTemplate.setEnableTransactionSupport(true); redisTemplate.setConnectionFactory(factory); } }
使用其进行Map的操作
@Resource private RedisTemplate<String,Object> template; public void setKey(String key, Map<String, Object> map) { this.template.opsForHash().putAll(key, map); } public Map<Object, Object> getMapValue(String key) { return this.template.opsForHash().entries(key); } public Object getValue(String key, String hashKey) { return this.template.opsForHash().get(key, hashKey); } public void deleteData(List<String> keys) { // 执行批量删除操作时先序列化template template.setKeySerializer(new JdkSerializationRedisSerializer()); template.delete(keys); }