1、rabbitmq配置类
@Configuration
public class RabbitMqConfig {
@Value("${rabbitMq.host}")
private String host;
@Value("${rabbitMq.port}")
private Integer port;
@Value("${rabbitMq.username}")
private String username;
@Value("${rabbitMq.password}")
private String password;
@Value("${rabbitMq.vhost}")
private String vhost;
@Value("${rabbitmq2.host}")
private String host2;
@Value("${rabbitmq2.port}")
private Integer port2;
@Value("${rabbitmq2.username}")
private String username2;
@Value("${rabbitmq2.password}")
private String password2;
@Value("${rabbitmq2.vhost}")
private String vhost2;
@Bean("customConnectionFactory")
public ConnectionFactory customConnectionFactory(){
try {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(vhost);
return connectionFactory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Bean("connectionFactory2")
public ConnectionFactory connectionFactory2(){
try {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost(host2);
connectionFactory.setPort(port2);
connectionFactory.setUsername(username2);
connectionFactory.setPassword(password2);
connectionFactory.setVirtualHost(vhost2);
return connectionFactory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2、yml参数,connectionFactory=#customConnectionFactory用于指定配置的connectionFactory,如果只用到一个rabbitmq,可以省略该参数,rabbitmq:exchangeNamequeue=dataSender&durable=True&passive=True,rabbitmq会自动匹配factory
rabbitMq:
host: 127.0.0.1
port: 5672
username: root
password: root
vhost: /
constant: rabbitmq:exchangeName?queue=dataSender&durable=True&passive=True&connectionFactory=#customConnectionFactory
rabbitmq2:
host: 127.0.0.1
port: 5672
username: root
password: root
routingKey: test
vhost: /
constant: rabbitmq:exchangeName2?connectionFactory=#connectionFactory2&exchangeType=topic&autoDelete=false
3、from实现路由
@Value("${rabbitMq.constant}")
protected String rebbitmqConstant;
@Value("${rabbitmq2.constant}")
protected String rebbitmqConstant2;
@Value("${rabbitmq2.routingKey}")
protected String routingKey;
@Override
public void configure() throws Exception {
from(rebbitmqConstant)
.process(exchange->{
exchange.getIn().setHeader("rabbitmq.ROUTING_KEY",routingKey);
})
.to(rebbitmqConstant2);
}