IOC 框架集成示例
此示例仅作“参考”,不同的框架按需调整相关注解与用法。
1、添加配置:
folkmq.server: "folkmq://127.0.0.1:18602"
folkmq.consumerGroup: "demoapp"
2、添加配置器类(构建客户端,并订阅):
@Configuration
public class EventConfig {
@Bean
public MqClient initClient(@Inject("${folkmq.server}") String serverUrl,
@Inject("${folkmq.consumerGroup}") String consumerGroup,
@Inject Map<String, MqConsumeHandler> subscriptionMap) throws IOException {
//构建客户端
MqClient client = FolkMQ.createClient(serverUrl)
.nameAs(consumerGroup)
.connect();
//订阅
for (Map.Entry<String, MqConsumeHandler> subscription : subscriptionMap.entrySet()) {
client.subscribe(subscription.getKey(), subscription.getValue());
}
return client;
}
}
或者
@Configuration
public class EventConfig {
@Bean
public MqClient initClient(@Inject("${folkmq.server}") String serverUrl,
@Inject("${folkmq.consumerGroup}") String consumerGroup) throws IOException {
//构建客户端
MqClient client = FolkMQ.createClient(serverUrl)
.nameAs(consumerGroup)
.connect();
return client;
}
@Bean
public void subTopic(@Inject MqClient client, @Inject Map<String, MqConsumeHandler> subscriptionMap) throws IOException {
//订阅
for (Map.Entry<String, MqConsumeHandler> subscription : subscriptionMap.entrySet()) {
client.subscribe(subscription.getKey(), subscription.getValue());
}
}
}
3、消费者处理组件(按需订阅主题):
借用组件的名字,做为订阅主题。
@Component("event.user.created")
public class EventUserCreated implements MqConsumeHandler {
@Override
public void consume(MqMessageReceived message) throws IOException {
}
}
@Component("event.user.updated")
public class EventUserUpdated implements MqConsumeHandler {
@Override
public void consume(MqMessageReceived message) throws IOException {
}
}
4、生产消息:
@Component
public class UserService {
@Inject
UserMapper userMapper;
@Inject
MqClient mqClient;
@Tran
public void save(User user){
//保存
userMapper.insert(user);
//发布事件(同步模式下,如果异常可触发事务回滚) //只是应用示例
mqClient.publish("event.user.created", new MqMessage("{userId:\""+ user.userId +"\"}"));
}
}