當前位置: 首頁>>代碼示例>>Java>>正文


Java RabbitTemplate類代碼示例

本文整理匯總了Java中org.springframework.amqp.rabbit.core.RabbitTemplate的典型用法代碼示例。如果您正苦於以下問題:Java RabbitTemplate類的具體用法?Java RabbitTemplate怎麽用?Java RabbitTemplate使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RabbitTemplate類屬於org.springframework.amqp.rabbit.core包,在下文中一共展示了RabbitTemplate類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: checkRabbitMQAMQPProtocol

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
public String checkRabbitMQAMQPProtocol(String messageAsString,
                                        String url,
                                        String user,
                                        String password,
                                        String vhost) throws Exception {
    org.springframework.amqp.rabbit.connection.CachingConnectionFactory cf =
            new org.springframework.amqp.rabbit.connection.CachingConnectionFactory();
    URL formattedUrl = new URL("http://" + url);
    cf.setHost(formattedUrl.getHost());
    cf.setPort(formattedUrl.getPort());
    cf.setUsername(user);
    cf.setPassword(password);
    cf.setVirtualHost(vhost);
    RabbitAdmin admin = new RabbitAdmin(cf);
    org.springframework.amqp.core.Queue queue = new org.springframework.amqp.core.Queue("myQueue");
    admin.declareQueue(queue);
    TopicExchange exchange = new TopicExchange("myExchange");
    admin.declareExchange(exchange);
    admin.declareBinding(
            BindingBuilder.bind(queue).to(exchange).with("foo.*"));
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend("myExchange", "foo.bar", messageAsString);
    String receivedMessage = template.receiveAndConvert("myQueue").toString();
    return receivedMessage;
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:26,代碼來源:CheckBrokerConnectionUtils.java

示例2: call

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
/**
 * @Title: call
 * @Description: call類型,點對點發送接收消息
 * @param topicRoutingKey
 * @param serverName
 * @param bodyMsg
 * @param outTimeMillis
 * @throws Exception 設定文件
 * @return Map<String,Object>    返回類型
 */
public Map<String,Object> call(String topicRoutingKey,String serverName,Map<String,Object> bodyMsg,int outTimeMillis) throws Exception{
    Map<String,Object> sendMsg = new HashMap<String,Object>();
    sendMsg.put("mqkey",topicRoutingKey+"."+serverName);
    sendMsg.put("mqtype","call");
    sendMsg.put("mqbody",bodyMsg==null?new HashMap<String,Object>():bodyMsg);

    String topicMessage = JSON.toJSONString(sendMsg, JsonFilter.filter);
    Message message=new Message(topicMessage.getBytes("UTF-8"),new MessageProperties());

    RabbitTemplate directTemplate =new RabbitTemplate();
    directTemplate.setConnectionFactory(connectionFactory);
    directTemplate.setExchange(PropertyLoader.MQ_EXCHANGE);
    directTemplate.setReplyTimeout(outTimeMillis);

    Message reply=directTemplate.sendAndReceive(topicRoutingKey,message);
    if(reply==null){
        throw new Exception("waitting rabbitmq response timeout");
    }
    String body=new String(reply.getBody(),"UTF-8");
    Map<String,Object> reqMsgMap =JSON.parseObject(body,new TypeReference<Map<String, Object>>(){});
    LOG.info("back :"+reqMsgMap);
    reqMsgMap =JSON.parseObject(reqMsgMap.get("mqbody").toString(),new TypeReference<Map<String, Object>>(){});
    return reqMsgMap;
}
 
開發者ID:elves-project,項目名稱:openapi,代碼行數:35,代碼來源:MessageProducer.java

示例3: testDefaultRabbitConfiguration

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Test
public void testDefaultRabbitConfiguration() {
	load(TestConfiguration.class);
	RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
	RabbitMessagingTemplate messagingTemplate = this.context
			.getBean(RabbitMessagingTemplate.class);
	CachingConnectionFactory connectionFactory = this.context
			.getBean(CachingConnectionFactory.class);
	DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
	RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class);
	assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory);
	assertThat(getMandatory(rabbitTemplate)).isFalse();
	assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate);
	assertThat(amqpAdmin).isNotNull();
	assertThat(connectionFactory.getHost()).isEqualTo("localhost");
	assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(false);
	assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false);
	assertThat(this.context.containsBean("rabbitListenerContainerFactory"))
			.as("Listener container factory should be created by default").isTrue();
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:21,代碼來源:RabbitAutoConfigurationTests.java

示例4: spyOn

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Override
public Spy spyOn(final String queue) {
	final RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
	template.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor());
	return new Spy() {

		@Override
		public Object receive(boolean expectNull) throws Exception {
			if (expectNull) {
				Thread.sleep(50);
				return template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue);
			}
			Object bar = null;
			int n = 0;
			while (n++ < 100 && bar == null) {
				bar = template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue);
				Thread.sleep(100);
			}
			assertThat(n).isLessThan(100).withFailMessage("Message did not arrive in RabbitMQ");
			return bar;
		}

	};
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-stream-binder-rabbit,代碼行數:25,代碼來源:RabbitBinderTests.java

示例5: testDefaultRabbitConfiguration

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Test
public void testDefaultRabbitConfiguration() {
	load(TestConfiguration.class);
	RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class);
	RabbitMessagingTemplate messagingTemplate = this.context
			.getBean(RabbitMessagingTemplate.class);
	CachingConnectionFactory connectionFactory = this.context
			.getBean(CachingConnectionFactory.class);
	RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class);
	assertEquals(connectionFactory, rabbitTemplate.getConnectionFactory());
	assertEquals(rabbitTemplate, messagingTemplate.getRabbitTemplate());
	assertNotNull(amqpAdmin);
	assertEquals("localhost", connectionFactory.getHost());
	assertTrue("Listener container factory should be created by default",
			this.context.containsBean("rabbitListenerContainerFactory"));
}
 
開發者ID:Nephilim84,項目名稱:contestparser,代碼行數:17,代碼來源:RabbitAutoConfigurationTests.java

示例6: getObject

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Override
public AmqpTemplate getObject() throws Exception {
    RabbitTemplate rabbitTemplate = rabbitAdmin.getRabbitTemplate();
    rabbitTemplate.setMessageConverter(messageConverter);
    rabbitTemplate.setRetryTemplate(retryTemplate());

    if (messagingConfiguration.isMandatoryMessages()) {
        logger.info("will send mandatoryMessages, which expect at least one consumer");

        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(createReturnCallback());
    } else {
        logger.info("mandatory flag is not set, messages are not being set as mandatory");
    }

    return rabbitTemplate;
}
 
開發者ID:zeroDivisible,項目名稱:spring-rabbitmq-example,代碼行數:18,代碼來源:AmqpTemplateFactory.java

示例7: createReturnCallback

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
private RabbitTemplate.ReturnCallback createReturnCallback() {
    return new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(final Message message, final int replyCode, final String replyText, final String exchange,
                                    final String routingKey) {
            try {
                byte[] correlationFromMessage = message.getMessageProperties().getCorrelationId();
                UniqueId uniqueId = uniqueIdFactory.fromBytes(correlationFromMessage);
                logger.warn("exchange: [ {} ], routingKey: [ {} ], there is no consumer defined to consume [ {} ]", exchange,
                            routingKey, message);
                responseListener.notifyWithError(uniqueId, new RuntimeException("no listener for message"));
            } catch (Exception e) {
                logger.warn("for message {}, replyCode {}, replyText, exchange, routingKey", message, replyCode, replyText, exchange,
                            routingKey);
                logger.warn("something is wrong while processing return callback", e);
            }
        }
    };
}
 
開發者ID:zeroDivisible,項目名稱:spring-rabbitmq-example,代碼行數:20,代碼來源:AmqpTemplateFactory.java

示例8: replyIfNecessary

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
private void replyIfNecessary(Message message, Object result, RabbitTemplate mqTemplate) {
	MessageProperties messageProperties = message.getMessageProperties();
	String correlationId = null;
	try {
		correlationId = new String(messageProperties.getCorrelationId(), DEFAULT_CHARSET);
	} catch (Exception ignored) {
		try {
			correlationId = (String) SerializationUtils.deserialize(messageProperties.getCorrelationId());
		} catch (Exception warnException) {
			LogUtil.warn(logger, "#####獲取correlationId失敗,可能導致客戶端掛起", warnException);
		}
	}
	boolean isNecessary = result != null && messageProperties.getReplyTo() != null;
	if (isNecessary) {
		mqTemplate.send(messageProperties.getReplyTo(), correlationId == null ? mqMessageConverter.toSendMessage(result) : mqMessageConverter.toReplyMessage(result, correlationId));
	}
}
 
開發者ID:xiaolongzuo,項目名稱:zxl,代碼行數:18,代碼來源:MQServer.java

示例9: main

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
public static void main(String[] args) throws Exception
{
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

    // invoke the CONFIG
    /*
     * application context then starts the message listener container, and
     * the message listener container bean starts listening for messages
     */
    ctx.register(RabbitMQConfig.class);
    ctx.refresh();
    
    RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);

    System.out.println("* Waiting 3 seconds...");
    Thread.sleep(3000);
    System.out.println("* Sending message...");
    
    rabbitTemplate.convertAndSend(queueName, "* Hello from RabbitMQ!");

    System.exit(0);
}
 
開發者ID:huangye177,項目名稱:spring4probe,代碼行數:23,代碼來源:RabbitMQApp.java

示例10: createProxy

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@SuppressWarnings("unchecked")
public static <T> T createProxy(Class<T> clazz, int timeout) {
	RabbitTemplate rabbitTemplate = RabbitConfiguration.rabbitTemplate();
	if (rabbitTemplate == null) {
		throw new RuntimeException("��Ϣ�������Ѿ�崻�������ϵ����Ա��");
	}
	AmqpProxyFactoryBean amqpProxyFactoryBean = new AmqpProxyFactoryBean();
	amqpProxyFactoryBean.setAmqpTemplate(rabbitTemplate);
	amqpProxyFactoryBean.setServiceInterface(clazz);
	amqpProxyFactoryBean.afterPropertiesSet();
	amqpProxyFactoryBean.setRemoteInvocationFactory(new SimpleRemoteInvocationFactory());

	Object springOrigProxy = createProxy(amqpProxyFactoryBean);
	RabbitMethodInterceptor methodInterceptor = new RabbitMethodInterceptor(timeout);

	ProxyFactory factory = new ProxyFactory();
	factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, methodInterceptor));
	factory.setProxyTargetClass(false);
	factory.addInterface(clazz);
	factory.setTarget(springOrigProxy);
	return (T) factory.getProxy();

}
 
開發者ID:jiangchanghui,項目名稱:JavaFxClient,代碼行數:24,代碼來源:ServiceProxyFactory.java

示例11: TicketingServiceProducerImpl

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
/**
 * Constructor
 * @param rabbitTemplate Rabbit Template
 * @param ticketServiceResponseExchange Event Exchange
 */
public TicketingServiceProducerImpl(final RabbitTemplate rabbitTemplate, final Exchange ticketServiceResponseExchange)
{
    this.ticketServiceResponseExchange = ticketServiceResponseExchange;
    this.rabbitTemplate = rabbitTemplate;
 
}
 
開發者ID:dellemc-symphony,項目名稱:ticketing-service-paqx-parent-sample,代碼行數:12,代碼來源:TicketingServiceProducerImpl.java

示例12: rabbitTemplate

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
/**
 * This returns the RabbitMQ template.
 *
 * @return The RabbitMQ template.
 */
@Bean
RabbitTemplate rabbitTemplate()
{
    final RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory);
    template.setMessageConverter(messageConverter());
    template.setRetryTemplate(retryTemplate());
    return template;
}
 
開發者ID:dellemc-symphony,項目名稱:ticketing-service-paqx-parent-sample,代碼行數:14,代碼來源:TicketingServiceRabbitConfig.java

示例13: getExchangeFromRabbitTemplate

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
private String getExchangeFromRabbitTemplate(Object target) {
  String exchange = null;
  if (target instanceof RabbitTemplate) {
    exchange = ((RabbitTemplate) target).getExchange();
  }
  return exchange;
}
 
開發者ID:netshoes,項目名稱:spring-cloud-sleuth-amqp,代碼行數:8,代碼來源:AmqpTemplateAspect.java

示例14: rabbitTemplate

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnMissingBean(RabbitTemplate.class)
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    RetryTemplate retryTemplate = new RetryTemplate();
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(500);
    backOffPolicy.setMultiplier(10.0);
    backOffPolicy.setMaxInterval(10000);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    template.setRetryTemplate(retryTemplate);
    template.setMessageConverter(messageConverter);
    return template;
}
 
開發者ID:lodsve,項目名稱:lodsve-framework,代碼行數:16,代碼來源:RabbitConfiguration.java

示例15: commandBusRabbitTemplate

import org.springframework.amqp.rabbit.core.RabbitTemplate; //導入依賴的package包/類
@Bean
@Autowired
public RabbitTemplate commandBusRabbitTemplate(final ConnectionFactory commandBusConnectionFactory, final MessageConverter commandBusMessageConverter) {

    log.info("Creating command bus RabbitMQ template with a custom JSON converter");
    final RabbitTemplate rabbitTemplate = new RabbitTemplate(commandBusConnectionFactory);
    rabbitTemplate.setMessageConverter(commandBusMessageConverter);

    return rabbitTemplate;
}
 
開發者ID:sem2nawara,項目名稱:acme-solution,代碼行數:11,代碼來源:CommandBusConfigurer.java


注:本文中的org.springframework.amqp.rabbit.core.RabbitTemplate類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。