其他分享
首页 > 其他分享> > 知识点总结(二)--Disruptor

知识点总结(二)--Disruptor

作者:互联网

  1. Disruptor
    1.  

    2.  

       

    3.  

       

    4.  

      volatile关键字的作用:保证可见性,禁止指令重排,不保证原子性

    5.  

      简单用法:

    6.  

       

    7.  

       

    8.  

       

    9. //消费者
      public class MsgConsumer implements EventHandler<MsgEvent>{
          private String name;
          public MsgConsumer(String name){
              this.name = name;
          }
          @Override
          public void onEvent(MsgEvent msgEvent, long l, boolean b) throws Exception {
              System.out.println(this.name+" -> 接收到信息: "+msgEvent.getValue());
          }
      }
      
      //生产者处理
      public class MsgProducer {
          private Disruptor disruptor;
          public MsgProducer(Disruptor disruptor){
              this.disruptor = disruptor;
          }
      
          public void send(String data){
              RingBuffer<MsgEvent> ringBuffer = this.disruptor.getRingBuffer();
              long next = ringBuffer.next();
              try{
                  MsgEvent event = ringBuffer.get(next);
                  event.setValue(data);
              }finally {
                  ringBuffer.publish(next);
              }
          }
      
          public void send(List<String> dataList){
              dataList.stream().forEach(data -> this.send(data));
          }
      }
      
      
      //触发测试
      public class DisruptorDemo {
          @Test
          public void test(){
              Disruptor<MsgEvent> disruptor = new Disruptor<>(MsgEvent::new, 1024, Executors.defaultThreadFactory());
      
              //定义消费者
              MsgConsumer msg1 = new MsgConsumer("1");
              MsgConsumer msg2 = new MsgConsumer("2");
              MsgConsumer msg3 = new MsgConsumer("3");
      
              //绑定配置关系
              disruptor.handleEventsWith(msg1, msg2, msg3);
              disruptor.start();
      
              // 定义要发送的数据
              MsgProducer msgProducer = new MsgProducer(disruptor);
              msgProducer.send(Arrays.asList("nihao","hah"));
          }
      }

       

    10.  

       

       

       

标签:知识点,name,disruptor,--,Disruptor,MsgConsumer,new,public
来源: https://www.cnblogs.com/zzhAylm/p/15499882.html