当前位置: 首页>>代码示例>>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;未经允许,请勿转载。