当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
Spring Data JPA为我们提供了下面的Serializer:
GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
我们自己配置RedisTemplate并定义Serializer。
package cxy.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; 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.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Autowired @Qualifier(value = "redisTemplate") private RedisTemplate redisTemplate; @Bean(name = "newRedisTemplate") public RedisTemplate<String, RedisCountDo> redisTemplate() { // 设置序列化 Jackson2JsonRedisSerializer<RedisCountDo> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(RedisCountDo.class); RedisSerializer stringSerializer = new StringRedisSerializer(); // key序列化 redisTemplate.setKeySerializer(stringSerializer); // value序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // Hash key序列化 redisTemplate.setHashKeySerializer(stringSerializer); // Hash value序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
使用先注入RedisConfig类
@Autowired private RedisConfig redisConfig;
然后使用方法仿照下面
@Test public void redisTest2() { RedisTemplate<String, RedisCountDo> redisTemplate = redisConfig.redisTemplate(); for (int i = 0; i < 4; i++) { // Long aLong = RandomUtil.randomLong(); Long aLong=541654546156L; String userId = new StringBuilder("AAA:BBB:").append(aLong).toString(); if (!redisTemplate.hasKey(userId)) { RedisCountDo redisCountDoSet = new RedisCountDo(new Date(), 10); redisTemplate.opsForValue().set(userId, redisCountDoSet, 1, TimeUnit.DAYS); } else { RedisCountDo redisCountDo = redisTemplate.opsForValue().get(userId); while (redisCountDo.getCount() == 0) { Long expire = redisTemplate.boundHashOps(userId).getExpire(); System.out.println(String.format("请求次数太多,请%s后再来", FormatTimeUtils.formatTime(expire))); System.exit(0); } redisCountDo.setCount(redisCountDo.getCount() - 1); redisTemplate.opsForValue().set(userId, redisCountDo, 0); System.out.println(redisCountDo); } } }
做 redisTemplate.opsForValue().set(userId, redisCountDoSet, 1, TimeUnit.DAYS);等这些读写操作.