一、移动端项目存在的问题
1.1 移动端项目存在的问题
移动端是面向所有的消费者的,请求压力相对比较大,如果所有的数据查询都是从数据库MySQL中直接查询的,那么可能就存在如下问题: 频繁访问数据库,数据库访问压力大,系统性能下降,用户体验较差。
1.2 解决该问题的方法
要解决我们上述提到的问题,就可以使用Redis,通过Redis来做缓存,从而降低数据库的访问压力,提高系统的访问性能,从而提升用户体验。加入Redis做缓存之后,我们在进行数据查询时,就需要先查询缓存,如果缓存中有数据,直接返回,如果缓存中没有数据,则需要查询数据库,再将数据库查询的结果,缓存在redis中。
二、项目使用Redis缓存
step1). 在项目的pom.xml文件中导入spring data redis的maven坐标
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
step2). 在项目的application.yml中加入redis相关配置
redis:host: 192.168.200.200port: 6379password: root@123456database: 0
step3). 编写Redis的配置类RedisConfig,定义RedisTemplate
import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration public class RedisConfig extends CachingConfigurerSupport {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;} }
step4). 使用Redis缓存、获取、删除手机短信验证码
//将生成的验证码保存到Redis,并设置过期时间 redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);//从Redis中获取缓存的验证码 Object codeInSession = redisTemplate.opsForValue().get(phone);//从Redis中删除缓存的验证码 redisTemplate.delete(phone);