Redis设置用用户名以及在java项目中如何配置
1.redis在版本6.0版本之后出现了用户名登录的方法,使用这种方式可以可以给不同的用户分配权限而不是使用默认的同一个用户权限
如果需要在redis中使用用户名则需要配置,下面是一个例子:
== 没有被注解掉并且以user开头的内容为你使用redis无密码登录时生成的,并且这个代码配置不会随着你配置redis密码以及redis用户名而消失,需要你手动注释或者删除,下面的背注解代码则是redis用户名的配置其中:user 后面的all为用户名 on> 后面的 allpass为用户的密码 。 如果将 >allpass 修改为 nopass 则为没有密码 ==
而密码后面的那些配置为用户的权限配置这里我给当前用户配置的权限与默认用户权限相同
2.在java的yml文件中需要配置用户名
redis:
database: 0
host: 127.0.0.1
port: 6379
password: root
timeout: 5000
properties:
username: userroot
在代码中需要一个方法用来创建LettuceConnectionFactory
public class RedisConfig extends CachingConfigurerSupport {
private static final Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private Integer port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.database}")
private String database;
@Value("${spring.redis.properties.username}")
private String username;
@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
config.setPassword(password);
//在这里获取到redis在yml文件中的配置
config.setUsername(username);
config.setDatabase(database);
return new LettuceConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//将实现后的lettuceConnectionFactory方法引入替换之前使用直接new的方法
template.setConnectionFactory(lettuceConnectionFactory());
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
template.setHashValueSerializer(serializer);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
这样就完整的配置了redis的用户名,并且整合在项目中