Java Code Examples for org.springframework.amqp.rabbit.connection.CachingConnectionFactory

The following examples show how to use org.springframework.amqp.rabbit.connection.CachingConnectionFactory. These examples are extracted from open source projects. 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
/**
 * 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
private void checkConnectionFactoryIsErrorCapable() {
	if (!(this.connectionFactory instanceof CachingConnectionFactory)) {
		logger.warn(
				"Unknown connection factory type, cannot determine error capabilities: "
						+ this.connectionFactory.getClass());
	}
	else {
		CachingConnectionFactory ccf = (CachingConnectionFactory) this.connectionFactory;
		if (!ccf.isPublisherConfirms() && !ccf.isPublisherReturns()) {
			logger.warn(
					"Producer error channel is enabled, but the connection factory is not configured for "
							+ "returns or confirms; the error channel will receive no messages");
		}
		else if (!ccf.isPublisherConfirms()) {
			logger.info(
					"Producer error channel is enabled, but the connection factory is only configured to "
							+ "handle returned messages; negative acks will not be reported");
		}
		else if (!ccf.isPublisherReturns()) {
			logger.info(
					"Producer error channel is enabled, but the connection factory is only configured to "
							+ "handle negatively acked messages; returned messages will not be reported");
		}
	}
}
 
Example 3
@Test
public void testMultiplexOnPartitionedConsumer() throws Exception {
	final ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
	RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy();
	CachingConnectionFactory cf = new CachingConnectionFactory("localhost",
			proxy.getPort());

	final RabbitExchangeQueueProvisioner rabbitExchangeQueueProvisioner = new RabbitExchangeQueueProvisioner(cf);

	consumerProperties.setMultiplex(true);
	consumerProperties.setPartitioned(true);
	consumerProperties.setInstanceIndexList(Arrays.asList(1, 2, 3));

	final ConsumerDestination consumerDestination = rabbitExchangeQueueProvisioner.provisionConsumerDestination("foo", "boo", consumerProperties);

	final String name = consumerDestination.getName();

	assertThat(name).isEqualTo("foo.boo-1,foo.boo-2,foo.boo-3");
}
 
Example 4
@Test
public void testMultiplexOnPartitionedConsumerWithMultipleDestinations() throws Exception {
	final ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
	RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy();
	CachingConnectionFactory cf = new CachingConnectionFactory("localhost",
			proxy.getPort());

	final RabbitExchangeQueueProvisioner rabbitExchangeQueueProvisioner = new RabbitExchangeQueueProvisioner(cf);

	consumerProperties.setMultiplex(true);
	consumerProperties.setPartitioned(true);
	consumerProperties.setInstanceIndexList(Arrays.asList(1, 2, 3));

	final ConsumerDestination consumerDestination = rabbitExchangeQueueProvisioner.provisionConsumerDestination("foo,qaa", "boo", consumerProperties);

	final String name = consumerDestination.getName();

	assertThat(name).isEqualTo("foo.boo-1,foo.boo-2,foo.boo-3,qaa.boo-1,qaa.boo-2,qaa.boo-3");
}
 
Example 5
Source Project: generic-vnfm   Source File: EMSConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
  log.info("Initialization of RabbitConfiguration");

  emsConnectionFactory = new CachingConnectionFactory();
  ((CachingConnectionFactory) emsConnectionFactory).setHost(brokerIp);
  ((CachingConnectionFactory) emsConnectionFactory).setPort(rabbitPort);
  ((CachingConnectionFactory) emsConnectionFactory).setUsername(emsRabbitUsername);
  ((CachingConnectionFactory) emsConnectionFactory).setPassword(emsRabbitPassword);

  rabbitAdmin = new RabbitAdmin(emsConnectionFactory);
  TopicExchange topicExchange = new TopicExchange("openbaton-exchange");
  rabbitAdmin.declareExchange(topicExchange);
  log.info("exchange declared");

  queueName_emsRegistrator = "ems." + vnfmHelper.getVnfmEndpoint() + ".register";
  rabbitAdmin.declareQueue(new Queue(queueName_emsRegistrator, durable, exclusive, autodelete));
}
 
Example 6
Source Project: hawkbit   Source File: AmqpTestConfiguration.java    License: 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 7
Source Project: cukes   Source File: RabbitMQConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@DependsOn("amqpBroker")
CachingConnectionFactory connectionFactory() {
    log.info("Creating connection factory for MQ broker...");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(hostname);
    cf.setPort(port);
    cf.setUsername(userName);
    cf.setPassword(password);
    cf.setVirtualHost(virtualHost);
    cf.setAutomaticRecoveryEnabled(false);
    if (useSSL) {
        try {
            cf.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            //TODO don't throw raw exceptions
            throw new RuntimeException(e);
        }
    }

    log.info("Connection factory created.");
    return new CachingConnectionFactory(cf);
}
 
Example 8
private CachingConnectionFactory createSpringConnectionFactory(AmqpServiceInfo serviceInfo,
															   ServiceConnectorConfig serviceConnectorConfiguration,
															   com.rabbitmq.client.ConnectionFactory connectionFactory) {
	CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);

	if (serviceInfo.getUris() != null) {
		cachingConnectionFactory.setAddresses(getAddresses(serviceInfo));
	}

	if (serviceConnectorConfiguration != null) {
		Integer channelCacheSize = ((RabbitConnectionFactoryConfig) serviceConnectorConfiguration).getChannelCacheSize();
		if (channelCacheSize != null) {
			cachingConnectionFactory.setChannelCacheSize(channelCacheSize);
		}
	}

	return cachingConnectionFactory;
}
 
Example 9
Source Project: rabbitmq-mock   Source File: SpringIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
ConnectionFactory connectionFactory() {
    return new CachingConnectionFactory(
        MockConnectionFactoryFactory
            .build()
            .enableConsistentHashPlugin()
            .withAdditionalExchange(creatorWithExchangeType("x-fix-delayed-message", FixDelayExchange::new))
    );
}
 
Example 10
@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 11
@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 12
Source Project: kkbinlog   Source File: RabbitMQConfig.java    License: 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 13
Source Project: kkbinlog   Source File: RabbitMQConfig.java    License: 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 14
Source Project: kkbinlog   Source File: RabbitMQConfig.java    License: 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 15
Source Project: notes   Source File: RabbitConfig.java    License: 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;
}
 
Example 16
Source Project: shine-mq   Source File: RabbitmqFactory.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized static RabbitmqFactory getInstance(MqProperties config, CachingConnectionFactory factory) {
    rabbitConnectionFactory = factory;
    //设置生成者确认机制
    rabbitConnectionFactory.setPublisherConfirms(true);
    if (config.getRabbit().getChannelCacheSize() != null) {
        rabbitConnectionFactory.setChannelCacheSize(config.getRabbit().getChannelCacheSize());
    }
    if (rabbitmqFactory == null) {
        rabbitmqFactory = new RabbitmqFactory(config);
    }
    return rabbitmqFactory;
}
 
Example 17
Source Project: Spring-5.0-By-Example   Source File: RabbitMQConfiguration.java    License: 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
@Bean
public ConnectionFactory connectionFactory() {
    CommonProperties.RabbitMQ rabbitMQ = commonProperties.getRabbitMQ();
    CachingConnectionFactory factory = new CachingConnectionFactory(rabbitMQ.getHostname(), rabbitMQ.getPort());
    if (rabbitMQ.getUsername() != null && rabbitMQ.getPassword() != null) {
        factory.setUsername(rabbitMQ.getUsername());
        factory.setPassword(rabbitMQ.getPassword());
    }
    return factory;
}
 
Example 19
@Bean
public ConnectionFactory connectionFactory() {
	final Connection mockConnection = mock(Connection.class);
	final AMQP.Queue.DeclareOk mockDeclareOk = mock(AMQP.Queue.DeclareOk.class);
	com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
			com.rabbitmq.client.ConnectionFactory.class, new Answer() {
				@Override
				public Object answer(InvocationOnMock invocationOnMock)
						throws Throwable {
					// hack for keeping backward compatibility with #303
					if ("newConnection"
							.equals(invocationOnMock.getMethod().getName())) {
						return mockConnection;
					}
					return Mockito.RETURNS_DEFAULTS.answer(invocationOnMock);
				}
			});
	try {
		final Channel mockChannel = mock(Channel.class, invocationOnMock -> {
			if ("queueDeclare".equals(invocationOnMock.getMethod().getName())) {
				return mockDeclareOk;
			}
			return Mockito.RETURNS_DEFAULTS.answer(invocationOnMock);
		});
		when(mockConnection.isOpen()).thenReturn(true);
		when(mockConnection.createChannel()).thenReturn(mockChannel);
		when(mockConnection.createChannel(Mockito.anyInt())).thenReturn(mockChannel);
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
	return new CachingConnectionFactory(mockConnectionFactory) {

	};
}
 
Example 20
private boolean transactionalChannel() {
	if (this.rabbitProperties == null) {
		// backward compatibility
		return true;
	}
	return this.rabbitProperties.getPublisherConfirmType() == null
			|| this.rabbitProperties
					.getPublisherConfirmType() == CachingConnectionFactory.ConfirmType.NONE;
}
 
Example 21
@Bean
public ConnectionFactory connectionFactory() {
    //LOG.info("Creating RabbitMQHost ConnectionFactory for host: {}", rabbitMQHost);

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMQHost);
    return cachingConnectionFactory;
}
 
Example 22
@Bean
public ConnectionFactory connectionFactory() {
    //LOG.info("Creating RabbitMQHost ConnectionFactory for host: {}", rabbitMQHost);

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMQHost);
    return cachingConnectionFactory;
}
 
Example 23
@Bean
public ConnectionFactory connectionFactory() {
    //LOG.info("Creating RabbitMQHost ConnectionFactory for host: {}", rabbitMQHost);

    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMQHost);
    return cachingConnectionFactory;
}
 
Example 24
@Override
protected void obtainResource() throws Exception {
	resource = new CachingConnectionFactory("localhost");
	resource.createConnection().close();
	if (management) {
		Socket socket = SocketFactory.getDefault().createSocket("localhost", 15672);
		socket.close();
	}
}
 
Example 25
static void configureCachingConnectionFactory(
		CachingConnectionFactory connectionFactory,
		ConfigurableApplicationContext applicationContext,
		RabbitProperties rabbitProperties) throws Exception {

	if (StringUtils.hasText(rabbitProperties.getAddresses())) {
		connectionFactory.setAddresses(rabbitProperties.determineAddresses());
	}

	connectionFactory.setPublisherConfirmType(rabbitProperties.getPublisherConfirmType() == null ? ConfirmType.NONE : rabbitProperties.getPublisherConfirmType());
	connectionFactory.setPublisherReturns(rabbitProperties.isPublisherReturns());
	if (rabbitProperties.getCache().getChannel().getSize() != null) {
		connectionFactory.setChannelCacheSize(
				rabbitProperties.getCache().getChannel().getSize());
	}
	if (rabbitProperties.getCache().getConnection().getMode() != null) {
		connectionFactory
				.setCacheMode(rabbitProperties.getCache().getConnection().getMode());
	}
	if (rabbitProperties.getCache().getConnection().getSize() != null) {
		connectionFactory.setConnectionCacheSize(
				rabbitProperties.getCache().getConnection().getSize());
	}
	if (rabbitProperties.getCache().getChannel().getCheckoutTimeout() != null) {
		connectionFactory.setChannelCheckoutTimeout(rabbitProperties.getCache()
				.getChannel().getCheckoutTimeout().toMillis());
	}
	connectionFactory.setApplicationContext(applicationContext);
	applicationContext.addApplicationListener(connectionFactory);
	connectionFactory.afterPropertiesSet();
}
 
Example 26
@Bean
@ConditionalOnMissingBean(ConnectionNameStrategy.class)
@ConditionalOnProperty("spring.cloud.stream.rabbit.binder.connection-name-prefix")
public ConnectionNameStrategy connectionNamer(CachingConnectionFactory cf) {
	final AtomicInteger nameIncrementer = new AtomicInteger();
	ConnectionNameStrategy namer = f -> this.rabbitBinderConfigurationProperties
			.getConnectionNamePrefix() + "#" + nameIncrementer.getAndIncrement();
	// TODO: this can be removed when Boot 2.0.1 wires it in
	cf.setConnectionNameStrategy(namer);
	return namer;
}
 
Example 27
@Test
public void testConnect() {
	RabbitAdmin admin = new RabbitAdmin(this.lqcf);
	Queue queue = new Queue(UUID.randomUUID().toString(), false, false, true);
	admin.declareQueue(queue);
	ConnectionFactory targetConnectionFactory = this.lqcf
			.getTargetConnectionFactory("[" + queue.getName() + "]");
	RabbitTemplate template = new RabbitTemplate(targetConnectionFactory);
	template.convertAndSend("", queue.getName(), "foo");
	assertThat(template.receiveAndConvert(queue.getName())).isEqualTo("foo");
	((CachingConnectionFactory) targetConnectionFactory).destroy();
	admin.deleteQueue(queue.getName());
}
 
Example 28
@Test
public void testProducerAckChannel() throws Exception {
	RabbitTestBinder binder = getBinder();
	CachingConnectionFactory ccf = this.rabbitAvailableRule.getResource();
	ccf.setPublisherReturns(true);
	ccf.setPublisherConfirms(true);
	ccf.resetConnection();
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			new BindingProperties());
	ExtendedProducerProperties<RabbitProducerProperties> producerProps = createProducerProperties();
	producerProps.setErrorChannelEnabled(true);
	producerProps.getExtension().setConfirmAckChannel("acksChannel");
	Binding<MessageChannel> producerBinding = binder.bindProducer("acks.0",
			moduleOutputChannel, producerProps);
	final Message<?> message = MessageBuilder.withPayload("acksMessage".getBytes())
			.build();
	final AtomicReference<Message<?>> confirm = new AtomicReference<>();
	final CountDownLatch confirmLatch = new CountDownLatch(1);
	binder.getApplicationContext().getBean("acksChannel", DirectChannel.class)
			.subscribe(m -> {
				confirm.set(m);
				confirmLatch.countDown();
			});
	moduleOutputChannel.send(message);
	assertThat(confirmLatch.await(10, TimeUnit.SECONDS)).isTrue();
	assertThat(confirm.get().getPayload()).isEqualTo("acksMessage".getBytes());
	producerBinding.unbind();
}
 
Example 29
@Bean
public CachingConnectionFactory rabbitConnectionFactory(RabbitMQContainer rabbitMQContainer) throws Exception {
    // configuration properties are Spring Boot defaults
    RabbitConnectionFactoryBean rabbitFactory = new RabbitConnectionFactoryBean();
    rabbitFactory.setPort(rabbitMQContainer.getAmqpPort());
    rabbitFactory.afterPropertiesSet();
    CachingConnectionFactory factory = new CachingConnectionFactory(rabbitFactory.getObject());
    return factory;
}
 
Example 30
Source Project: Mastering-Microservices-with-Java   Source File: TurbineApp.java    License: 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;
}