You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Profiles切换:本地用ArtemisTopic默认用JmsTopic实现方案

实现方案

核心思路是利用Spring Profile特性,根据不同环境注入对应的Topic实例,让业务代码与具体Topic实现解耦。


1. 拆分Topic的Bean配置

分别为local环境和默认环境配置对应的Topic Bean:

1.1 Local环境(ActiveMQ Artemis)的Topic配置

在已有的MessagingConfigArtemis类中添加ArtemisTopic的Bean:

@Configuration
@EnableJms
@Profile("local")
@PropertySource("classpath:application-local.properties")
public class MessagingConfigArtemis {

    // 原有ConnectionFactory、JmsTemplate等Bean保持不变...

    @Bean
    public Destination rawTopic() {
        return new ActiveMQTopic("raw");
    }
}

1.2 默认环境(Servicebus)的Topic配置

新建默认环境的配置类,配置JmsTopic的Bean和Servicebus的连接工厂:

@Configuration
@EnableJms
@Profile("!local") // 非local环境生效
@PropertySource("classpath:application.properties")
public class MessagingConfigServicebus {

    // 替换为你准备的Servicebus连接配置
    private static final String SERVICEBUS_BROKER_URL = "xxx";
    private static final String SERVICEBUS_USERNAME = "xxx";
    private static final String SERVICEBUS_PASSWORD = "xxx";

    @Bean
    public ConnectionFactory jmsConnectionFactory() {
        // 初始化Servicebus对应的ConnectionFactory(比如Azure Service Bus的JMS连接工厂)
        return new ServiceBusConnectionFactory(SERVICEBUS_BROKER_URL, SERVICEBUS_USERNAME, SERVICEBUS_PASSWORD);
    }

    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate(jmsConnectionFactory());
        return jmsTemplate;
    }

    // 按需配置JmsListenerContainerFactory...

    @Bean
    public Destination rawTopic() {
        return new JmsTopic("raw");
    }
}

2. 修改Publisher类,解耦具体Topic实现

去掉硬编码的两个Topic实例,通过依赖注入获取适配当前环境的Destination:

@Service
public class Publisher{

    private final Destination rawTopic;
    private final JmsTemplate jmsTemplate;
    private final ObjectMapper mapper;
    private static final System.Logger LOGGER = System.getLogger(Publisher.class.getName());

    // 构造器注入(推荐)
    public Publisher(Destination rawTopic, JmsTemplate jmsTemplate, ObjectMapper mapper) {
        this.rawTopic = rawTopic;
        this.jmsTemplate = jmsTemplate;
        this.mapper = mapper;
    }

    public void send(Request request) {
        try {
            jmsTemplate.convertAndSend(rawTopic, mapper.writeValueAsString(request), message -> {
                return message;
            });
        } catch (JsonProcessingException exception) {
            LOGGER.log(System.Logger.Level.ERROR, exception);
        }
    }
}

3. 环境切换说明

  • 启动时指定spring.profiles.active=local,Spring自动加载MessagingConfigArtemis,注入ActiveMQTopic实例,使用Artemis的连接配置。
  • 不指定profile或指定非local的profile时,加载MessagingConfigServicebus,注入JmsTopic实例,使用Servicebus的连接配置。

内容的提问来源于stack exchange,提问作者Tara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 16:32:48