项目中使用了mq,kafka两种消息队列进行发送数据,为了避免硬编码,在项目中通过不同的配置文件自动识别具体消息队列策略。这里整理两种实施方案,仅供参考!
/**
* 发送数据接口
*/
public interface IBaseService {
void send();
}
@Service
public class KafkaServiceImpl implements IBaseService {
@Autowired
MyConfiguration myConfiguration;
@Override
public void send() {
System.out.println("调用Kafka接口发送数据!");
myConfiguration.init("-------------Kafka-------------");
}
}
@Service
public class MQServiceImpl implements IBaseService {
@Autowired
MyConfiguration myConfiguration;
@Override
public void send() {
System.out.println("调用MQ接口,发送数据!");
myConfiguration.init("-------------MQ-----------");
}
}
/**
* 根据不同配置文件,选择发送消息工具类
*/
@Component
public class SendMessageUtil {
//message.type在application.yaml,":kafka" 设置默认值为kafka
@Value("${message.type:kafka}")
private String type;
@Autowired
KafkaServiceImpl kafkaService;
@Autowired
MQServiceImpl mqService;
public IBaseService get(){
if (type.equals("kafka"))
return kafkaService;
else
return mqService;
}
}
application.yaml
message:
type: kafka
@Autowired
SendMessageUtil sendMessageUtil;
@Test
void contextLoadsTwo() {
IBaseService tempBaseService = sendMessageUtil.get();
tempBaseService.send();
}
/**
* Kafka推送方式
*/
public class KafkaCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String type = environment.getProperty("message.type");
if (type.contains("kafka")){
return true;
}
return false;
}
}
/**
* MQ推送方式
*/
public class MQCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String type = environment.getProperty("message.type");
if (type.contains("mq")){
return true;
}
return false;
}
}
application.yaml
message:
type: kafka
// 注意:运行contextLoadsTwo测试方法时候,需要将iBaseService全部注释掉,否则会报错
// 也要将KafkaServiceImpl和MQServiceImpl上面@Conditional注释掉
@Autowired
SendMessageUtil sendMessageUtil;
@Test
void contextLoadsTwo() {
IBaseService tempBaseService = sendMessageUtil.get();
tempBaseService.send();
}
源码奉上,欢迎star!
MyIdea