Весенняя загрузка отключить Redis Server - PullRequest
0 голосов
/ 04 февраля 2019

Мне нужно отключить redis в моем приложении Spring Boot.Я следовал многим советам из Интернета, но безуспешно.

Мои application.properties, он имеет следующую строку:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

spring.data.redis.repositories.enabled=false

И когда я пытаюсь запустить свое приложение, я получаю:

Описание :

Поле sessionRepository в org.springframework.session.web.socket.config.annotation.AbstractSessionWebSocketMessageBrokerConfigurer требуется компонент типа 'org.springframework.sess.SessionRepository ', который не найден.

Действие:

Рассмотрите возможность определения bean-компонента типа' org.springframework.session.SessionRepository 'в вашей конфигурации.

Приложение, которое я запускаю, тестирует WebSocket. Оно отлично работает, но для бизнеса мне нужно отключить Redis.Пожалуйста, любая помощь будет оценена.

Заранее спасибо !!

Вот мой код: Мой основной класс:

public class WebSocketChatApplication extends SpringBootServletInitializer {

public static void main(String[] args) {         
SpringApplication.run(WebSocketChatApplication.class, args);    
} 

@Override   protected SpringApplicationBuilder 
   configure(SpringApplicationBuilder application) {        return 
  return application.sources(WebSocketChatApplication.class);   } 
}

Вот мой ChatConfig:

@Configuration
@EnableConfigurationProperties(ChatProperties.class)
 public class ChatConfig {

@Autowired
private ChatProperties chatProperties;

@Bean
@Description("Tracks user presence (join / leave) and broacasts it to all connected users")
public PresenceEventListener presenceEventListener(SimpMessagingTemplate messagingTemplate) {
    PresenceEventListener presence = new PresenceEventListener(messagingTemplate, participantRepository());
    presence.setLoginDestination(chatProperties.getDestinations().getLogin());
    presence.setLogoutDestination(chatProperties.getDestinations().getLogout());
    return presence;
}

@Bean
@Description("Keeps connected users")
public ParticipantRepository participantRepository() {
    return new ParticipantRepository();
}

@Bean
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Description("Keeps track of the level of profanity of a websocket session")
public SessionProfanity sessionProfanity() {
    return new SessionProfanity(chatProperties.getMaxProfanityLevel());
}

@Bean
@Description("Utility class to check the number of profanities and filter them")
public ProfanityChecker profanityFilter() {
    ProfanityChecker checker = new ProfanityChecker();
    checker.setProfanities(chatProperties.getDisallowedWords());
    return checker;
}

/*@Bean(initMethod = "start", destroyMethod = "stop")
@Description("Embedded Redis used by Spring Session")
public RedisServer redisServer(@Value("${redis.embedded.port}") int port)  throws IOException {
    return new RedisServer(port);
}*/

}

Вот мой WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker


public class WebSocketConfig extends 
AbstractSessionWebSocketMessageBrokerConfigurer<Session> {



@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/queue/", "/topic/", "/exchange/");
    //registry.enableStompBrokerRelay("/queue/", "/topic/", "/exchange/");
    registry.setApplicationDestinationPrefixes("/app");
}

Класс SecurityConfig:

@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private static final String SECURE_ADMIN_PASSWORD = "rockandroll";

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .formLogin()
            .loginPage("/index.html")
            .loginProcessingUrl("/login")
            .defaultSuccessUrl("/chat.html")
            .permitAll()
            .and()
        .logout()
            .logoutSuccessUrl("/index.html")
            .permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/js/**", "/lib/**", "/images/**", "/css/**", "/index.html", "/").permitAll()
            .antMatchers("/websocket").hasRole("ADMIN")
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
            .anyRequest().authenticated();
    http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());


}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(new AuthenticationProvider() {

        @Override
        public boolean supports(Class<?> authentication) {
            return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
        }

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

            List<GrantedAuthority> authorities = SECURE_ADMIN_PASSWORD.equals(token.getCredentials()) ? 
                                                    AuthorityUtils.createAuthorityList("ROLE_ADMIN") : null;

            return new UsernamePasswordAuthenticationToken(token.getName(), token.getCredentials(), authorities);
        }
    });
}

}

Я думаю, что это самое важное. Остальное - RestController и пара объектов DTO.Как я уже сказал, он отлично работает, но мне нужно отключить Redis.

Ответы [ 2 ]

0 голосов
/ 04 февраля 2019

Я реализовал JDBC в сеансе памяти, и он отлично работает.Theres 1 вещь, которую я не понимаю.О сессиях, когда они мне нужны, а когда нет?Поскольку Spring загружается, вы можете выбрать Session Type = none.

Спасибо!

0 голосов
/ 04 февраля 2019

Вы можете попытаться отключить автоматическую настройку Redis в классе загрузочного приложения Spring, чтобы проверить, не происходит ли у вас другое поведение.

@SpringBootApplication(exclude = RedisAutoConfiguration.class)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...