顺序写的本质其实不是"顺序"写,而是内存映射
在rocketmq中,每个commitlog的大小都是固定的,比如是1024m,那么在操作这个commitlog
时就可以使用内存映射将整个文件映射进内存,就算rocketmq只产生了一条消息,这个commitlog
的大小也是1024m,只是用做了一个标记,标记下次写入消息到这个commitlog时从哪里开始
写入.如果不固定大小的话,内存映射的时候就无法确定结束位置.
private static int lastIndex;
private static volatile long fileLength = 1024 * 1024 * 1024L;
public static void main(String[] args) {
try (RandomAccessFile f = new RandomAccessFile("D:\\a.log", "rw")) {
FileChannel fc = f.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, fileLength);
byte number0 = 49;
mbb.put(lastIndex + 1, number0);
} catch (Exception e) {
e.printStackTrace();
}
}
就是这个fc.map()的第三个参数无法确定,如果这个参数无法确定,那么要么映射了commitlog一部分数据,要么超过了commitlog的大小,映射失败导致报错.
rocketmq流程
生产者生产消息发送到broker,broker收到消息后刷盘并返回确认给生产者.
刷盘的流程:获取当前的mapfile(就是MappedByteBuffer的封装),这个mapfile映射了一个
commitlog文件,写入一条消息到这个commitlog,再获取当前的consumeQueue文件,将这
条消息在这个commitlog的偏移信息记录进consumeQueue.
消费流程:broker推送消息给消费者,消费者消费完消息给予确认,broker收到确认后会在
consumeOffset.json文件中记录下消费完成,如果由于网络原因broker未收到确认,则broker
会调用消费者的消费确认接口去确认消息是否完成了消费.
同一个文件的MappedByteBuffer的共享
String woshihaoren = "woshihaoren";
try (RandomAccessFile f = new RandomAccessFile("D:\\a.txt", "rw")) {
FileChannel fc = f.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, woshihaoren.length());
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(woshihaoren.length());
byteBuffer.put(woshihaoren.getBytes());
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
fc.write(byteBuffer);
}
byte[] bytes = new byte[woshihaoren.length()];
mbb.get(bytes);
System.out.println(new String(bytes));
} catch (Exception e) {
e.printStackTrace();
}
原理是同一个文件的映射在内存中只有一个,directByteBuffer的操作都是直接操作
pageCache,pageCache只有一个,是所有进程共享的.