org.springframework.kafka.annotation.KafkaListener Java Examples
The following examples show how to use
org.springframework.kafka.annotation.KafkaListener.
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: App.java From Mastering-Distributed-Tracing with MIT License | 7 votes |
@KafkaListener(topics = "message") public void process(@Payload Message message, @Headers MessageHeaders headers) throws Exception { Span span = kafka.startConsumerSpan("process", headers); try (Scope scope = tracer.scopeManager().activate(span, true)) { System.out.println("Received message: " + message.message); if (message.image == null && message.message.trim().startsWith("/giphy")) { String query = message.message.split("/giphy")[1].trim(); System.out.println("Giphy requested: " + query); message.image = giphy.query(query); if (message.image != null) { kafka.sendMessage(message); System.out.println("Updated message, url=" + message.image); } } } }
Example #2
Source File: KafkaConsumer.java From cubeai with Apache License 2.0 | 6 votes |
@KafkaListener(topics = {"async-task-topic"}, group = "umu") @Async public void receive(String message) { log.info("Kafka received message='{}'", message); JSONObject taskCommand = JSONObject.parseObject(message); String taskType = taskCommand.getString("taskType"); if (taskType.equals("ucumos-onboarding")) { String taskUuid = taskCommand.getString("taskUuid"); if (null != taskUuid) { this.onboardingService.onboarding(taskUuid); } } }
Example #3
Source File: EventDispatcher.java From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 | 6 votes |
@KafkaListener(topics = { "mysqlcdc.cdc.USERS", "mysqlcdc.cdc.JOBS", "mysqlcdc.cdc.ADDRESSES"}) @Timed public void handleEvents(List<ConsumerRecord<String, DebeziumEvent>> records, Acknowledgment acknowledgment) { LOGGER.debug("Request to process {} records", records.size()); List<ConsumerRecord<String, DebeziumEvent>> sortedRecords = records.stream() .sorted(Comparator.comparing(r -> r.value().getPayload().getDate())) .collect(Collectors.toList()); sortedRecords.forEach(record -> { LOGGER.debug("Request to handle {} event in the topic {}", record.value().getPayload().getOperation(), record.topic()); handlerFactory.getHandler(record.topic()).process(record.value()); }); acknowledgment.acknowledge(); }
Example #4
Source File: KafkaMetricReceiver.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Receiving consumer messages on multiple topics * * @param records * @param ack */ @KafkaListener(topicPattern = TOPIC_KAFKA_RECEIVE_PATTERN, containerFactory = BEAN_KAFKA_BATCH_FACTORY) public void onMetricReceive(List<ConsumerRecord<byte[], Bytes>> records, Acknowledgment ack) { try { if (log.isDebugEnabled()) { log.debug("Receive metric records - {}", records); } if (log.isInfoEnabled()) { log.info("Receive metric records size - {}", records.size()); } doProcess(records, new MultiAcknowledgmentState(ack)); } catch (Exception e) { log.error(String.format("Failed to receive process for ", records.size()), e); } }
Example #5
Source File: SettleListenerOfPayment.java From reliable with Apache License 2.0 | 6 votes |
@ReliableOnConsumed(svc = "cat-settle",nextTopic = "CAT_SETTLE_CREATED", nextRetryMax = 2, nextSvcs = {"cat-statement"}) @KafkaListener(topics = "CAT_PAID_TCC_TRY") public CatStatement onCatPaid_TCC_TRY(ConsumerRecord<String, String> record) { ReliableDto dto = dtoConverter.convertOnConsumed(record); //-------------- CatSettle catSettle = new CatSettle(); catSettle.setId("CAT_SETTLE_TEST"); catSettle.setName("TRY"); settleController.create(catSettle); CatStatement catStatement = new CatStatement(); catStatement.setId("TEST_STATEMENT"); catStatement.setTest("CAT_SETTLE_CREATED"); return catStatement; }
Example #6
Source File: OrderData.java From match-trade with Apache License 2.0 | 6 votes |
/** * @Title: new_order * @Description: TODO(接收撤销订单数据) * @param 参数 * @return void 返回类型 * @throws */ @KafkaListener(id = "cancel_order", topics = "cancel_order") public void cancel_order(String param) { log.info("===收到cancel_order:"+param); CancelOrderParam cancel = JSON.parseObject(param, CancelOrderParam.class); IMap<Long, MatchOrder> order_map = hzInstance.getMap(HazelcastUtil.getOrderBookKey(cancel.getCoinTeam(), cancel.getIsBuy())); if (order_map.containsKey(cancel.getId())) { TransactionOptions options = new TransactionOptions().setTransactionType(TransactionOptions.TransactionType.ONE_PHASE); TransactionContext context = hzInstance.newTransactionContext(options); context.beginTransaction(); try { IMap<BigDecimal, BigDecimal> map = hzInstance.getMap(HazelcastUtil.getMatchKey(cancel.getCoinTeam(), cancel.getIsBuy())); MatchOrder cmo = order_map.remove(cancel.getId()); map.compute(cmo.getPrice(), (k,v) -> v.subtract(cmo.getUnFinishNumber())); if (map.get(cmo.getPrice()).compareTo(BigDecimal.ZERO) >-1) { context.commitTransaction(); pushData.updateOrder(cmo); //推送撤销成功结果 }else { throw new Exception(); } } catch (Exception e) { context.rollbackTransaction(); } } }
Example #7
Source File: SettleListenerOfPayment.java From reliable with Apache License 2.0 | 6 votes |
@ReliableOnConsumed(svc = "cat-settle", nextTopic = "CAT_SETTLE_CREATED", nextRetryMax = 2, nextSvcs = {"cat-statement"}) @KafkaListener(topics = "CAT_PAID") public CatStatement onCatPaid(ConsumerRecord<String, String> record) { ReliableDto dto = dtoConverter.convertOnConsumed(record); //-------------- CatSettle catSettle = new CatSettle(); catSettle.setId("CAT_SETTLE_TEST"); this.settleController.create(catSettle); CatStatement catStatement = new CatStatement(); catStatement.setId("TEST_STATEMENT"); catStatement.setTest("CAT_SETTLE_CREATED"); return catStatement; }
Example #8
Source File: Receiver.java From netty-learning-example with Apache License 2.0 | 6 votes |
@KafkaListener(topics = {"spring-kafka-protobuf-demo"}) public void listen(ConsumerRecord<?, Callback> record) { Callback callback = record.value(); log.info("message: {}", callback); if (callback == null){ return; } switch (callback.getEventTypeCase()) { case ONE_EVENT: log.info("one event: {}", callback.getOneEvent()); break; case TWO_EVENT: log.info("two event: {}", callback.getOneEvent()); break; default: log.info("default value..."); break; } }
Example #9
Source File: ExchangeOrderConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
@KafkaListener(topics = "exchange-order-cancel",containerFactory = "kafkaListenerContainerFactory") public void onOrderCancel(List<ConsumerRecord<String,String>> records){ for (int i = 0; i < records.size(); i++) { ConsumerRecord<String,String> record = records.get(i); log.info("取消订单topic={},key={},size={}",record.topic(),record.key(),records.size()); ExchangeOrder order = JSON.parseObject(record.value(), ExchangeOrder.class); if(order == null){ return ; } CoinTrader trader = traderFactory.getTrader(order.getSymbol()); if(trader.getReady()) { try { ExchangeOrder result = trader.cancelOrder(order); if (result != null) { kafkaTemplate.send("exchange-order-cancel-success", JSON.toJSONString(result)); } }catch (Exception e){ log.info("====取消订单出错===",e); e.printStackTrace(); } } } }
Example #10
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
@KafkaListener(topics = "exchange-order-completed", containerFactory = "kafkaListenerContainerFactory") public void handleOrderCompleted(List<ConsumerRecord<String, String>> records) { try { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); logger.info("订单交易处理完成消息topic={},value={}", record.topic(), record.value()); List<ExchangeOrder> orders = JSON.parseArray(record.value(), ExchangeOrder.class); for (ExchangeOrder order : orders) { String symbol = order.getSymbol(); // 委托成交完成处理 exchangeOrderService.tradeCompleted(order.getOrderId(), order.getTradedAmount(), order.getTurnover()); // 推送订单成交 messagingTemplate.convertAndSend( "/topic/market/order-completed/" + symbol + "/" + order.getMemberId(), order); nettyHandler.handleOrder(NettyCommand.PUSH_EXCHANGE_ORDER_COMPLETED, order); } } } catch (Exception e) { e.printStackTrace(); } }
Example #11
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
/** * 处理模拟交易 * * @param records */ @KafkaListener(topics = "exchange-trade-mocker", containerFactory = "kafkaListenerContainerFactory") public void handleMockerTrade(List<ConsumerRecord<String, String>> records) { try { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); logger.info("mock数据topic={},value={},size={}", record.topic(), record.value(), records.size()); List<ExchangeTrade> trades = JSON.parseArray(record.value(), ExchangeTrade.class); String symbol = trades.get(0).getSymbol(); // 处理行情 CoinProcessor coinProcessor = coinProcessorFactory.getProcessor(symbol); if (coinProcessor != null) { coinProcessor.process(trades); } pushJob.addTrades(symbol, trades); } } catch (Exception e) { e.printStackTrace(); } }
Example #12
Source File: KafkaConsumer.java From cubeai with Apache License 2.0 | 6 votes |
@KafkaListener(topics = {"async-task-topic"}, group = "umu") @Async public void receive(String message) { log.info("Kafka received message='{}'", message); JSONObject taskCommand = JSONObject.parseObject(message); String taskType = taskCommand.getString("taskType"); String taskUuid = taskCommand.getString("taskUuid"); if (null != taskUuid) { if (taskType.equals("ucumos-deploy")) { this.deployService.deploy(taskUuid, taskCommand.getBoolean("isPublic")); } if (taskType.equals("ucumos-lcm-stop")) { this.lifeCircleManagementService.stop(taskUuid, taskCommand.getString("deploymentUuid")); } } }
Example #13
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
/** * 订单取消成功 * * @param records */ @KafkaListener(topics = "exchange-order-cancel-success", containerFactory = "kafkaListenerContainerFactory") public void handleOrderCanceled(List<ConsumerRecord<String, String>> records) { try { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); logger.info("取消订单消息topic={},value={},size={}", record.topic(), record.value(), records.size()); ExchangeOrder order = JSON.parseObject(record.value(), ExchangeOrder.class); String symbol = order.getSymbol(); // 调用服务处理 exchangeOrderService.cancelOrder(order.getOrderId(), order.getTradedAmount(), order.getTurnover()); // 推送实时成交 messagingTemplate.convertAndSend("/topic/market/order-canceled/" + symbol + "/" + order.getMemberId(), order); nettyHandler.handleOrder(NettyCommand.PUSH_EXCHANGE_ORDER_CANCELED, order); } } catch (Exception e) { e.printStackTrace(); } }
Example #14
Source File: FinanceConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
/** * 处理充值消息,key值为币种的名称(注意是全称,如Bitcoin) * * @param record */ @KafkaListener(topics = {"deposit"}) public void handleDeposit(ConsumerRecord<String, String> record) { logger.info("topic={},key={},value={}", record.topic(), record.key(), record.value()); if (StringUtils.isEmpty(record.value())) { return; } JSONObject json = JSON.parseObject(record.value()); if (json == null) { return; } BigDecimal amount = json.getBigDecimal("amount"); String txid = json.getString("txid"); String address = json.getString("address"); Coin coin = coinService.findOne(record.key()); logger.info("coin={}", coin); if (coin != null && walletService.findDeposit(address, txid) == null) { MessageResult mr = walletService.recharge(coin, address, amount, txid); logger.info("wallet recharge result:{}", mr); } }
Example #15
Source File: FinanceConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
/** * 异步打钱后返回状态 * @param record */ @KafkaListener(topics = {"withdraw-notify"}) public void withdrawNotify(ConsumerRecord<String, String> record){ logger.info("topic={},accessKey={},value={}", record.topic(), record.key(), record.value()); if (StringUtils.isEmpty(record.value())) { return; } JSONObject json = JSON.parseObject(record.value()); Long withdrawId = json.getLong("withdrawId"); WithdrawRecord withdrawRecord=withdrawRecordService.findOne(withdrawId); if(withdrawRecord==null){ return; } String txid=json.getString("txid"); int status=json.getInteger("status"); //转账失败,状态变回等待放币 if(status==0){ withdrawRecord.setStatus(WithdrawStatus.WAITING); withdrawRecordService.save(withdrawRecord); }else if(status==1){ withdrawRecordService.withdrawSuccess(withdrawId, txid); } }
Example #16
Source File: FinanceConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
/** * 处理充值消息,key值为币种的名称(注意是全称,如Bitcoin) * * @param record */ @KafkaListener(topics = {"deposit"}) public void handleDeposit(ConsumerRecord<String, String> record) { logger.info("topic={},key={},value={}", record.topic(), record.key(), record.value()); if (StringUtils.isEmpty(record.value())) { return; } JSONObject json = JSON.parseObject(record.value()); if (json == null) { return; } BigDecimal amount = json.getBigDecimal("amount"); String txid = json.getString("txid"); String address = json.getString("address"); Coin coin = coinService.findOne(record.key()); logger.info("coin={}", coin); if (coin != null && walletService.findDeposit(address, txid) == null) { MessageResult mr = walletService.recharge(coin, address, amount, txid); logger.info("wallet recharge result:{}", mr); } }
Example #17
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
@KafkaListener(topics = "exchange-order-completed", containerFactory = "kafkaListenerContainerFactory") public void handleOrderCompleted(List<ConsumerRecord<String, String>> records) { try { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); logger.info("订单交易处理完成消息topic={},value={}", record.topic(), record.value()); List<ExchangeOrder> orders = JSON.parseArray(record.value(), ExchangeOrder.class); for (ExchangeOrder order : orders) { String symbol = order.getSymbol(); // 委托成交完成处理 exchangeOrderService.tradeCompleted(order.getOrderId(), order.getTradedAmount(), order.getTurnover()); // 推送订单成交 messagingTemplate.convertAndSend( "/topic/market/order-completed/" + symbol + "/" + order.getMemberId(), order); nettyHandler.handleOrder(NettyCommand.PUSH_EXCHANGE_ORDER_COMPLETED, order); } } } catch (Exception e) { e.printStackTrace(); } }
Example #18
Source File: KafkaReceiver.java From spring-cloud-sofastack-samples with Apache License 2.0 | 6 votes |
@KafkaListener(topics = {KafkaConstants.TRADE_TOPIC}, groupId = "test-consumer-group") public void listen(ConsumerRecord<?, ?> record) { LOGGER.info("Invoker kafka listen to consumer.topic {},{}", record.topic(), record.value()); try { Optional<?> kafkaMessage = Optional.ofNullable(record.value()); if (kafkaMessage.isPresent()) { String cmd = kafkaMessage.get().toString(); if (SUCCESS.equals(cmd.split(COLON)[0])) { Result<UserDetails> result = userService.queryUserDetail(Integer.valueOf(cmd .split(COLON)[1])); if (result.isSuccess()) { mailService.sendTextMail(result.getData().getEmail(), "转账成功", "samples 测试转账成功"); } LOGGER.info("Success to consumer kafka message. cmd = {}", cmd); } else { LOGGER.error("Failed to consumer kafka message. message type {}", cmd); } } } catch (Exception e) { LOGGER.error("Failed to execute consumer kafka message", e); } }
Example #19
Source File: ExchangeOrderConsumer.java From ZTuoExchange_framework with MIT License | 6 votes |
@KafkaListener(topics = "exchange-order-cancel",containerFactory = "kafkaListenerContainerFactory") public void onOrderCancel(List<ConsumerRecord<String,String>> records){ for (int i = 0; i < records.size(); i++) { ConsumerRecord<String,String> record = records.get(i); log.info("取消订单topic={},key={},size={}",record.topic(),record.key(),records.size()); ExchangeOrder order = JSON.parseObject(record.value(), ExchangeOrder.class); if(order == null){ return ; } CoinTrader trader = traderFactory.getTrader(order.getSymbol()); if(trader.getReady()) { try { ExchangeOrder result = trader.cancelOrder(order); if (result != null) { kafkaTemplate.send("exchange-order-cancel-success", JSON.toJSONString(result)); } }catch (Exception e){ log.info("====取消订单出错===",e); e.printStackTrace(); } } } }
Example #20
Source File: OrderListener.java From spring-in-action-5-samples with Apache License 2.0 | 5 votes |
@KafkaListener(topics="tacocloud.orders.topic") public void handle(Order order, ConsumerRecord<String, Order> record) { log.error("Received from partition {} with timestamp {}", record.partition(), record.timestamp()); ui.displayOrder(order); }
Example #21
Source File: KafkaFilterEventConsumer.java From eventeum with Apache License 2.0 | 5 votes |
@Override @KafkaListener(topics = "#{eventeumKafkaSettings.eventeumEventsTopic}", groupId = "#{eventeumKafkaSettings.groupId}", containerFactory = "eventeumKafkaListenerContainerFactory") public void onMessage(EventeumMessage message) { final Consumer<EventeumMessage> consumer = messageConsumers.get(message.getType()); if (consumer == null) { logger.error(String.format("No consumer for message type %s!", message.getType())); return; } consumer.accept(message); }
Example #22
Source File: Consumer.java From iot-dc with Apache License 2.0 | 5 votes |
/** * 指令队列 * * @param record * @throws Exception */ @KafkaListener(topics = "rtu_inst_topic") public void listen(ConsumerRecord<String, byte[]> record) throws Exception { String msg = new String(record.value()); 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 #23
Source File: MemberConsumer.java From ZTuoExchange_framework with MIT License | 5 votes |
/** * 重置用户钱包地址 * @param record */ @KafkaListener(topics = {"reset-member-address"}) public void resetAddress(ConsumerRecord<String,String> record){ String content = record.value(); JSONObject json = JSON.parseObject(content); Coin coin = coinService.findByUnit(record.key()); Assert.notNull(coin,"coin null"); if(coin.getEnableRpc()==BooleanEnum.IS_TRUE){ MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(record.key(),json.getLong("uid")); Assert.notNull(memberWallet,"wallet null"); String account = "U" + json.getLong("uid")+ GeneratorUtil.getNonceString(4); //远程RPC服务URL,后缀为币种单位 String serviceName = "SERVICE-RPC-" + coin.getUnit(); try{ String url = "http://" + serviceName + "/rpc/address/{account}"; ResponseEntity<MessageResult> result = restTemplate.getForEntity(url, MessageResult.class, account); logger.info("remote call:service={},result={}", serviceName, result); if (result.getStatusCode().value() == 200) { MessageResult mr = result.getBody(); if (mr.getCode() == 0) { String address = mr.getData().toString(); memberWallet.setAddress(address); } } } catch (Exception e){ logger.error("call {} failed,error={}",serviceName,e.getMessage()); } memberWalletService.save(memberWallet); } }
Example #24
Source File: FinanceConsumer.java From ZTuoExchange_framework with MIT License | 5 votes |
/** * 处理提交请求,调用钱包rpc,自动转账 * * @param record */ @KafkaListener(topics = {"withdraw"}) public void handleWithdraw(ConsumerRecord<String, String> record) { logger.info("topic={},key={},value={}", record.topic(), record.key(), record.value()); if (StringUtils.isEmpty(record.value())) { return; } JSONObject json = JSON.parseObject(record.value()); Long withdrawId = json.getLong("withdrawId"); try { String serviceName = "SERVICE-RPC-" + record.key().toUpperCase(); String url = "http://" + serviceName + "/rpc/withdraw?address={1}&amount={2}&fee={3}"; Coin coin = coinService.findByUnit(record.key()); logger.info("coin = {}",coin.toString()); if (coin != null && coin.getCanAutoWithdraw() == BooleanEnum.IS_TRUE) { BigDecimal minerFee = coin.getMinerFee(); MessageResult result = restTemplate.getForObject(url, MessageResult.class, json.getString("address"), json.getBigDecimal("arriveAmount"), minerFee); logger.info("=========================rpc 结束================================"); logger.info("result = {}", result); if (result.getCode() == 0 && result.getData() != null) { logger.info("====================== 处理成功,data为txid更新业务 =================================="); //处理成功,data为txid,更新业务订单 String txid = (String) result.getData(); withdrawRecordService.withdrawSuccess(withdrawId, txid); } else { logger.info("====================== 自动转账失败,转为人工处理 =================================="); //自动转账失败,转为人工处理 withdrawRecordService.autoWithdrawFail(withdrawId); } } } catch (Exception e) { e.printStackTrace(); logger.error("auto withdraw failed,error={}", e.getMessage()); logger.info("====================== 自动转账失败,转为人工处理 =================================="); // 自动转账失败,转为人工处理 withdrawRecordService.autoWithdrawFail(withdrawId); } }
Example #25
Source File: SMSKafkaListener.java From spring-cloud-shop with MIT License | 5 votes |
@KafkaListener(topics = "sms_send") public void doProcess(ConsumerRecord<?, ?> record) { Optional<?> message = Optional.ofNullable(record.value()); if (message.isPresent()) { Object obj = message.get(); System.out.println("============" + obj); } }
Example #26
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 5 votes |
/** * 消费交易盘口信息 * * @param records */ @KafkaListener(topics = "exchange-trade-plate", containerFactory = "kafkaListenerContainerFactory") public void handleTradePlate(List<ConsumerRecord<String, String>> records) { try { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); logger.info("推送盘口信息topic={},value={},size={}", record.topic(), record.value(), records.size()); TradePlate plate = JSON.parseObject(record.value(), TradePlate.class); String symbol = plate.getSymbol(); pushJob.addPlates(symbol, plate); } } catch (Exception e) { e.printStackTrace(); } }
Example #27
Source File: ExchangeTradeConsumer.java From ZTuoExchange_framework with MIT License | 5 votes |
/** * 处理成交明细 * * @param records */ @KafkaListener(topics = "exchange-trade", containerFactory = "kafkaListenerContainerFactory") public void handleTrade(List<ConsumerRecord<String, String>> records) { for (int i = 0; i < records.size(); i++) { ConsumerRecord<String, String> record = records.get(i); executor.submit(new HandleTradeThread(record)); } }
Example #28
Source File: KafkaConsumer.java From java-tutorial with MIT License | 5 votes |
/** * 监听kafka.tut 的 topic * * @param record * @param topic topic */ @KafkaListener(id = "tut", topics = "kafka.tut") public void listen(ConsumerRecord<?, ?> record, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { //判断是否NULL Optional<?> kafkaMessage = Optional.ofNullable(record.value()); if (kafkaMessage.isPresent()) { //获取消息 Object message = kafkaMessage.get(); logger.info("Receive: +++++++++++++++ Topic:" + topic); logger.info("Receive: +++++++++++++++ Record:" + record); logger.info("Receive: +++++++++++++++ Message:" + message); } }
Example #29
Source File: ExchangeOrderConsumer.java From ZTuoExchange_framework with MIT License | 5 votes |
@KafkaListener(topics = "exchange-order",containerFactory = "kafkaListenerContainerFactory") public void onOrderSubmitted(List<ConsumerRecord<String,String>> records){ for (int i = 0; i < records.size(); i++) { ConsumerRecord<String,String> record = records.get(i); log.info("接收订单>>topic={},value={},size={}",record.topic(),record.value(),records.size()); ExchangeOrder order = JSON.parseObject(record.value(), ExchangeOrder.class); if(order == null){ return ; } CoinTrader trader = traderFactory.getTrader(order.getSymbol()); //如果当前币种交易暂停会自动取消订单 if (trader.isTradingHalt() || !trader.getReady()) { //撮合器未准备完成,撤回当前等待的订单 kafkaTemplate.send("exchange-order-cancel-success", JSON.toJSONString(order)); } else { try { long startTick = System.currentTimeMillis(); trader.trade(order); log.info("complete trade,{}ms used!", System.currentTimeMillis() - startTick); } catch (Exception e) { e.printStackTrace(); log.info("====交易出错,退回订单===",e); kafkaTemplate.send("exchange-order-cancel-success", JSON.toJSONString(order)); } } } }
Example #30
Source File: Consumer.java From iot-dc with Apache License 2.0 | 5 votes |
/** * 刷新 iot信息 * * @param record * @throws Exception */ @KafkaListener(topics = "rtu_refresh_topic") public void refreshIotInfo(ConsumerRecord<String, byte[]> record) throws Exception { String msg = new String(record.value()); 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(); } } }