Cassandra源码阅读(未完成)

SEDA

Cassandra 的操作使用的并发模型。SEDA将应用程序分解为由事件队列分隔的各个阶段,并引入动态资源控制器的概念,允许应用程序动态调整,不断适应变化的负载。它是事件驱动的,收到请求后,先构造event,然后放到stage的请求队列中,stage从请求队列里拿到event进行处理,处理结束后,构造event_next并放入stage_next的请求队列。Stage之间通过队列来衔接,每个stage单独治理,各stage之间相互解耦。以异步响应的方式处理事件。

image

Threaded server design:Each incoming request is dispatched to a separate thread,which performs the entire processing for the request and return a result to the client. Edges re-preset control flow between components. Note that other I/O operations,such as disk access,are not shown here,but are incorporated within each threads' request processing

image

cassandra.concurrent

Cassandra中基于SEDA的并发模型实现目录。它是整个模型的基础。

StageManager

StageManager类中主要维护了一份stages列表。

EnumMap<Stage, LocalAwareExecutorService> stages = new EnumMap<>(Stage.class);

static {

    stages.put(Stage.TRACING, tracingExecutor());

......

}

根据不同的Stage枚举创建出不同的ExecutorService,在使用时获取对应的ExecuteService执行不同的任务。

Ex:

ListenableFutureTask task = ListenableFutureTask.create(runnable, null); StageManager.getStage(Stage.GOSSIP).execute(task);

StageManager.getStage(Stage.TRACING).execute(new WrappedRunnable(){});

LocalAwareExecutorService

Cassandra所有线程池的抽象接口,继承ExecutorService类,构建了基本的任务模型。添加了两个自己的方法:

    // we need a way to inject a TraceState directly into the Executor context without going through
    // the global Tracing sessions; see CASSANDRA-5668
    public void execute(Runnable command, ExecutorLocals locals);

    // permits executing in the context of the submitting thread
    public void maybeExecuteImmediately(Runnable command);

ExecutorLocals是cassandra的trace跟踪类。调用execute(Runnable command, ExecutorLocals locals)实现了链路的跟踪。

cassandra-concurrent.jpg

常用的实现类只有两个:

  1. SEPExecutor:Executor中引用了SharedExecutorPool,SharedExecutorPool并非单例模式,但它在cassandra中是一个静态单例。
public static final SharedExecutorPool SHARED = new SharedExecutorPool("SharedPool");

通过newExecutor方法创建SEPExecutor,把自己方入创建的SEPExecutor中,并维护一个SEPExecutor列表。这意味着所有的共享一个SharedExecutorPool

    public LocalAwareExecutorService newExecutor(int maxConcurrency, int maxQueuedTasks, String jmxPath, String name)
    {
        SEPExecutor executor = new SEPExecutor(this, maxConcurrency, maxQueuedTasks, jmxPath, name);
        executors.add(executor);
        return executor;
    }

SEPExecutor调用execute时,SEPExecutor会把Thread封装成一个FutureTask放入Queue。这些Task最终是通过SEPWorker去执行的,SEPWorker在SEPExecutor的execute第一次被调用或停止后第一次被调用时通过SharedExecutorPool创建一个Work.SPINNING的SEPWorker,他是一个自循环worker,他有匿名内部类Worker可以用来治理状态和保存SEPExecutor,使得SEPWorker能找到SEPExecutor。由于execute放入Runnable是会使用Work.SPINNING的worker,所以任务并不会立刻被执行,SEPWorker会在自旋时分配SEPExecutor以及切换状态。而上面使用提到的maybeExecuteImmediately方法会立即执行任务。

// 4种Work:
static final Work STOP_SIGNALLED = new Work();
static final Work STOPPED = new Work();
static final Work SPINNING = new Work();
static final Work WORKING = new Work();
Work work = schedule(Work.SPINNING);
new SEPWorker(workerId.incrementAndGet(), work, this);

SEPWorker创建后启动Thread,Thread自旋执行ThreadPool

SEPWorker(Long workerId, Work initialState, SharedExecutorPool pool)
    {
        this.pool = pool;
        this.workerId = workerId;
        thread = new FastThreadLocalThread(this, pool.poolName + "-Worker-" + workerId);
        thread.setDaemon(true);
        set(initialState);
        thread.start();
    }

public void run()
    {
        SEPExecutor assigned = null;
        Runnable task = null;
        try
        {
            while (true)
            {
               if (isSpinning() && !selfAssign())
                 {
                    doWaitSpin();
                    continue;
                }
              ...  
 }
         }
    }

SEPExecutor、SEPWorker和SharedExecutorPool组成了一套线程池的体系。与其他线程池不用的是,它所有worker共享一个pool,空闲的worker自由的寻找需要执行的executor,executor保存需要执行的runnable。

  1. JMXEnabledThreadPoolExecutor:
    JMXEnabledThreadPoolExecutor相对简单一些,它继承了ThreadPoolExecutor类,大部分功能和父类相同,提供了部分扩展。比如DebuggableThreadPoolExecutor类中对Exception处理的扩展,以及ThreadPoolExecutor创建时维护了ThreadPoolMetrics和MBeanWrapper这两个类。
public static final RejectedExecutionHandler blockingExecutionHandler = new RejectedExecutionHandler()
    {...... };
 public DebuggableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
    {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
        allowCoreThreadTimeOut(true);

        // block task submissions until queue has room.
        // this is fighting TPE's design a bit because TPE rejects if queue.offer reports a full queue.
        // we'll just override this with a handler that retries until it gets in.  ugly, but effective.
        // (there is an extensive analysis of the options here at
        //  http://today.java.net/pub/a/today/2008/10/23/creating-a-notifying-blocking-thread-pool-executor.html)
        this.setRejectedExecutionHandler(blockingExecutionHandler);
    }
public JMXEnabledThreadPoolExecutor(int corePoolSize,
                                        int maxPoolSize,
                                        long keepAliveTime,
                                        TimeUnit unit,
                                        BlockingQueue<Runnable> workQueue,
                                        NamedThreadFactory threadFactory,
                                        String jmxPath)
    {
        super(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue, threadFactory);
        super.prestartAllCoreThreads();
        metrics = new ThreadPoolMetrics(this, jmxPath, threadFactory.id);

        mbeanName = "org.apache.cassandra." + jmxPath + ":type=" + threadFactory.id;
        MBeanWrapper.instance.registerMBean(this, mbeanName);
    }

ThreadPoolMetrics:基于metrics-core.jar包中的MetricRegistry实现对于该线程池指标的监控。
MBeanWrapper:MBeanWrapper有两个实现类NoOpMBeanWrapper、PlatformMBeanWrapper。NoOpMBeanWrapper不做任何事情。PlatformMBeanWrapper使用了JMX的MBeanServer类。


Cassandra启动

Cassandra通过CassandraDaemon类的main函数启动

    public static void main(String[] args)
    {
        instance.activate();
    }

启动时,Cassandra需要做以下几件事:

  1. 初始化配置文件
public void applyConfig()
    {
        DatabaseDescriptor.daemonInitialization();
    }

DatabaseDescriptor是Cassandra的配置管理类,Cassandra节点的配置属性会保存在Config类中。

public static void daemonInitialization() throws ConfigurationException
    {
        daemonInitialization(DatabaseDescriptor::loadConfig); //通过loadConfig方法将Config加载入DatabaseDescriptor。
    }

Cassandra读写操作

通过thrift包我们可以对Cassandra进行通信,CassandraServer是读写命令的入口。

1. Read

相关知识点:

  1. SEDA模型:cassandra核心思想
  2. ThreadPoolExecutor:多线程管理相关点
  3. Metric:线程调用监控
  4. MBeanServer:
  5. Netty:Cassandra基于CQL3协议的通讯基于Netty框架

参考资料:

SEDA: An Architecture for Well-Conditioned, Scalable Internet Services
Understanding Cassandra Code Base

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 亲爱的你啊, 见信好。 听说你最近遇到许多事情,急需要灌一大碗毒鸡汤。我想,你不大不小的年纪可还算是过的安稳,...
    milie阅读 670评论 1 2
  • 生活就是这样,你勇敢、努力,还是会被淹没,被无视,被遗弃,只因为你不能为别人带来更大的好处。 人,连选择朋友的时候...
    斑马_zebra阅读 96评论 0 0