org.springframework.amqp.rabbit.annotation.RabbitHandler Java Examples

The following examples show how to use org.springframework.amqp.rabbit.annotation.RabbitHandler. 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: RabbitReceiver.java    From code with Apache License 2.0 7 votes vote down vote up
/**
 * 
 * 	spring.rabbitmq.listener.order.queue.name=queue-2
	spring.rabbitmq.listener.order.queue.durable=true
	spring.rabbitmq.listener.order.exchange.name=exchange-1
	spring.rabbitmq.listener.order.exchange.durable=true
	spring.rabbitmq.listener.order.exchange.type=topic
	spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
	spring.rabbitmq.listener.order.key=springboot.*
 * @param order
 * @param channel
 * @param headers
 * @throws Exception
 */
@RabbitListener(bindings = @QueueBinding(
		value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}", 
		durable="${spring.rabbitmq.listener.order.queue.durable}"),
		exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}", 
		durable="${spring.rabbitmq.listener.order.exchange.durable}", 
		type= "${spring.rabbitmq.listener.order.exchange.type}", 
		ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
		key = "${spring.rabbitmq.listener.order.key}"
		)
)
@RabbitHandler
public void onOrderMessage(@Payload com.bfxy.springboot.entity.Order order, 
		Channel channel, 
		@Headers Map<String, Object> headers) throws Exception {
	System.err.println("--------------------------------------");
	System.err.println("消费端order: " + order.getId());
	Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
	//手工ACK
	channel.basicAck(deliveryTag, false);
}
 
Example #2
Source File: RabbitReceiver.java    From code with Apache License 2.0 6 votes vote down vote up
@RabbitListener(bindings = @QueueBinding(
		value = @Queue(value = "queue-1", 
		durable="true"),
		exchange = @Exchange(value = "exchange-1", 
		durable="true", 
		type= "topic", 
		ignoreDeclarationExceptions = "true"),
		key = "springboot.*"
		)
)
@RabbitHandler
public void onMessage(Message message, Channel channel) throws Exception {
	System.err.println("--------------------------------------");
	System.err.println("消费端Payload: " + message.getPayload());
	Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
	//手工ACK
	channel.basicAck(deliveryTag, false);
}
 
Example #3
Source File: MqListener.java    From iot-dc with Apache License 2.0 6 votes vote down vote up
/**
 * 指令队列
 *
 * @param message
 */
@RabbitListener(queues = "rtu_inst_queue")
@RabbitHandler
public void command(Message message) throws IOException {
    String msg = new String(message.getBody());
    LOGGER.info("rtu-command: {}", msg);
    RTUCommandInfo commandInfo = JsonUtils.jsonStr2Obj(msg, RTUCommandInfo.class);
    if (commandInfo == null ||
            StringUtils.isEmpty(commandInfo.getSn()) ||
            StringUtils.isEmpty(commandInfo.getInstruction()) ||
            StringUtils.isEmpty(commandInfo.getInstructionType())) {
        LOGGER.warn("bad command: {}", commandInfo);
        return;
    }
    CommandHandler.writeCommand(commandInfo.getSn(), commandInfo.getInstruction(), commandInfo.getInstructionType());
}
 
Example #4
Source File: RabbitMQOrderReceiver.java    From HIS with Apache License 2.0 6 votes vote down vote up
@RabbitHandler
public void handle(String msg){
    LOGGER.info("receive order message msg:{}",msg);
    String[] temp = msg.split("&");
    if(temp.length != 2){
        LOGGER.warn("处方单超时处理失败: msg:{}",msg);
        return;
    }
    Long id = new Long(temp[0]);
    int type = Integer.parseInt(temp[1]);
    int handleCount = 0;
    if(type == 4){
        handleCount = dmsFeeRabbitMQService.herbalOutOfTime(id);
    }else if(type == 5){
        handleCount = dmsFeeRabbitMQService.medicineOutOfTime(id);
    }else{
        handleCount = dmsFeeRabbitMQService.nonDrugOutOfTime(id);
    }
    System.out.println("处理结果:" + handleCount);
}
 
Example #5
Source File: RabbitMQOrderReceiver.java    From HIS with Apache License 2.0 6 votes vote down vote up
@RabbitHandler
public void handle(String msg){
    LOGGER.info("receive order message msg:{}",msg);
    String[] temp = msg.split("&");
    if(temp.length != 2){
        LOGGER.warn("处方单超时处理失败: msg:{}",msg);
        return;
    }
    Long id = new Long(temp[0]);
    int type = Integer.parseInt(temp[1]);
    int handleCount = 0;
    if(type == 4){
        handleCount = dmsFeeRabbitMQService.herbalOutOfTime(id);
    }else if(type == 5){
        handleCount = dmsFeeRabbitMQService.medicineOutOfTime(id);
    }else{
        handleCount = dmsFeeRabbitMQService.nonDrugOutOfTime(id);
    }
    System.out.println("处理结果:" + handleCount);
}
 
Example #6
Source File: RabbitMQOrderReceiver.java    From HIS with Apache License 2.0 6 votes vote down vote up
@RabbitHandler
public void handle(String msg){
    LOGGER.info("receive order message msg:{}",msg);
    String[] temp = msg.split("&");
    if(temp.length != 2){
        LOGGER.warn("处方单超时处理失败: msg:{}",msg);
        return;
    }
    Long id = new Long(temp[0]);
    int type = Integer.parseInt(temp[1]);
    int handleCount = 0;
    if(type == 4){
        handleCount = dmsFeeRabbitMQService.herbalOutOfTime(id);
    }else if(type == 5){
        handleCount = dmsFeeRabbitMQService.medicineOutOfTime(id);
    }else{
        handleCount = dmsFeeRabbitMQService.nonDrugOutOfTime(id);
    }
    System.out.println("处理结果:" + handleCount);
}
 
Example #7
Source File: RabbitMQOrderReceiver.java    From HIS with Apache License 2.0 6 votes vote down vote up
@RabbitHandler
public void handle(String msg){
    LOGGER.info("receive order message msg:{}",msg);
    String[] temp = msg.split("&");
    if(temp.length != 2){
        LOGGER.warn("处方单超时处理失败: msg:{}",msg);
        return;
    }
    Long id = new Long(temp[0]);
    int type = Integer.parseInt(temp[1]);
    int handleCount = 0;
    if(type == 4){
        handleCount = dmsFeeRabbitMQService.herbalOutOfTime(id);
    }else if(type == 5){
        handleCount = dmsFeeRabbitMQService.medicineOutOfTime(id);
    }else{
        handleCount = dmsFeeRabbitMQService.nonDrugOutOfTime(id);
    }
    System.out.println("处理结果:" + handleCount);
}
 
Example #8
Source File: AbstractDownCommandReceiver.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * 订阅处理下行指令
 *
 * @param commandProto  指令信息
 * @param rabbitChannel rabbit通道
 * @param message       消息
 * @throws Exception 异常
 */
@RabbitHandler
public void receiveDownCommand(CommandProto commandProto, com.rabbitmq.client.Channel rabbitChannel, Message message) throws Exception {
    try {
        //终端不在线
        Long terminalId = commandProto.getTerminalId();
        Channel channel = SessionUtil.getChannel(terminalId);
        if (channel == null) {
            log.info("处理下发指令,终端不在线{}", commandProto);
            commandProto.setSendResult(CommandSendResultEnum.TERMINAL_OFFLINE);
            messageSender.sendUpCommand(commandProto);
            return;
        }

        registerDownCommand(commandProto);
        printLog(channel, commandProto);
        handleDownCommand(channel, commandProto);
    } catch (Exception e) {
        log.error("处理下发指令异常{}", commandProto, e);
        rabbitChannel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
 
Example #9
Source File: MyAckReceiver.java    From springboot-learn with MIT License 6 votes vote down vote up
@RabbitHandler
public void process(String sendMsg, Channel channel, Message message) {

    System.out.println("AckReceiver  : 收到发送消息 " + sendMsg + ",收到消息时间"
            + LocalDateTime.now(ZoneId.systemDefault()));

    try {
        //告诉服务器收到这条消息已经被当前消费者消费了,可以在队列安全删除,这样后面就不会再重发了,
        //否则消息服务器以为这条消息没处理掉,后续还会再发
        //第二个参数是消息的标识,false只确认当前一个消息收到,true确认所有consumer获得的消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("process success");
    } catch (Exception e) {
        System.out.println("process fail");
        try {
            //ack返回false,并重新回到队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }

}
 
Example #10
Source File: MqListener.java    From iot-dc with Apache License 2.0 6 votes vote down vote up
/**
 * 指令队列
 *
 * @param message
 */
@RabbitListener(queues = "rtu_inst_queue")
@RabbitHandler
public void command(Message message) throws IOException {
    String msg = new String(message.getBody());
    LOGGER.info("rtu-command: {}", msg);
    RTUCommandInfo commandInfo = JsonUtils.jsonStr2Obj(msg, RTUCommandInfo.class);
    if (commandInfo == null ||
            StringUtils.isEmpty(commandInfo.getSn()) ||
            StringUtils.isEmpty(commandInfo.getInstruction()) ||
            StringUtils.isEmpty(commandInfo.getInstructionType())) {
        LOGGER.warn("bad command: {}", commandInfo);
        return;
    }
    CommandHandler.writeCommand(commandInfo.getSn(), commandInfo.getInstruction(), commandInfo.getInstructionType());
}
 
Example #11
Source File: MyAckReceiver2.java    From springboot-learn with MIT License 6 votes vote down vote up
@RabbitHandler
public void process(String sendMsg, Channel channel, Message message) {

    System.out.println("AckReceiver  : 收到发送消息 " + sendMsg.toString() + ",收到消息时间"
            + LocalDateTime.now(ZoneId.systemDefault()));

    MessageObj messageObj = JSON.parseObject(sendMsg, MessageObj.class);
    System.out.println(messageObj.toString());
    try {
        //告诉服务器收到这条消息已经被当前消费者消费了,可以在队列安全删除,这样后面就不会再重发了,
        //否则消息服务器以为这条消息没处理掉,后续还会再发
        //第二个参数是消息的标识,false只确认当前一个消息收到,true确认所有consumer获得的消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("receiver success");
    } catch (Exception e) {
        System.out.println("receiver fail");
        e.printStackTrace();
    }

}
 
Example #12
Source File: MqListener.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 刷新 iot信息
 *
 * @param message
 * @throws Exception
 */
@RabbitListener(queues = "rtu_refresh_queue")
@RabbitHandler
public void refreshIotInfo(Message message) throws Exception {
    String msg = new String(message.getBody());
    if (GlobalInfo.Global_Iot_Redis_Key.equals(msg)) {
        LOGGER.info("start refresh GlobalInfo, rtu_refresh key is : {}", msg);
        boolean flag = ioTService.refreshIotMapper2Global();
        if (flag) {
            ChannelManagerHandler.refreshRTUChannelInfo();
        }
    }
}
 
Example #13
Source File: RegEmailQueueReceiver.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@RabbitHandler//@RabbitHandler来实现具体消费
public void QueueReceiver(String reg_email) {

    try {
        //send email
        System.out.println("Receiver : " + reg_email);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #14
Source File: DingTalkServiceChangeReceiveListener.java    From pig with MIT License 5 votes vote down vote up
@RabbitHandler
public void receive(String text) {
    long startTime = System.currentTimeMillis();
    log.info("消息中心接收到钉钉发送请求-> 内容:{} ", text);
    dingTalkMessageHandler.process(text);
    long useTime = System.currentTimeMillis() - startTime;
    log.info("调用 钉钉网关处理完毕,耗时 {}毫秒", useTime);
}
 
Example #15
Source File: MailListener.java    From Blog with Apache License 2.0 5 votes vote down vote up
@RabbitHandler
    public void executeSms(Map<String, String> map) {
        String mail = map.get("mail");
        String code = map.get("code");

        try {
//            this.sendMail(mail, code);
            Thread.sleep(6000);
            userService.updateMailSendState(mail, code, MailConfig.MAIL_STATE_OK);
            log.info(mail + "-" + code + "-发送成功");
        } catch (Exception e) {
            userService.updateMailSendState(mail, code, MailConfig.MAIL_STATE_ERROR);
            log.error(mail + code + "发送失败-" + e.getMessage());
        }
    }
 
Example #16
Source File: Receiver.java    From springboot-example with Apache License 2.0 5 votes vote down vote up
@RabbitHandler
/**
 * 监听消费消息
 */
public void process(String message) {
    System.out.println("Direct 消费消息:" + message);
}
 
Example #17
Source File: MobileCodeReceiveListener.java    From pig with MIT License 5 votes vote down vote up
@RabbitHandler
public void receive(MobileMsgTemplate mobileMsgTemplate) {
    long startTime = System.currentTimeMillis();
    log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext());
    String channel = mobileMsgTemplate.getChannel();
    SmsMessageHandler messageHandler = messageHandlerMap.get(channel);
    if (messageHandler == null) {
        log.error("没有找到指定的路由通道,不进行发送处理完毕!");
        return;
    }

    messageHandler.execute(mobileMsgTemplate);
    long useTime = System.currentTimeMillis() - startTime;
    log.info("调用 {} 短信网关处理完毕,耗时 {}毫秒", channel, useTime);
}
 
Example #18
Source File: PointValueReceiver.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
@RabbitHandler
public void pointValueReceive(PointValue pointValue) {
    if (null == pointValue || null == pointValue.getDeviceId() || null == pointValue.getPointId()) {
        log.error("Invalid data: {}", pointValue);
        return;
    }

    /*
    Convention:
    PointId = 0 indicates device status
    PointId > 0 indicates device point data
     */
    if (pointValue.getPointId().equals(0L)) {
        log.info("Received device({}) status({})", pointValue.getDeviceId(), pointValue.getRawValue());
        // Save device status to redis, 15 minutes
        redisUtil.setKey(
                Common.Cache.DEVICE_STATUS_KEY_PREFIX + pointValue.getDeviceId(),
                pointValue.getRawValue(),
                15,
                TimeUnit.MINUTES);
    } else {
        // LinkedBlockingQueue ThreadPoolExecutor
        threadPoolExecutor.execute(() -> {
            log.debug("Received data: {}", pointValue);
            // Save device point data to redis, 15 minutes
            redisUtil.setKey(
                    Common.Cache.REAL_TIME_VALUE_KEY_PREFIX + pointValue.getDeviceId() + "_" + pointValue.getPointId(),
                    pointValue.getValue(),
                    15,
                    TimeUnit.MINUTES);
            // Push device point data to MQ
            pointValueService.add(pointValue);
        });
    }
}
 
Example #19
Source File: RoleDeleteConsumer.java    From cloud-service with MIT License 5 votes vote down vote up
/**
 * 接收到删除角色的消息<br>
 * 删除角色和菜单关系
 * 
 * @param roleId
 */
@RabbitHandler
public void roleDeleteHandler(Long roleId) {
	log.info("接收到删除角色的消息,roleId:{}", roleId);
	try {
		roleMenuDao.delete(roleId, null);
	} catch (Exception e) {
		log.error("角色删除消息处理异常", e);
	}
}
 
Example #20
Source File: LogConsumer.java    From cloud-service with MIT License 5 votes vote down vote up
/**
 * 处理消息
 * 
 * @param log
 */
@RabbitHandler
public void logHandler(Log log) {
	try {
		logService.save(log);
	} catch (Exception e) {
		logger.error("保存日志失败,日志:{},异常:{}", log, e);
	}

}
 
Example #21
Source File: LogRabbitListener.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@RabbitHandler
public void receive(AuthLog authLog) {
	Log sysLog = authLog.getLog();
	MDC.put(CommonConstant.KEY_USER, authLog.getLog().getCreateBy());
	Date currentDate = new Date();
	if (null == sysLog.getCreateTime()) sysLog.setCreateTime(currentDate);
	if (null == sysLog.getUpdateTime()) sysLog.setUpdateTime(currentDate);
	LogInfo logInfo = new LogInfo();
	BeanUtils.copyProperties(sysLog, logInfo);
	logInfoService.saveOrUpdate(logInfo);
	MDC.remove(CommonConstant.KEY_USER);
}
 
Example #22
Source File: MobileServiceChangeReceiveListener.java    From pig with MIT License 5 votes vote down vote up
@RabbitHandler
public void receive(MobileMsgTemplate mobileMsgTemplate) {
    long startTime = System.currentTimeMillis();
    log.info("消息中心接收到短信发送请求-> 手机号:{} -> 信息体:{} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext());
    String channel = mobileMsgTemplate.getChannel();
    SmsMessageHandler messageHandler = messageHandlerMap.get(channel);
    if (messageHandler == null) {
        log.error("没有找到指定的路由通道,不进行发送处理完毕!");
        return;
    }

    messageHandler.execute(mobileMsgTemplate);
    long useTime = System.currentTimeMillis() - startTime;
    log.info("调用 {} 短信网关处理完毕,耗时 {}毫秒", mobileMsgTemplate.getType(), useTime);
}
 
Example #23
Source File: WorkReceiver.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@RabbitHandler
public void receive(String in) {
    StopWatch watch = new StopWatch();
    watch.start();
    LOGGER.info("instance {} [x] Received '{}'", this.instance, in);
    doWork(in);
    watch.stop();
    LOGGER.info("instance {} [x] Done in {}s", this.instance, watch.getTotalTimeSeconds());
}
 
Example #24
Source File: UserPointReceiver.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
@RabbitHandler
public void process(String msg) {
    // 这里转换成相应的对象还有问题,确保全部都是 json ?
    RegistPoint payload = JsonMapper.INSTANCE.fromJson(msg, RegistPoint.class);
    Result<?> result = pointServiceClient.addRegistPoint(payload.getUserId());
    if (result.success()) {
        // 操作成功后,删除可靠消息;失败则不处理,等待超时处理
        messageServiceClient.deleteMessageByMessageId(payload.getMessageId());
    }
}
 
Example #25
Source File: MqListener.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 刷新 iot信息
 *
 * @param message
 * @throws Exception
 */
@RabbitListener(queues = "rtu_refresh_queue")
@RabbitHandler
public void refreshIotInfo(Message message) throws Exception {
    String msg = new String(message.getBody());
    if (GlobalInfo.Global_Iot_Redis_Key.equals(msg)) {
        LOGGER.info("start refresh GlobalInfo, rtu_refresh key is : {}", msg);
        boolean flag = ioTService.refreshIotMapper2Global();
        if (flag) {
            ChannelManagerHandler.refreshRTUChannelInfo();
        }
    }
}
 
Example #26
Source File: NotificationDispatcher.java    From cola-cloud with MIT License 5 votes vote down vote up
@RabbitHandler
public void dispatch(@Payload Notification notification){
    if(notification != null && exchangers != null){
        exchangers.forEach((exchanger) -> {
            if(exchanger.support(notification)){
                //添加到线程池进行处理
               executorService.submit(new NotificationTask(exchanger,notification));
            }
        });
    }
}
 
Example #27
Source File: Tut2Receiver.java    From java-tutorial with MIT License 5 votes vote down vote up
@RabbitHandler
public void receiver(String inMsg) throws InterruptedException {
    StopWatch watch = new StopWatch();
    watch.start();
    System.out.println("instance " + this.instance +
            " [x] Received '" + inMsg + "'");
    doWork(inMsg);
    watch.stop();
    System.out.println("instance " + this.instance +
            " [x] Done in " + watch.getTotalTimeSeconds() + "s");

}
 
Example #28
Source File: AbstractMqListener.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@RabbitHandler
@Override
public void process(T obj, Message message, Channel channel) throws Exception {
    // 确认消息
    this.basicAck(channel, message.getMessageProperties().getDeliveryTag());

    if (!this.doProcess(obj, message, channel)) {
        log.error("消息确认失败未消费");
        // 处理业务发生异常,不消费消息,可重新再次消费消息
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
    }
}
 
Example #29
Source File: SmsListener.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 发送短信
 * @param message 监听到的数据
 */
@RabbitHandler
public SendSmsResponse sendSms(Map<String,String> message){
       LogBack.info("手机号:{},验证码:{};", message.get("mobile"), message.get("code"));
	try {
		return smsUtil.sendSms(message.get("mobile"), template_code, sign_name,
				"{\"code\":\"" + message.get("code") + "\"}");
       } catch (ClientException | NullPointerException e) {
           LogBack.error("发送手机验证码失败:{}", e.getMessage());
		e.printStackTrace();
	}

       return null;
}
 
Example #30
Source File: LogReceiveListener.java    From pig with MIT License 5 votes vote down vote up
@RabbitHandler
public void receive(LogVO logVo) {
    SysLog sysLog = logVo.getSysLog();
    MDC.put(KEY_USER, logVo.getUsername());
    sysLog.setCreateBy(logVo.getUsername());
    sysLogService.insert(sysLog);
    MDC.remove(KEY_USER);
}