一、引入redis的依赖,内容如下:
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、配置文件
1、在application.yml配置文件的配置内容如下:
#redis的一些配置
redis:
# Redis服务器连接端口
port: 6379
# Redis服务器地址
host: 127.0.0.1
# Redis数据库索引(默认为0)
database: 0
# Redis服务器连接密码(默认为空)
password:
# 连接池最大连接数(使用负值表示没有限制)
pool:
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 5000ms
2、 在application.properties配置文件的配置内容如下:
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000ms
3、以上配置完成后就可以使用redis存取数据了。
三、在springboot中如何使用redis(连接池自动管理,提供了一个高度封装的“RedisTemplate”类)
1、首先使用@Autowired注入RedisTemplate(后面直接使用,就不特殊说明)
@Autowired
private RedisTemplate redisTemplate;
2、然后Redistemplage类中的方法就都可以使用,常用的方法如下:
参考:博客地址: https://blog.youkuaiyun.com/sinat_22797429/article/details/89196933
四、如果使用redisDesktopManager工具中出现乱码(序列化)的情况的话,可以将RedisTemplate类的重写,如下:
1、在实体类的同级目录下新建一个redis的包(其他地方也可)
2、在redis的包中新建类RedisConfig,类内容如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration //这个注释就相当于一个配置文件的作用
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory connectionFactory){
RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
//1、解决key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//2、解决value序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
return redisTemplate;
}
}