Spring Boot中通过RabbitTemplate主动pull(get)消息的例子
2018-02-09 10:44
1966 查看
import java.io.IOException; import java.util.Properties; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.rabbit.core.ChannelCallback; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RabbitAdminService { private static final Logger LOGGER = LoggerFactory.getLogger(RabbitAdminService.class); @Autowired AmqpAdmin rabbitAdmin; @Autowired RabbitTemplate rabbitTemplate; public int getCount(String queueName) { Properties properties = rabbitAdmin.getQueueProperties(queueName); return (Integer)properties.get(RabbitAdmin.QUEUE_MESSAGE_COUNT); } @PostConstruct public void init(){ new Thread( new Runnable(){ @Override public void run(){ while(true){ try{ Thread.sleep(1000); processQueue(MQConstants.INDUSTRYSMS_QUEUE); }catch(Exception e){ } } } }).start(); } public static class ChannelCallbackImpl implements ChannelCallback<Message>{ private String queueName; public ChannelCallbackImpl(String queueName){ this.queueName = queueName; } @Override public Message doInRabbit(Channel channel) { GetResponse response = null; try { response = channel.basicGet(queueName, false); Message message = Message.parseFrom(response.getBody()); if(message != null){ int mobiles = message.getMessageTosList().size(); LOGGER.info("号码:{}", mobiles); } channel.basicAck(response.getEnvelope().getDeliveryTag(), false); return message; } catch(Exception e) { try { channel.basicNack(response.getEnvelope().getDeliveryTag(), false, true); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } } public void processQueue(String queueName) { rabbitTemplate.execute(new ChannelCallbackImpl(queueName)); } }
相关文章推荐
- SpringBoot通过restTemplate实现消费服务
- 集群与负载均衡系列(6)——消息队列之rabbitMQ+spring-boot+spring amqp发送可靠的消息
- spring boot Rabbitmq集成,延时消息队列实现
- spring boot RestTemplate 发送 get 请求
- activemq的连接池,通过spring的JmsTemplate发送消息到指定的Destination
- Spring boot通过JPA和Mybatis同时连接2个关系数据库的例子
- spring boot 使用@RestController 和 @Controller 构造常见http get ,post请求例子
- Spring Boot + RabbitMQ 实现消息队列场景
- spring-boot rabbitmq 例子
- Spring-boot通过redisTemplate使用redis(无须手动序列化)
- Spring Boot RabbitMQ 延迟消息实现完整版示例
- springboot jpa Query使用原生SQL例子--测试通过
- spring boot Rabbitmq集成,延时消息队列实现
- activemq的连接池,通过spring的JmsTemplate发送消息到指定的Destination
- springboot+rabbitmq例子
- spring boot RestTemplate 发送 get 请求使用误区
- springboot+rabbitMq整合开发实战一
- 通过Spring Boot + Mybatis + Redis快速搭建现代化Web项目
- SpringBoot 实现WebSocket进行消息发送(适用于SpringMVC)
- Spring通过实现getBean方法获得Bean的实例