本文介绍了多个事务管理器 - 在运行时选择一个 - Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring 在我的应用程序中配置事务.我为两个 RabbitMQ 服务器定义了两个事务管理器.

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;
}

...

在我的服务类中,我需要通过传入的 'env' 变量来选择正确的事务管理器.(即如果 env=='qa' 我需要选择 'qatxManager' 否则如果 'env==dev' 我需要选择devtxManager".

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);
....

我怎样才能完成它?

推荐答案

我认为你需要一个 Facade.定义一个接口并创建 2 个实现相同接口但具有不同 @Transactional(value = "qatxManager")

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

然后定义一个 Facade 类,该类保留 2 个实现(使用 @Qualifier 来区分它们) Facade 获取 env 字符串并调用适当 bean 的方法

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

这篇关于多个事务管理器 - 在运行时选择一个 - Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:55