Multiple transaction managers - Selecting a one at runtime - Spring

981 views Asked by At

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

There are 1 answers

1
StanislavL On BEST ANSWER

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