之前学习了redis,知道其是非关系型数据库,而且读写操作很快并且能够实现持久化。但在项目中很少用到redis,最近刚好用到redis,加以记录。如果后期再遇到会持续更新。redis 操作很简单,对应用场景加以记录。
1 redis 做缓存,redis中一般适合存储什么类型的数据: 经常查询,不经常写入的数据,且数据不是特别重要。
1.1 首先导入相关依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
1.2创建redis 缓存配置类,配置插件 写法固定,不用去写
package com.boshrong.base.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@EnableCaching
@Configuration
public class redisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
1.3 在配置文件中配置redis 地址等配置信息
spring
redis:
host: 127.0.0.1
port: 6379
database: 0
timeout: 1800000
# 设置最大连接数
lettuce:
pool:
max-active: 20
max-wait: -1
# 最大阻塞等待时间 负数表示没有限制
max-idle: 5
min-idle: 0
1.4在接口中添加redis 缓存
在要使用redis 缓存的方法上添加相应注解, 将注解@Cacheable(key = “‘lession’”,value = “8”)加到方法上。
比如说我要查询 比较热门的八门课程。在其接口上加上相应的注解。
@ApiOperation("查询8门热门课程")
@GetMapping("getLession8")
@Cacheable(key = "'lession'",value = "8")
public Result getLession8(){
QueryWrapper<EduCourse> wrapper=new QueryWrapper<>();
wrapper.orderByDesc("view_count");
wrapper.last("limit 8");
List<EduCourse> list=eduCourseService.list(wrapper);
return Result.sucess().data("data",list);
}
redis 会根据注解的key 和value 生成redis 中的key ,生成规则一部分源码如下:
可以看到中间加了:: ,key 对应value 就是我们接口返回的值。
每次当我们去访问该接口的时候,先去redis 中找,redis 中没有再去数据库中找相关数据。返回并放入redis。
场景2 redis 做短信验证功能时间限制。
在实际应用中,每当用户在注册的时候需要短信验证。短信验证需要时效性。我们可以将生成的验证码放在redis中,并设置过期时间。
在springboot下我们使用redisTemplate来进行相关操作,只需要注入就行。
@Autowired
RedisTemplate<String,String> redisTemplate;
我们将手机号作为key,生成的验证码作为value ,设置5分钟过期时间,将其放入redis中。
redisTemplate.opsForValue().set(iphoneNumber, code, 5, TimeUnit.MINUTES);
在用户注册时,从redis中获取值与用户输入的值,没有获取到说明以失效,不一致说明输入错误
Object redisCode=redisTemplate.opsForValue().get(mobile);