简介:
Redis(Remote Dictionary Server ):远程字典服务, 是一个key-value数据库
安装:
https://github.com/tporadowski/redis/releases
打开直接下载zip压缩包解压即可
解压后:
打开命令框(终端)开始运行redis
redis-server.exe redis.windows.conf
导入依赖:
pom.xml:
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.1</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置yml:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test
redis:
host: 127.0.0.1
port: 6379
password:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 30000
#打印数据库语句
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
port: 9999
添加工具类:
redis工具类:
/**
* @author Jkchen
* @description: redis工具类$
* @date 2021/10/20 16:04
*/
@Component
public class RedisUtil {
@Autowired
RedisTemplate<Object,Object> redisTemplate;
//存入数据到缓存
public void setValue(String key,Object value){
redisTemplate.opsForValue().set(key,value);
}
//通过key 获得数据
public Object getValue(String key){
return redisTemplate.opsForValue().get(key);
}
//存入数据到缓存并设置过期时间(单位为秒)
public void setValuesAndExpire(String key,Object value,long time){
redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
}
//删除缓存
public void delete(String key){
redisTemplate.delete(key);
}
}
redis配置类:
/**
* @author Jkchen
* @description: Redis配置
* @date 2021/10/21 15:56
*/
@Configuration
public class RedisConfig {
// 使用Jackson2JsonRedisSerialize替换默认JDK序列化
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// key采用String的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
// hash的key也采用String的序列化方式
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// value序列化方式采用jackson
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// hash的hash的value序列化方式采用jackson
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
测试:
根据id查询信息
@Override
public Object findById(int id) {
//根据key查询缓存
User user = (User) redisUtil.getValue("userKey" + id);
//判断是否为空
if(user==null){
//缓存为空
user=userMapper.selectById(id);
System.out.println("缓存为空查询数据库");
//插入缓存并且设置过期时间(单位为秒)
redisUtil.setValuesAndExpire("userKey"+id,user,30);
System.out.println("插入缓存");
}else{
System.out.println("从redis里取出");
}
return user;
}