文章目录
一、安装redis
1.1 安装redis
sudo apt-get update
sudo apt-get install redis-server
1.2 启动redis
redis-server
1.3 查看redis是否启动
redis-cli
1.4 redis端口
6379
二、使用redis
2.1 添加依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2.2 redis配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.24
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
2.3 spring boot对redis支持
spring boot在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,
2.4 自定义配置RedisTemplate
@Configuration
public class RedisConfig {
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisTemplate<String,Object> getRedis() {
RedisTemplate<String, Object> stringObjectRedisTemplate = new RedisTemplate<>();
stringObjectRedisTemplate.setConnectionFactory(redisConnectionFactory);
//key的序列化方式
stringObjectRedisTemplate.setKeySerializer(new StringRedisSerializer());
//value的序列化方式
stringObjectRedisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
//hash的value序列化方式
stringObjectRedisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
return stringObjectRedisTemplate;
}
}
@Bean
public StringRedisTemplate getStringRedisTemplate(){
return new StringRedisTemplate();
}
2.5 参考
三、修改redis密码
1.1 临时修改redis密码
- 设置密码
config set requirepass 123456
auth 123456
查看设置的密码:
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "123456"
1.2 永久设置redis密码
- 修改redis.conf
cd /etc/redis
vim redis.conf
- 修改配置文件中的requirepass
- 重启配置文件
sudo service redis-server restart