一、使用redis缓存
1、导入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在项目application.yml中加入redis相关配置
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 0
3、新建redis的配置类,修改key序列化器
redis默认的序列化器生成的数据不便于查看
配置前:
配置后:
package com.mp.rj.config;
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 {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
//默认的Key序列化器为:JdkSerializationRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
3、业务场景下使用
@Resource
private RedisTemplate redisTemplate;
//将生成的验证码缓存到redis中,并设置有效期为5分钟
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//从redis中获取缓存的验证码
Object codeInRedis = redisTemplate.opsForValue().get(phone);
//如果用户登录成功,删除redis中缓存的验证码
redisTemplate.delete(phone);
4、分支下的优化测试无bug后合并回主分支
切换回主分支:idea右下角分支->master->checkout
将分支修改合并到主分支:idea右下角分支->修改的分支->mergeintocurrent
二、使用Spring Cache简化实现缓存功能
1、Spring Cache是一个框架,实现了基于注解的缓存功能。Spring Cache提供了一层抽象,底层可以切换不同的cache实现,具体就是通过CacheManager接口来提不同的缓存技术。CacheManager是Spring提供的各种缓存技术抽象接口。
2、使用redis缓存技术
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
3、配置application.yml
spring:
redis:
host: 127.0.0.1
port: 6379
password:
database: 0
cache:
redis:
time-to-live: 1800000 #设置缓存过期时间
2、启动类加入@EnableCaching注解开启缓存注解功能
3、在Controller的方法上加入@Cacheable、@CacheEvict等注解进行缓存操作