SpringBoot程序MQ宕机备用方案-多活架构
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class MqConfig {
@Bean(name = "primaryMqExecutor")
@Primary
public ExecutorService primaryMqExecutor() {
return new ThreadPoolExecutor(
5,
20,
300,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024),
new CustomizableThreadFactory("primary-mq-thread-"),
new ThreadPoolExecutor.CallerRunsPolicy()
);
}
@Bean(name = "standbyMqExecutor")
public ExecutorService standbyMqExecutor() {
return new ThreadPoolExecutor(
5,
20,
300,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024),
new CustomizableThreadFactory("standby-mq-thread-"),
new ThreadPoolExecutor.CallerRunsPolicy()
);
}
}
这个代码示例定义了两个ExecutorService
Bean,一个用于主消息队列(primaryMqExecutor),另一个用于备用消息队列(standbyMqExecutor)。通过定义两个Bean,我们可以在程序中根据主消息队列的状态动态地切换到备用消息队列,实现消息队列的多活(Multi-Active)架构。这里使用了ThreadPoolExecutor
来创建线程池,并通过CustomizableThreadFactory
来设置线程名的前缀,使得线程的功能更加清晰。
评论已关闭