org.springframework.amqp.rabbit.connection.ConnectionFactory Java Examples

The following examples show how to use org.springframework.amqp.rabbit.connection.ConnectionFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RabbitServiceAutoConfiguration.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link ConnectionFactory} using the singleton service
 * connector.
 * @param cloud {@link Cloud} instance to be used for accessing services.
 * @param connectorConfigObjectProvider the {@link ObjectProvider} for the
 * {@link RabbitConnectionFactoryConfig}.
 * @param applicationContext application context instance
 * @param rabbitProperties rabbit properties
 * @return the {@link ConnectionFactory} used by the binder.
 * @throws Exception if configuration of connection factory fails
 */
@Bean
@Primary
ConnectionFactory rabbitConnectionFactory(Cloud cloud,
		ObjectProvider<RabbitConnectionFactoryConfig> connectorConfigObjectProvider,
		ConfigurableApplicationContext applicationContext,
		RabbitProperties rabbitProperties) throws Exception {

	ConnectionFactory connectionFactory = cloud
			.getSingletonServiceConnector(ConnectionFactory.class,
					connectorConfigObjectProvider.getIfUnique());

	configureCachingConnectionFactory(
			(CachingConnectionFactory) connectionFactory,
			applicationContext, rabbitProperties);

	return connectionFactory;
}
 
Example #2
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloudProfile() {
	this.context = new SpringApplicationBuilder(SimpleProcessor.class,
			MockCloudConfiguration.class).web(WebApplicationType.NONE)
					.profiles("cloud").run();
	BinderFactory binderFactory = this.context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	ConnectionFactory connectionFactory = this.context
			.getBean(ConnectionFactory.class);

	assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);

	assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses"))
			.isNotNull();
	assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses"))
			.isNull();

	Cloud cloud = this.context.getBean(Cloud.class);

	verify(cloud).getSingletonServiceConnector(ConnectionFactory.class, null);
}
 
Example #3
Source File: RabbitBinderModuleTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentConnectionFactoryInheritedIfOverridden() {
	context = new SpringApplicationBuilder(SimpleProcessor.class,
			ConnectionFactoryConfiguration.class).web(WebApplicationType.NONE)
					.run("--server.port=0");
	BinderFactory binderFactory = context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	assertThat(binderConnectionFactory).isSameAs(MOCK_CONNECTION_FACTORY);
	ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);
	assertThat(binderConnectionFactory).isSameAs(connectionFactory);
	CompositeHealthContributor bindersHealthIndicator = context
			.getBean("bindersHealthContributor", CompositeHealthContributor.class);
	assertThat(bindersHealthIndicator).isNotNull();
	RabbitHealthIndicator indicator = (RabbitHealthIndicator) bindersHealthIndicator.getContributor("rabbit");
	assertThat(indicator).isNotNull();
	// mock connection factory behaves as if down
	assertThat(indicator.health().getStatus())
			.isEqualTo(Status.DOWN);
}
 
Example #4
Source File: AbstractCloudConfigServiceScanTest.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void cloudScanWithAllTypesOfServices() {
	ApplicationContext testContext = getTestApplicationContext(createMysqlService("mysqlDb"), 
															  createPostgresqlService("postDb"),
															  createMongoService("mongoDb"),
															  createRedisService("redisDb"),
															  createRabbitService("rabbit"));
	
	assertNotNull("Getting service by id", testContext.getBean("mysqlDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mysqlDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("postDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("postDb", DataSource.class));		

	assertNotNull("Getting service by id", testContext.getBean("mongoDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("mongoDb", MongoDbFactory.class));		
	
	assertNotNull("Getting service by id", testContext.getBean("redisDb"));
	assertNotNull("Getting service by id and type", testContext.getBean("redisDb", RedisConnectionFactory.class));		

	assertNotNull("Getting service by id", testContext.getBean("rabbit"));
	assertNotNull("Getting service by id and type", testContext.getBean("rabbit", ConnectionFactory.class));		
}
 
Example #5
Source File: RabbitMQConfiguration.java    From seed with Apache License 2.0 6 votes vote down vote up
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(new Jackson2JsonMessageConverter());
    template.setEncoding(SeedConstants.DEFAULT_CHARSET);
    //消息发送失败时,返回到队列中(需要spring.rabbitmq.publisherReturns=true)
    template.setMandatory(true);
    //消息成功到达exchange,但没有queue与之绑定时触发的回调(即消息发送不到任何一个队列中)
    //也可以在生产者发送消息的类上实现org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback和RabbitTemplate.ReturnCallback两个接口(本例中即为SendController.java)
    template.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> LogUtil.getLogger().error("消息发送失败,replyCode={},replyText={},exchange={},routingKey={},消息体=[{}]", replyCode, replyText, exchange, routingKey, JSON.toJSONString(message.getBody())));
    //消息成功到达exchange后触发的ack回调(需要spring.rabbitmq.publisherConfirms=true)
    template.setConfirmCallback((correlationData, ack, cause) -> {
        if(ack){
            LogUtil.getLogger().info("消息发送成功,消息ID={}", correlationData.getId());
        }else{
            LogUtil.getLogger().error("消息发送失败,消息ID={},cause={}", correlationData.getId(), cause);
        }
    });
    return template;
}
 
Example #6
Source File: RabbitWithoutRabbitTemplateConfig.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Bean
public RabbitAdmin rabbitAdmin(Queue queue, ConnectionFactory connectionFactory) {
  final TopicExchange exchange = new TopicExchange("myExchange", true, false);

  final RabbitAdmin admin = new RabbitAdmin(connectionFactory);
  admin.declareQueue(queue);
  admin.declareExchange(exchange);
  admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("#"));

  return admin;
}
 
Example #7
Source File: AmqpTestConfiguration.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Bean
ConnectionFactory rabbitConnectionFactory(final RabbitMqSetupService rabbitmqSetupService) {
    final CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setHost(rabbitmqSetupService.getHostname());
    factory.setPort(5672);
    factory.setUsername(rabbitmqSetupService.getUsername());
    factory.setPassword(rabbitmqSetupService.getPassword());
    try {
        factory.setVirtualHost(rabbitmqSetupService.createVirtualHost());
        // All exception are catched. The BrokerRunning decide if the
        // test should break or not
    } catch (@SuppressWarnings("squid:S2221") final Exception e) {
        Throwables.propagateIfInstanceOf(e, AlivenessException.class);
        LOG.error("Cannot create virtual host.", e);
    }
    return factory;
}
 
Example #8
Source File: RabbitConnectionFactoryCloudConfigTestHelper.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
public static void assertConfigProperties(ConnectionFactory connector, Integer channelCacheSize,
										  Integer requestedHeartbeat, Integer connectionTimeout,
										  int connectionLimit, boolean publisherConfirms) {
	Integer timeoutToTest = connectionTimeout < 0 ? DEFAULT_FACTORY_TIMEOUT : connectionTimeout;
	Integer heartBeatToTest = requestedHeartbeat < 0 ? DEFAULT_FACTORY_HEARTBEAT : requestedHeartbeat;

	assertNotNull(connector);

	assertEquals(channelCacheSize, ReflectionTestUtils.getField(connector, "channelCacheSize"));
	assertEquals(connectionLimit, ReflectionTestUtils.getField(connector, "connectionLimit"));
	assertEquals(publisherConfirms, ReflectionTestUtils.getField(connector, "publisherConfirms"));

	Object rabbitConnectionFactory = ReflectionTestUtils.getField(connector, "rabbitConnectionFactory");
	assertNotNull(rabbitConnectionFactory);
	assertEquals(heartBeatToTest, ReflectionTestUtils.getField(rabbitConnectionFactory, "requestedHeartbeat"));
	assertEquals(timeoutToTest, ReflectionTestUtils.getField(rabbitConnectionFactory, "connectionTimeout"));
}
 
Example #9
Source File: RabbitMQConfiguration.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 5 votes vote down vote up
@Bean("springConnectionFactory")
public ConnectionFactory connectionFactory() {
  CachingConnectionFactory factory = new CachingConnectionFactory();
  factory.setUsername(this.user);
  factory.setPassword(this.pass);
  factory.setHost(this.host);
  factory.setPort(this.port);
  return factory;
}
 
Example #10
Source File: HomeController.java    From hello-spring-cloud with Apache License 2.0 5 votes vote down vote up
private String toString(ConnectionFactory rabbitConnectionFactory) {
    if (rabbitConnectionFactory == null) {
        return "<none>";
    } else {
        return rabbitConnectionFactory.getHost() + ":"
                + rabbitConnectionFactory.getPort();
    }
}
 
Example #11
Source File: RabbitMQConfig.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setAddresses(host + ":"  + port);
    factory.setVirtualHost(virtualHost);
    factory.setUsername(username);
    factory.setPassword(password);
    return factory;
}
 
Example #12
Source File: ITSpringRabbit.java    From brave with Apache License 2.0 5 votes vote down vote up
@Bean RabbitTemplate newRabbitTemplate(
  ConnectionFactory connectionFactory,
  Binding binding,
  SpringRabbitTracing springRabbitTracing
) {
  RabbitTemplate result = springRabbitTracing.newRabbitTemplate(connectionFactory);
  result.setExchange(binding.getExchange());
  return result;
}
 
Example #13
Source File: RabbitConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
@Bean
public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setMessageConverter(new Jackson2JsonMessageConverter());
    return factory;
}
 
Example #14
Source File: AmqpContextConfigTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void 値がオーバライドされて指定のインスタンスがDIコンテナに登録される() {
    assertThat(config.host, is("192.168.10.10"));
    assertThat(config.port, is("5673"));
    assertThat(config.username, is("jfw"));
    assertThat(config.password, is("jfw"));
    assertThat(config.channelCacheSize, is(100));
    assertThat(context.getBean(ConnectionFactory.class), is(notNullValue()));
    assertThat(context.getBean(RabbitTemplate.class), is(notNullValue()));
    assertThat(context.getBean(MessageConverter.class), is(notNullValue()));
}
 
Example #15
Source File: RabbitConnectionFactoryXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void cloudRabbitConnectionFactoryWithProperties() {
	ApplicationContext testContext = getTestApplicationContext("cloud-rabbit-with-config.xml", createService("my-service"));

	ConnectionFactory connector = testContext.getBean("service-properties", getConnectorType());
	RabbitConnectionFactoryCloudConfigTestHelper.assertConfigProperties(connector, DEFAULT_CHANNEL_CACHE_SIZE, 5, 10, 15, true);
}
 
Example #16
Source File: TurbineApp.java    From Mastering-Microservices-with-Java with MIT License 5 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
    //LOG.info("Creating RabbitMQHost ConnectionFactory for host: {}", rabbitMQHost);

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMQHost);
    return cachingConnectionFactory;
}
 
Example #17
Source File: RabbitMQConfiguration.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 5 votes vote down vote up
@Bean("springConnectionFactory")
public ConnectionFactory connectionFactory() {
  CachingConnectionFactory factory = new CachingConnectionFactory();
  factory.setUsername(this.user);
  factory.setPassword(this.pass);
  factory.setHost(this.host);
  factory.setPort(this.port);
  return factory;
}
 
Example #18
Source File: DataSubscriberRabbitMQImpl.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(String clientId, BinLogDistributorClient binLogDistributorClient) {
    List<QueueInfo> queueList = rabbitHttpClient.getQueues(vhost);
    ConnectionFactory connectionFactory = rabbitMQClient.getConnectionFactory();
    //处理历史数据
    queueList.stream().filter(queueInfo -> queueInfo.getName().startsWith(DATA + clientId) && !queueInfo.getName().endsWith("-Lock"))
            .forEach(queueInfo -> executors.submit(new DataHandler(queueInfo.getName(), clientId, binLogDistributorClient, redissonClient, connectionFactory)));
    try {
        Channel channel = connectionFactory.createConnection().createChannel(false);
            channel.queueDeclare(NOTIFIER + clientId, true, false, true, null);
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body);
                    //每次推送都会执行这个方法,每次开线程,使用线程里面redis锁判断开销太大,先在外面判断一次
                    if (!DataHandler.DATA_KEY_IN_PROCESS.contains(msg)) {
                        //如果没在处理再进入
                        executors.submit(new DataHandler(msg, clientId, binLogDistributorClient, redissonClient, connectionFactory));
                    }
                }
            };
        channel.basicConsume(NOTIFIER + clientId, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example #19
Source File: RabbitConnectionFactoryCreator.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
private void setConnectionFactoryUri(com.rabbitmq.client.ConnectionFactory connectionFactory, String uri) {
	try {
		connectionFactory.setUri(uri);
	} catch (Exception e) {
		throw new IllegalArgumentException("Invalid AMQP URI", e);
	}
}
 
Example #20
Source File: RabbitConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public SimpleRabbitListenerContainerFactory retryQueuesContainerFactory(ConnectionFactory connectionFactory, RetryQueuesInterceptor retryInterceptor) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);

    Advice[] adviceChain = { retryInterceptor };
    factory.setAdviceChain(adviceChain);

    return factory;
}
 
Example #21
Source File: LocalizedQueueConnectionFactoryIntegrationTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	ConnectionFactory defaultConnectionFactory = rabbitAvailableRule.getResource();
	String[] addresses = new String[] { "localhost:9999", "localhost:5672" };
	String[] adminAddresses = new String[] { "http://localhost:15672",
			"http://localhost:15672" };
	String[] nodes = new String[] { "foo@bar", "rabbit@localhost" };
	String vhost = "/";
	String username = "guest";
	String password = "guest";
	this.lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory,
			addresses, adminAddresses, nodes, vhost, username, password, false, null,
			null, null, null);
}
 
Example #22
Source File: RabbitExchangeQueueProvisioner.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
public RabbitExchangeQueueProvisioner(ConnectionFactory connectionFactory,
		List<DeclarableCustomizer> customizers) {

	this.rabbitAdmin = new RabbitAdmin(connectionFactory);
	this.autoDeclareContext.refresh();
	this.rabbitAdmin.setApplicationContext(this.autoDeclareContext);
	this.rabbitAdmin.afterPropertiesSet();
	this.customizers = customizers;
}
 
Example #23
Source File: RabbitMQConfig.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setAddresses(host + ":"  + port);
    factory.setVirtualHost(virtualHost);
    factory.setUsername(username);
    factory.setPassword(password);
    return factory;
}
 
Example #24
Source File: TopicRabbitConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
@Bean
public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setMessageConverter(new Jackson2JsonMessageConverter());
    return factory;
}
 
Example #25
Source File: AmqpTestConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Bean
@Primary
public RabbitTemplate rabbitTemplateForTest(final ConnectionFactory connectionFactory) {
    final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    rabbitTemplate.setReplyTimeout(TimeUnit.SECONDS.toMillis(3));
    rabbitTemplate.setReceiveTimeout(TimeUnit.SECONDS.toMillis(3));
    return rabbitTemplate;
}
 
Example #26
Source File: RabbitConfig.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * @param rabbitConnectionFactory
 * @return SimpleMessageListenerContainer
 */
@Primary
public SimpleMessageListenerContainer rabbitListener(ConnectionFactory rabbitConnectionFactory) {
	SimpleMessageListenerContainer factory = new SimpleMessageListenerContainer();
	factory.setConnectionFactory(rabbitConnectionFactory);
	factory.setPrefetchCount(prefetchCount);
	factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
	factory.setConcurrentConsumers(consumerCount);
	return factory;

}
 
Example #27
Source File: AmqpIntegration.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow amqpReplyFlow(ConnectionFactory rabbitConnectionFactory,
		EchoService echoService) {
	return IntegrationFlows
			.from(Amqp.inboundGateway(rabbitConnectionFactory,
					this.echoQueueAndExchangeName))
			.transform(String.class, echoService::echo).get();
}
 
Example #28
Source File: RabbitMQRouterConfig.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
    factory.setConcurrentConsumers(1);
    factory.setMaxConcurrentConsumers(20);

    Advice[] adviceChain = new Advice[] { interceptor() };
    factory.setAdviceChain(adviceChain);
    return factory;
}
 
Example #29
Source File: RabbitMQInitializerTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Bean
public ConnectionFactory factory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    return connectionFactory;
}
 
Example #30
Source File: RabbitConfig.java    From notes with Apache License 2.0 5 votes vote down vote up
/**
 * 注入
 *
 * @param
 * @return com.rabbitmq.client.Connection
 * @author fruiqi
 * @date 19-1-22 下午5:41
 **/
@Bean
public ConnectionFactory getConnection() throws Exception {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setUsername(userName);
    factory.setPassword(userPassword);
    factory.setHost(host);
    factory.setPort(port);
    return factory;
}