當前位置: 首頁>>代碼示例>>Java>>正文


Java Disruptor類代碼示例

本文整理匯總了Java中com.lmax.disruptor.dsl.Disruptor的典型用法代碼示例。如果您正苦於以下問題:Java Disruptor類的具體用法?Java Disruptor怎麽用?Java Disruptor使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Disruptor類屬於com.lmax.disruptor.dsl包,在下文中一共展示了Disruptor類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: initDisruptor

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
private void initDisruptor(int processors, int ringBufferSize) {
  LOG.info("eds client init disruptor with processors="
      + processors + " and ringBufferSize=" + ringBufferSize);

  executor = Executors.newFixedThreadPool(
      processors,
      new ThreadFactoryBuilder().setNameFormat("disruptor-executor-%d").build());

  final WaitStrategy waitStrategy = createWaitStrategy();
  ringBufferSize = sizeFor(ringBufferSize); // power of 2
  disruptor = new Disruptor<>(EdsRingBufferEvent.FACTORY, ringBufferSize, executor,
      ProducerType.MULTI, waitStrategy);

  EdsEventWorkHandler[] handlers = new EdsEventWorkHandler[processors];
  for (int i = 0; i < handlers.length; i++) {
    handlers[i] = new EdsEventWorkHandler();
  }
  // handlers number = threads number
  disruptor.handleEventsWithWorkerPool(handlers); // "handleEventsWith" just like topics , with multiple consumers

  disruptor.start();
}
 
開發者ID:eXcellme,項目名稱:eds,代碼行數:23,代碼來源:PublishManager.java

示例2: SharedMessageStore

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@SuppressWarnings("unchecked")
public SharedMessageStore(MessageDao messageDao, int bufferSize, int maxDbBatchSize) {

    pendingMessages = new ConcurrentHashMap<>();
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("DisruptorMessageStoreThread-%d").build();

    disruptor = new Disruptor<>(DbOperation.getFactory(),
            bufferSize, namedThreadFactory, ProducerType.MULTI, new SleepingWaitStrategy());

    disruptor.setDefaultExceptionHandler(new LogExceptionHandler());

    disruptor.handleEventsWith(new DbEventMatcher(bufferSize))
            .then(new DbWriter(messageDao, maxDbBatchSize))
            .then((EventHandler<DbOperation>) (event, sequence, endOfBatch) -> event.clear());
    disruptor.start();
    this.messageDao = messageDao;
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:19,代碼來源:SharedMessageStore.java

示例3: createDisruptor

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
/**
 * create a disruptor
 *
 * @param name           The title of the disruptor
 * @param ringBufferSize The size of ringBuffer
 */
public void createDisruptor(String name, int ringBufferSize) {
    if (DISRUPTOR_MAP.keySet().contains(name)) {
        throw new NulsRuntimeException(ErrorCode.FAILED, "create disruptor faild,the name is repetitive!");
    }

    Disruptor<DisruptorEvent> disruptor = new Disruptor<DisruptorEvent>(EVENT_FACTORY,
            ringBufferSize, new NulsThreadFactory(ModuleService.getInstance().getModuleId(EventBusModuleBootstrap.class),name), ProducerType.SINGLE,
            new SleepingWaitStrategy());
    disruptor.handleEventsWith(new EventHandler<DisruptorEvent>() {
        @Override
        public void onEvent(DisruptorEvent disruptorEvent, long l, boolean b) throws Exception {
            Log.debug(disruptorEvent.getData() + "");
        }
    });
    DISRUPTOR_MAP.put(name, disruptor);
}
 
開發者ID:nuls-io,項目名稱:nuls,代碼行數:23,代碼來源:DisruptorUtil.java

示例4: offer

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
/**
 * add the data obj to the disruptor named the field name
 *
 * @param name
 * @param obj
 */
public void offer(String name, Object obj) {
    Disruptor<DisruptorEvent> disruptor = DISRUPTOR_MAP.get(name);
    AssertUtil.canNotEmpty(disruptor, "the disruptor is not exist!name:" + name);
    RingBuffer<DisruptorEvent> ringBuffer = disruptor.getRingBuffer();
    //請求下一個事件序號;
    long sequence = ringBuffer.next();
    try {
        //獲取該序號對應的事件對象;
        DisruptorEvent event = ringBuffer.get(sequence);
        event.setData(obj);
    } finally {
        //發布事件;
        ringBuffer.publish(sequence);
    }
}
 
開發者ID:nuls-io,項目名稱:nuls,代碼行數:22,代碼來源:DisruptorUtil.java

示例5: responseMessageSender

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@Bean
public JmsMessageSender responseMessageSender(@Value("${jms-sender.ring-buffer-size}")int ringBufferSize) throws JMSException {

  DisruptorJmsMessageSender disruptorJmsMessageSender = DisruptorJmsMessageSenderFactory.create(
      responseSession(),
      responseMessageProducer(),
      new ArtemisMessageDtoDupMessageDetectStrategy(),
      ringBufferSize
  );

  Disruptor disruptor = disruptorJmsMessageSender.getDisruptor();

  BeanRegisterUtils.registerSingleton(
      applicationContext,
      "responseMessageSenderLifeCycleContainer",
      new DisruptorLifeCycleContainer("responseMessageSender", disruptor, Ordered.LOWEST_PRECEDENCE)
  );

  return disruptorJmsMessageSender;

}
 
開發者ID:bighector,項目名稱:-artemis-disruptor-miaosha,代碼行數:22,代碼來源:JmsServerConfiguration.java

示例6: setup

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@Setup
public void setup() {
    executor = Executors.newSingleThreadExecutor();
    disruptor = new Disruptor<LongEvent>(LongEvent.EVENT_FACTORY, executor, new SingleThreadedClaimStrategy(Run.QUEUE_SIZE), new BusySpinWaitStrategy());

    eventCount = new AtomicInteger();

    handler = (event, sequence, endOfBatch) -> {
        if(Run.LONGVAL == event.getValue()) {
            eventCount.incrementAndGet();
        } else {
            throw new RuntimeException("Failed.");
        }
    };

    disruptor.handleEventsWith(handler);

    ringBuffer = disruptor.start();
}
 
開發者ID:conversant,項目名稱:disruptor_benchmark,代碼行數:20,代碼來源:LMAXDisruptorPushPullBenchmark.java

示例7: setup

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@Setup
public void setup() {
    executor = Executors.newFixedThreadPool(Run.NTHREAD);
    disruptor = new Disruptor<LongEvent>(LongEvent.EVENT_FACTORY, executor, new MultiThreadedClaimStrategy(Run.QUEUE_SIZE), new BusySpinWaitStrategy());

    eventCount = new AtomicInteger();

    handler = (event, sequence, endOfBatch) -> {
        if(Run.LONGVAL == event.getValue()) {
            eventCount.incrementAndGet();
        } else {
            throw new RuntimeException("Failed.");
        }
    };

    disruptor.handleEventsWith(handler);

    ringBuffer = disruptor.start();
}
 
開發者ID:conversant,項目名稱:disruptor_benchmark,代碼行數:20,代碼來源:LMAXDisruptorBenchmark.java

示例8: main

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
public static void main(String[] args) throws InterruptedException
{
    Disruptor<ObjectBox> disruptor = new Disruptor<ObjectBox>(
        ObjectBox.FACTORY, RING_SIZE, Executors.newCachedThreadPool(), ProducerType.MULTI,
        new BlockingWaitStrategy());
    disruptor.handleEventsWith(new Consumer()).then(new Consumer());
    final RingBuffer<ObjectBox> ringBuffer = disruptor.getRingBuffer();
    Publisher p = new Publisher();
    IMessage message = new IMessage();
    ITransportable transportable = new ITransportable();
    String streamName = "com.lmax.wibble";
    System.out.println("publishing " + RING_SIZE + " messages");
    for (int i = 0; i < RING_SIZE; i++)
    {
        ringBuffer.publishEvent(p, message, transportable, streamName);
        Thread.sleep(10);
    }
    System.out.println("start disruptor");
    disruptor.start();
    System.out.println("continue publishing");
    while (true)
    {
        ringBuffer.publishEvent(p, message, transportable, streamName);
        Thread.sleep(10);
    }
}
 
開發者ID:winwill2012,項目名稱:disruptor-code-analysis,代碼行數:27,代碼來源:MultiProducerWithTranslator.java

示例9: RingBufferService

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private RingBufferService(final Properties config) {
	config.put(KafkaProducerService.CONFIG_PREFIX + "value.serializer", ByteBufSerde.ByteBufSerializer.class.getName());
	config.put(KafkaProducerService.CONFIG_PREFIX + "key.serializer", Serdes.String().serializer());
	producer = KafkaProducerService.getInstance(config);
	bufferSize = ConfigurationHelper.getIntSystemThenEnvProperty(RB_CONF_BUFFER_SIZE, RB_DEFAULT_BUFFER_SIZE, config);
	targetTopic = ConfigurationHelper.getSystemThenEnvProperty(RB_CONF_TOPIC_NAME, RB_DEFAULT_TOPIC_NAME, config);
	eventBuffInitSize = ConfigurationHelper.getIntSystemThenEnvProperty(RB_CONF_BUFF_INITIAL_SIZE, RB_DEFAULT_BUFF_INITIAL_SIZE, config);
	shutdownTimeout = ConfigurationHelper.getIntSystemThenEnvProperty(RB_CONF_STOP_TIMEOUT, RB_DEFAULT_STOP_TIMEOUT, config);
	waitStrategy = RBWaitStrategy.getConfiguredStrategy(config);
	disruptor = new Disruptor<ByteBuf>(this, bufferSize, threadFactory, ProducerType.MULTI, waitStrategy);
	disruptor.handleEventsWith(this);   // FIXME: need to able to supply several handlers
	disruptor.start();
	ringBuffer = disruptor.getRingBuffer();
	log.info("<<<<< RawRingBufferDispatcher Started.");		
}
 
開發者ID:nickman,項目名稱:HeliosStreams,代碼行數:17,代碼來源:RingBufferService.java

示例10: dealWithDisruptorFromTail

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
private static void dealWithDisruptorFromTail(ListenerChain chain, Disruptor<ElectronsHolder> disruptor) {
    if (idOnly(chain.getId(), chain.getAfter())) {
        return;
    }
    List<ListenerChain> befores = chain.getBefores();
    if (CollectionUtils.isEmpty(befores)) {
        return;
    }
    for (ListenerChain c : befores) {
        dealWithDisruptorFromTail(c, disruptor);
    }
    ProxyHandler[] handlers = new ProxyHandler[befores.size()];
    for (int i = 0; i < befores.size(); i++) {
        handlers[i] = befores.get(i).getProxyHandler();
    }
    disruptor.after(handlers).handleEventsWith(chain.getProxyHandler());
}
 
開發者ID:carryxyh,項目名稱:Electrons,代碼行數:18,代碼來源:ListenerChainBuilderNew.java

示例11: DisruptorTransfer

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
@SuppressWarnings("unchecked")
public DisruptorTransfer(final SpanEventHandler spanEventHandler, final int buffSize) {
  // Executor executor = Executors.newCachedThreadPool();
  final ThreadFactory threadFactory = Executors.defaultThreadFactory();

  // The factory for the event
  final SpanEventFactory factory = new SpanEventFactory();

  // Specify the size of the ring buffer, must be power of 2.
  final int bufferSize = buffSize;

  // Construct the Disruptor
  disruptor = new Disruptor<SpanEvent>(factory, bufferSize, threadFactory);

  // Connect the handler
  // disruptor.handleEventsWith(new
  // SpanEventHandler("http://localhost:9080/upload"));
  disruptor.handleEventsWith(spanEventHandler);

  // Start the Disruptor, starts all threads running
  disruptor.start();

  final RingBuffer<SpanEvent> ringBuffer = disruptor.getRingBuffer();
  producer = new SpanEventProducer(ringBuffer);
}
 
開發者ID:Yirendai,項目名稱:cicada,代碼行數:26,代碼來源:DisruptorTransfer.java

示例12: initialize

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
private void initialize() {
    logger.info("Start initialize ots writer, table name: {}.", tableName);
    DescribeTableRequest request = new DescribeTableRequest();
    request.setTableName(tableName);
    OTSFuture<DescribeTableResult> result = ots.describeTable(request);
    DescribeTableResult res = result.get();
    this.tableMeta = res.getTableMeta();
    logger.info("End initialize with table meta: {}.", tableMeta);

    RowChangeEvent.RowChangeEventFactory factory = new RowChangeEvent.RowChangeEventFactory();

    // start flush thread, we only need one event handler, so we just set a thread pool with fixed size 1.
    disruptorExecutor = Executors.newFixedThreadPool(1);
    disruptor = new Disruptor<RowChangeEvent>(factory, writerConfig.getBufferSize(), disruptorExecutor);
    ringBuffer = disruptor.getRingBuffer();
    eventHandler = new RowChangeEventHandler(ots, writerConfig, callback, executor);
    disruptor.handleEventsWith(eventHandler);
    disruptor.start();

    // start flush timer
    startFlushTimer(writerConfig.getFlushInterval());
}
 
開發者ID:aliyun,項目名稱:aliyun-tablestore-java-sdk,代碼行數:23,代碼來源:DefaultOTSWriter.java

示例13: AuditReporter

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
AuditReporter(int queueSize, long timeBucketIntervalInSec, int reportFreqMsgCount, int reportFreqIntervalSec,
    boolean combineMetricsAmongHosts) {
  reportExecutor =
      Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(getType() + "-audit-reporter-%d")
          .build());;

  queueSize = Util.ceilingNextPowerOfTwo(queueSize);
  disruptor = new Disruptor<AuditMsgReportTask>(new AuditMsgReportTaskFactory(), queueSize, reportExecutor);
  disruptor.handleEventsWith(new AuditMsgReportTaskHandler(this));
  ringBuffer = disruptor.getRingBuffer();

  aggregator =
      new AuditAggregator(timeBucketIntervalInSec, reportFreqMsgCount, reportFreqIntervalSec,
          combineMetricsAmongHosts);

  SUBMITTED_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.submittedNumber");
  FAILED_TO_SUBMIT_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.failedToSubmitNumber");
  REPORTED_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.reportedNumber");
  FAILED_TO_REPORT_COUNTER = Metrics.getRegistry().meter(getType() + ".auditReporter.failedToReportNumber");
  Metrics.getRegistry().register(getType() + ".auditReporter.queueSize", new Gauge<Integer>() {
    @Override
    public Integer getValue() {
      return (int) disruptor.getRingBuffer().remainingCapacity();
    }
  });
}
 
開發者ID:uber,項目名稱:chaperone,代碼行數:27,代碼來源:AuditReporter.java

示例14: getCurrentDisruptor

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
private Disruptor<ExchangeEvent> getCurrentDisruptor() throws DisruptorNotStartedException {
    Disruptor<ExchangeEvent> currentDisruptor = disruptor.getReference();

    if (currentDisruptor == null) {
        // no current Disruptor reference, we may be reconfiguring or it was not started
        // check which by looking at the reference mark...
        boolean[] changeIsPending = new boolean[1];

        while (currentDisruptor == null) {
            currentDisruptor = disruptor.get(changeIsPending);
            //Check if we are reconfiguring
            if (currentDisruptor == null && !changeIsPending[0]) {
                throw new DisruptorNotStartedException(
                        "Disruptor is not yet started or already shut down.");
            } else if (currentDisruptor == null && changeIsPending[0]) {
                //We should be back shortly...keep trying but spare CPU resources
                LockSupport.parkNanos(1L);
            }
        }
    }

    return currentDisruptor;
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:24,代碼來源:DisruptorReference.java

示例15: open

import com.lmax.disruptor.dsl.Disruptor; //導入依賴的package包/類
/**
 * Start dispatching events
 * 
 * @return a Future that asyncrhonously notifies an observer when this EventReactor is ready
 */
@SuppressWarnings("unchecked")
public CompletableFuture<? extends EventReactor<T>> open() {
  if (isRunning.compareAndSet(false, true)) {
    CompletableFuture<EventReactor<T>> future = new CompletableFuture<>();
    this.disruptor =
        new Disruptor<>(EVENT_FACTORY, ringSize, threadFactory, ProducerType.MULTI,
            new BusySpinWaitStrategy());
    this.disruptor.handleEventsWith(this::handleEvent);
    this.ringBuffer = disruptor.start();

    // Starts a timer thread
    this.timer = new Timer();
    future.complete(this);
    return future;
  } else {
    return CompletableFuture.completedFuture(this);
  }
}
 
開發者ID:FIXTradingCommunity,項目名稱:silverflash,代碼行數:24,代碼來源:EventReactor.java


注:本文中的com.lmax.disruptor.dsl.Disruptor類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。