在将Redis会话与Spring会话一起使用时无法访问属性。 自动接线没有发生,因此该对象为null。不知道我在这里做什么错。
@自动连线 私有RedisSentinelProperties redisSentinelProperties;
没有spring-session,它可以正常工作,没有任何问题。
我尝试了没有春季会议,它工作正常。能够访问所有属性,并且自动接线正确
@自动连线 私有RedisSentinelProperties redisSentinelProperties;
自定义属性配置
@Component
@ConfigurationProperties(prefix = "app.redis")
@Validated
public class RedisSentinelProperties {
@NotNull
private String masterName;
@Valid
private Sentinel sentinel = new Sentinel();
////removed the getter and setter method for better readability
public static class Sentinel {
@NotEmpty
private List<String> nodes = new ArrayList<>();
//removed the getter and setter method for better readability
}
}
application.properties
app.redis.master-name=mymaster
app.redis.sentinel.nodes=192.168.56.50:26379,192.168.56.50:26380,192.168.56.50:26381
spring-session配置
@SpringBootApplication
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigPropertiesDemoApplication.class, args);
}
}
public class RedisHttpSessionInitializer extends AbstractHttpSessionApplicationInitializer {
public RedisHttpSessionInitializer() {
super(RedisHttpSessionConfig.class);
}
}
@Configuration
@EnableRedisHttpSession
@EnableWebSecurity
public class RedisHttpSessionConfig {
@Autowired
private RedisSentinelProperties redisSentinelProperties;
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.readFrom(SLAVE_PREFERRED)
.build();
private Set<String> sentinelHostAndPorts(){
Set<String> nodes = redisSentinelProperties.getSentinel().getNodes().stream().collect(Collectors.toSet());
return nodes;
}
//This is where NullPointerException is thrown line 37 in the stack trace
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(redisSentinelProperties.getMasterName(), sentinelHostAndPorts());
@Bean
public LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory(sentinelConfig, clientConfig);
}
}
下面是堆栈跟踪
由以下原因引起:java.lang.NullPointerException 在com.bt.consumer.configpropertiesdemo.config.RedisHttpSessionConfig。(RedisHttpSessionConfig.java:37) 在com.bt.consumer.configpropertiesdemo.config.RedisHttpSessionConfig $$ EnhancerBySpringCGLIB $$ f6d40824。() 在sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)处 在sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 在sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 在java.lang.reflect.Constructor.newInstance(Constructor.java:423) 在org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)