注册event bus
java
import io.lettuce.core.event.EventBus;
import io.lettuce.core.resource.ClientResources;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import java.util.Optional;
@Configuration
public class RedisConnectionEventBusAutoConfig {
@Bean
public EventBus lettuceEventBus(LettuceConnectionFactory lettuceConnectionFactory) {
Optional<ClientResources> clientResources = lettuceConnectionFactory.getClientConfiguration()
.getClientResources();
boolean present = clientResources.isPresent();
return present ? clientResources.get().eventBus() : null;
}
}
监听事件
java
import com.jinlei.gateway.sirius.application.RouteDefinitionService;
import io.lettuce.core.event.EventBus;
import io.lettuce.core.event.connection.ConnectionActivatedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.Disposable;
@Component
@RequiredArgsConstructor
@Slf4j
public class RedisConnectionEventListener {
private Disposable subscription;
private final RouteDefinitionService routeDefinitionService;
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
EventBus eventBus = event.getApplicationContext().getBean(EventBus.class);
// 订阅事件
subscription = eventBus.get().subscribe(redisEvent -> {
if (redisEvent instanceof ConnectionActivatedEvent) {
ConnectionActivatedEvent connectionActivatedEvent = (ConnectionActivatedEvent) redisEvent;
log.info("Redis reconnect ..try refresh route: {}", connectionActivatedEvent);
routeDefinitionService.refreshRouteDefinition();
}
});
}
// 清理资源
@EventListener
public void onApplicationStop(ContextClosedEvent event) {
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}