Multiple transaction managers - Selecting a one at runtime - Spring

柔情痞子 提交于 2019-12-13 01:34:50

问题


I am using Spring to configure transactions in my application. I have two transaction managers defined for two RabbitMQ servers.

....

@Bean(name = "devtxManager")
public PlatformTransactionManager devtxManager() {
    return new RabbitTransactionManager(devConnectionFactory());
}

@Bean(name = "qatxManager")
public PlatformTransactionManager qatxManager() {
    return new RabbitTransactionManager(qaConnectionFactory());
}

@Bean
public ConnectionFactory devConnectionFactory() {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setHost(propertyLoader.loadProperty("dev.rabbit.host"));
    factory.setPort(Integer.parseInt(propertyLoader.loadProperty("dev.rabbit.port")));
    factory.setVirtualHost("product");
    factory.setUsername(propertyLoader.loadProperty("dev.sender.rabbit.user"));
    factory.setPassword(propertyLoader.loadProperty("dev.sender.rabbit.password"));
    return factory;
}

@Bean
public ConnectionFactory qaConnectionFactory() {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setHost(propertyLoader.loadProperty("qa.rabbit.host"));
    factory.setPort(Integer.parseInt(propertyLoader.loadProperty("qa.rabbit.port")));
    factory.setVirtualHost("product");
    factory.setUsername(propertyLoader.loadProperty("qa.sender.rabbit.user"));
    factory.setPassword(propertyLoader.loadProperty("qa.sender.rabbit.password"));
    return factory;
}

...

In my service class I need to pick the right transaction manager by the 'env' variable passed in. ( i.e if env=='qa' I need to choose 'qatxManager' else if 'env==dev' I need to choose 'devtxManager'.

....

@Transactional(value = "qatxManager")
public String requeue(String env, String sourceQueue, String destQueue) {

    // read from queue
    List<Message> messageList = sendReceiveImpl.receive(env, sourceQueue);
....

How can I get it done?


回答1:


I think you need a Facade. Define an interface and create 2 classes implementing the same interface but with different @Transactional(value = "qatxManager")

Then define one Facade class which keeps 2 implementations (use @Qualifier to distinguish them) The Facade gets the env String and call method of proper bean



来源:https://stackoverflow.com/questions/30719516/multiple-transaction-managers-selecting-a-one-at-runtime-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!