当前位置: 首页>>代码示例>>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;未经允许,请勿转载。