org.springframework.amqp.rabbit.annotation.RabbitListener Java Examples
The following examples show how to use
org.springframework.amqp.rabbit.annotation.RabbitListener.
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: AccessLogsHandler.java From open-cloud with MIT License | 8 votes |
/** * 接收访问日志 * * @param access */ @RabbitListener(queues = QueueConstants.QUEUE_ACCESS_LOGS) public void accessLogsQueue(@Payload Map access) { try { if (access != null) { GatewayAccessLogs logs = BeanConvertUtils.mapToObject(access, GatewayAccessLogs.class); if (logs != null) { if (logs.getIp() != null) { logs.setRegion(ipRegionService.getRegion(logs.getIp())); } logs.setUseTime(logs.getResponseTime().getTime() - logs.getRequestTime().getTime()); gatewayLogsMapper.insert(logs); } } } catch (Exception e) { log.error("error:", e); } }
Example #2
Source File: AsyncRPCServer.java From SpringBootBucket with MIT License | 7 votes |
@RabbitListener(queues = QUEUE_ASYNC_RPC_WITH_FIXED_REPLY) public void processAsyncRpcFixed(User user, @Header(AmqpHeaders.REPLY_TO) String replyTo, @Header(AmqpHeaders.CORRELATION_ID) byte[] correlationId) { // String body = new String(message.getBody(), Charset.forName("UTF-8")); // User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){}); logger.info("user.name={}", user.getName()); logger.info("use a fixed reply queue={}, correlationId={}", replyTo, new String(correlationId)); ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(user.getName()); asyncResult.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { amqpTemplate.convertAndSend(replyTo, (Object) result, m -> { //https://stackoverflow.com/questions/42382307/messageproperties-setcorrelationidstring-is-not-working m.getMessageProperties().setCorrelationId(new String(correlationId)); return m; }); } @Override public void onFailure(Throwable ex) { logger.error("接受到QUEUE_ASYNC_RPC_WITH_FIXED_REPLY失败", ex); } }); }
Example #3
Source File: RabbitReceiver.java From code with Apache License 2.0 | 7 votes |
/** * * 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 #4
Source File: ElasticSearchReceiver.java From ChengFeng1.5 with MIT License | 6 votes |
@RabbitListener(queues = ChengfengConstant.RabbitMQ.QUEUE_NAME_ELASTICSEARCH) public void process(String init, Message message, Channel channel) throws IOException { try { log.info(init + "消息收到" + "初始化数据库内容到elasticsearch"); List<PurchaseProduct> purchaseProducts = productMapper.selectAllPurchaseProducts(); purchaseProducts.stream().forEach(purchaseProduct -> { double ratio = purchaseProduct.getGoodEvaluationNums().doubleValue() / purchaseProduct.getEvaluationNums().doubleValue(); BigDecimal ratioDecimal = new BigDecimal(ratio); purchaseProduct.setGoodRatio(ratioDecimal.setScale(2, RoundingMode.HALF_UP).doubleValue()); log.info(purchaseProduct.getGoodRatio().toString()); purchaseProduct.setDetail(new StringBuilder().append(purchaseProduct.getName()).append(purchaseProduct.getSubtitle()).toString()); productRepository.save(purchaseProduct); }); }finally { channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); } }
Example #5
Source File: SmsListener.java From mogu_blog_v2 with Apache License 2.0 | 6 votes |
@RabbitListener(queues = "mogu.sms") public void sendSms(Map<String, String> map) { try { SendSmsResponse response = smsUtil.sendSms( map.get("mobile"), map.get("template_code"), map.get("sign_name"), map.get("param")); System.out.println("code:" + response.getCode()); System.out.println("message:" + response.getMessage()); } catch (ClientException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Example #6
Source File: CacheListener.java From heimdall with Apache License 2.0 | 6 votes |
/** * Cleans the Rabbit cache with specific message. * * @param message {@link Message} */ @RabbitListener( queues = RabbitConstants.LISTENER_HEIMDALL_CLEAN_CACHE) public void cleanCaches(final Message message) { String key = (String) rabbitTemplate.getMessageConverter().fromMessage(message); if (key != null && !key.isEmpty()) { if (key.contains(";")) { String[] split = key.split(";"); log.info("Clean cache with key: {} and id: {} ", split[0], split[1]); cacheService.clean(split[0], split[1]); } else { log.info("Clean cache with key: {}", key); cacheService.clean(key); } } else { log.info("Clean all caches"); cacheService.clean(); } }
Example #7
Source File: MQReceiver.java From goods-seckill with Apache License 2.0 | 6 votes |
@RabbitListener(queues = MQConfig.MIAOSHA_QUEUE) public void receive(String message) { LOG.info("========receive message: " + message + "========="); MiaoshaMessage mm = RedisService.stringToBean(message, MiaoshaMessage.class); Long goodsId = mm.getGoodsId(); Long userId = mm.getUserId(); // 判断库存 GoodsVo goodsVo = goodsService.getGoodsById(goodsId); if (goodsVo.getStock_count() <= 0) { return; } // 判断是否是重复秒杀 MiaoshaOrderEntity order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId); if (order != null) { return; } // 生成秒杀订单 miaoshaService.miaosha(userId, goodsVo); }
Example #8
Source File: BookHandler.java From springboot-learning-experience with Apache License 2.0 | 6 votes |
/** * <p>TODO 该方案是 spring-boot-data-amqp 默认的方式,不太推荐。具体推荐使用 listenerManualAck()</p> * 默认情况下,如果没有配置手动ACK, 那么Spring Data AMQP 会在消息消费完毕后自动帮我们去ACK * 存在问题:如果报错了,消息不会丢失,但是会无限循环消费,一直报错,如果开启了错误日志很容易就吧磁盘空间耗完 * 解决方案:手动ACK,或者try-catch 然后在 catch 里面讲错误的消息转移到其它的系列中去 * spring.rabbitmq.listener.simple.acknowledge-mode=manual * <p> * * @param book 监听的内容 */ @RabbitListener(queues = {RabbitConfig.DEFAULT_BOOK_QUEUE}) public void listenerAutoAck(Book book, Message message, Channel channel) { // TODO 如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉 final long deliveryTag = message.getMessageProperties().getDeliveryTag(); try { log.info("[listenerAutoAck 监听的消息] - [{}]", book.toString()); // TODO 通知 MQ 消息已被成功消费,可以ACK了 channel.basicAck(deliveryTag, false); } catch (IOException e) { try { // TODO 处理失败,重新压入MQ channel.basicRecover(); } catch (IOException e1) { e1.printStackTrace(); } } }
Example #9
Source File: GoodsListener.java From leyou with Apache License 2.0 | 6 votes |
/** * 处理delete的消息 * * @param id */ @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "leyou.delete.index.queue", durable = "true"), exchange = @Exchange( value = "leyou.item.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = "item.delete") ) public void listenDelete(Long id) { if (id == null) { return; } // 删除索引 this.searchService.deleteIndex(id); }
Example #10
Source File: GoodsListener.java From leyou with Apache License 2.0 | 6 votes |
/** * 处理insert和update的消息 * * @param id * @throws Exception */ @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "leyou.create.index.queue", durable = "true"), exchange = @Exchange( value = "leyou.item.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = {"item.insert", "item.update"}) ) public void listenCreate(Long id) throws Exception { if (id == null) { return; } // 创建或更新索引 this.searchService.createIndex(id); }
Example #11
Source File: MqListener.java From iot-dc with Apache License 2.0 | 6 votes |
/** * 指令队列 * * @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 #12
Source File: MongodbReceiver.java From ChengFeng1.5 with MIT License | 6 votes |
@RabbitListener(queues = ChengfengConstant.RabbitMQ.QUEUE_NAME_MONGODB) public void process(String init,Message message, Channel channel){ try{ log.info(init+"消息收到"+"初始化数据库内容到mongodb"); List<Journalism> journalisms = journalismMapper.selectAllJournalisms(); journalisms.stream().parallel().forEach(journalism -> { journalism.setCommentNums(0); Random random=new Random(); journalism.setStarNums(random.nextInt(300)); mongoRepository.save(journalism); }); }finally { try { channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); } catch (IOException e) { e.printStackTrace(); } } }
Example #13
Source File: MqListener.java From iot-dc with Apache License 2.0 | 6 votes |
/** * 指令队列 * * @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 #14
Source File: AsyncRPCServer.java From SpringBootBucket with MIT License | 6 votes |
@RabbitListener(queues = QUEUE_ASYNC_RPC) public void processAsyncRpc(Message message, @Header(AmqpHeaders.REPLY_TO) String replyTo) { String body = new String(message.getBody(), Charset.forName("UTF-8")); User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){}); logger.info("recevie message {} and reply to {}, user.name={}", body, replyTo, user.getName()); if (replyTo.startsWith("amq.rabbitmq.reply-to")) { logger.debug("starting with version 3.4.0, the RabbitMQ server now supports Direct reply-to"); } else { logger.info("fall back to using a temporary reply queue"); } ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(body); asyncResult.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { amqpTemplate.convertAndSend(replyTo, result); } @Override public void onFailure(Throwable ex) { logger.error("接受到QUEUE_ASYNC_RPC失败", ex); } }); }
Example #15
Source File: MQReceiver.java From seckill with Apache License 2.0 | 6 votes |
@RabbitListener(queues = MQConfig.SECKILL_QUEUE) public void receive(String message) { log.info("receive message:" + message); SeckillMessage seckillMessage = RedisService.stringToBean(message, SeckillMessage.class); SeckillUser user = seckillMessage.getSeckillUser(); long goodsId = seckillMessage.getGoodsId(); //判断库存 GoodsVO goods = goodsService.getGoodsVOById(goodsId); int stock = goods.getStockCount(); if (stock < 1) { return; } //判断是否已经秒杀到了 SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId); if (order != null) { return; } //减库存 下订单 写入秒杀订单 seckillService.seckill(user, goods); }
Example #16
Source File: InterceptorListener.java From heimdall with Apache License 2.0 | 6 votes |
/** * Updates the {@link Interceptor} repository. * * @param message {@link Message} */ @RabbitListener(queues = RabbitConstants.LISTENER_HEIMDALL_INTERCEPTORS) public void updateInterceptors(final Message message) { Long interceptorId = (Long) rabbitTemplate.getMessageConverter().fromMessage(message); Interceptor interceptor = interceptorJdbcRepository.findOneInterceptorSimplified(interceptorId); if (Objects.nonNull(interceptor)) { log.info("Updating/Creating Interceptor id: " + interceptorId); interceptorFileService.createFileInterceptor(interceptor); } else { log.info("It was not possible Updating/Creating Interceptor id: " + interceptorId); } }
Example #17
Source File: RouteListener.java From heimdall with Apache License 2.0 | 5 votes |
/** * Updates the {@link ZuulRoute} repository. * * @param message {@link Message} */ @RabbitListener(queues = RabbitConstants.LISTENER_HEIMDAL_ROUTES) public void updateZuulRoutes(final Message message) { try { log.info("Updating Zuul Routes"); cacheService.clean(); heimdallHandlerMapping.setDirty(false); startServer.initApplication(); } catch (Exception e) { log.error(e.getMessage(), e); } }
Example #18
Source File: AmqpReceiver.java From code with Apache License 2.0 | 5 votes |
/** * 数码供应商服务 接收消息 * @param message */ @RabbitListener(bindings = @QueueBinding( exchange = @Exchange("myOrder"), key = "computer", value = @Queue("computerOrder") )) public void processComputer(String message) { log.info("computer MqReceiver: {}", message); }
Example #19
Source File: AmqpReceiver.java From code with Apache License 2.0 | 5 votes |
/** * 水果供应商服务 接收消息 * @param message */ @RabbitListener(bindings = @QueueBinding( exchange = @Exchange("myOrder"), key = "fruit", value = @Queue("fruitOrder") )) public void processFruit(String message) { log.info("fruit MqReceiver: {}", message); }
Example #20
Source File: AmqpReceiver.java From code with Apache License 2.0 | 5 votes |
/** * 1.手动创建队列 @RabbitListener(queues = "myQueue") * 2.自动创建队列 @RabbitListener(queuesToDeclare = @Queue("myQueue")) * 3.自动创建Exchange与Queue绑定 */ @RabbitListener(bindings = @QueueBinding( value = @Queue("myQueue"), exchange = @Exchange("myExchange") )) public void process(String message) { log.info("MqReceiver={}", message); }
Example #21
Source File: GoodsListener.java From leyou with Apache License 2.0 | 5 votes |
/** * 处理insert和update的消息 * * @param id * @throws Exception */ @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "leyou.create.web.queue", durable = "true"), exchange = @Exchange( value = "leyou.item.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = {"item.insert", "item.update"})) public void listenCreate(Long id) throws Exception { if (id == null) { return; } // 创建页面 goodsHtmlService.createHtml(id); }
Example #22
Source File: GoodsListener.java From leyou with Apache License 2.0 | 5 votes |
/** * 处理delete的消息 * * @param id */ @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "leyou.delete.web.queue", durable = "true"), exchange = @Exchange( value = "leyou.item.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = "item.delete")) public void listenDelete(Long id) { if (id == null) { return; } // 删除页面 goodsHtmlService.deleteHtml(id); }
Example #23
Source File: BookHandler.java From springboot-learning-experience with Apache License 2.0 | 5 votes |
@RabbitListener(queues = {RabbitConfig.MANUAL_BOOK_QUEUE}) public void listenerManualAck(Book book, Message message, Channel channel) { log.info("[listenerManualAck 监听的消息] - [{}]", book.toString()); try { // TODO 通知 MQ 消息已被成功消费,可以ACK了 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (IOException e) { // TODO 如果报错了,那么我们可以进行容错处理,比如转移当前消息进入其它队列 } }
Example #24
Source File: RabbitBroadcasterDBEventStoreIT.java From eventeum with Apache License 2.0 | 5 votes |
@RabbitListener(bindings = @QueueBinding( key = "contractEvents.*", value = @Queue("contractEvents"), exchange = @Exchange(value = "ThisIsAExchange", type = ExchangeTypes.TOPIC) )) public void onContractEvent(EventeumMessage message) { if(message.getDetails() instanceof ContractEventDetails){ onContractEventMessageReceived((ContractEventDetails) message.getDetails()); } else if(message.getDetails() instanceof TransactionDetails){ onTransactionMessageReceived((TransactionDetails) message.getDetails()); } }
Example #25
Source File: AmqpConfiguration.java From ESarch with Apache License 2.0 | 5 votes |
@Qualifier("trade-events") @Bean public SubscribableMessageSource<EventMessage<?>> tradeEvents(AMQPMessageConverter messageConverter) { return new SpringAMQPMessageSource(messageConverter) { @Transactional @RabbitListener(queues = "trades") @Override public void onMessage(Message message, Channel channel) { super.onMessage(message, channel); } }; }
Example #26
Source File: RabbitSubmitExaminationReceiver.java From spring-microservice-exam with MIT License | 5 votes |
/** * 处理提交考试逻辑:统计错题,计算成绩等 * 1. 先更新考试记录的状态为正在计算 * 2. 更新成功则执行提交逻辑 * * @param answer answer * @author tangyi * @date 2019/05/03 14:56 */ @RabbitListener(queues = {MqConstant.SUBMIT_EXAMINATION_QUEUE}) public void submitExamination(Answer answer) { log.debug("examRecordId: {}, modifier: {}", answer.getExamRecordId(), answer.getModifier()); try { // 异步提交会丢失tenantCode,需要手动设置 TenantContextHolder.setTenantCode(answer.getTenantCode()); ExaminationRecord examRecord = examRecordService.get(answer.getExamRecordId()); if (examRecord == null) return; if (SubmitStatusEnum.NOT_SUBMITTED.getValue().equals(examRecord.getSubmitStatus())) log.warn("Examination: {} not submitted", examRecord.getId()); if (SubmitStatusEnum.CALCULATE.getValue().equals(examRecord.getSubmitStatus())) log.warn("Examination: {} is counting, please do not submit again", examRecord.getId()); // 更新状态为正在统计 examRecord.setSubmitStatus(SubmitStatusEnum.CALCULATE.getValue()); // 更新成功 if (examRecordService.update(examRecord) > 0) { log.debug("Examination: {} count success", examRecord.getId()); answerService.submit(answer); } else { log.warn("Examination: {} count failed", examRecord.getId()); } } catch (Exception e) { log.error(e.getMessage(), e); } }
Example #27
Source File: AuthorityMqAutoConfiguration.java From zuihou-admin-boot with Apache License 2.0 | 5 votes |
@RabbitListener(queues = QueueConstants.QUEUE_SCAN_API_RESOURCE) public void ScanApiResourceQueue(@Payload String param) { SystemApiScanSaveDTO scan = JSONObject.parseObject(param, SystemApiScanSaveDTO.class); BaseContextHandler.setTenant(scan.getTenant()); this.systemApiService.batchSave(scan); }
Example #28
Source File: MqListener.java From iot-dc with Apache License 2.0 | 5 votes |
/** * 刷新 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 #29
Source File: LocalListner.java From cloud-espm-cloud-native with Apache License 2.0 | 5 votes |
/** * This method is used to process messages from queue. * * @param in * @param channel * @param tag * @throws IOException * @throws InterruptedException */ @RabbitListener(queues = "espm.salesOrders") public void recieve(SalesOrder in, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException, InterruptedException { SalesOrderRepository repo = appContext.getBean(SalesOrderRepository.class); try { if (!repo.existsById(in.getSalesOrderId())) { repo.save(in); logger.info(in.getSalesOrderId() + " created"); channel.basicAck(tag, false); value = initialValue; } else { logger.error(in.getSalesOrderId() + " already Exists, Deleting from Queue"); channel.basicAck(tag, false); } } catch (DataIntegrityViolationException e) { logger.error(in.getSalesOrderId() + " is an invalid Sales-Order, Deleting from Queue"); channel.basicNack(tag, false, false); } catch (CannotCreateTransactionException ccte) { logger.error("Unable to connect to DB"); logger.error("Backing for " + value); TimeUnit.MILLISECONDS.sleep(value); if (value <= maxVal) value = value * multiplier; channel.basicNack(tag, false, true); } }
Example #30
Source File: AuthorityMqAutoConfiguration.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@RabbitListener(queues = QueueConstants.QUEUE_SCAN_API_RESOURCE) public void scanApiResourceRabbitListener(@Payload String param) { SystemApiScanSaveDTO scan = JSONObject.parseObject(param, SystemApiScanSaveDTO.class); BaseContextHandler.setTenant(scan.getTenant()); this.systemApiService.batchSave(scan); }