1. 场景
项目通过配置文件值动态判断配置为kafka或rabbitmq的消息队列作为中间件。
2.实现
通过实现Condition
接口,重写matches方法来进行场景判断:
2.1. kafka的Confition开关:
package com.hero.kafka.config;import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;public class KafkaCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {String useKafka = context.getEnvironment().getProperty("myConfig.useKafka");return "TRUE".equalsIgnoreCase(useKafka);}
}
2.1. rabbitmq的Conditon开关:
package com.hero.nms.rabbitmq.config;import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;public class RabbitmqCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {String useKafka = context.getEnvironment().getProperty("myConfig.useKafka");return "FALSE".equalsIgnoreCase(useKafka) || "nms_message_choose_mq".equalsIgnoreCase(useKafka);}
}
2.4. 注解方式控制kafka配置是否生效@Conditional(KafkaCondition.class)
@Configuration
@DependsOn(value = "springContextHolder")
@Conditional(KafkaCondition.class)
public class KafkaConfig {
// TODO ...
}
2.3. 注解方式控制rabbitmq配置是否生效@Conditional(RabbitmqCondition.class)
@Configuration
@DependsOn(value = "springContextHolder")
@Conditional(RabbitmqCondition.class)
public class RabbitmqConfig {
// TODO ...
}
3. 总结
通过注解@Conditional(KafkaCondition.class)
、@Conditional(RabbitmqCondition.class)
结合配置值 myConfig.useKafka
可以实现项目启动的时候使用rabbitmq还是kafka作为消息中间件。