`
javahacker2
  • 浏览: 41385 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

metaq源码分析(二)

 
阅读更多

消息,是MetaQ最重要的资源,在分析MetaQ之前必须了解的概念,我们所做的一切都是围绕消息进行的,让我们看看MetaQ中消息的定义是怎样的,MetaQ的类Message定义了消息的格式:

Java代码  收藏代码
  1. public class Message implements Serializable {  
  2.   private long id; //消息的ID  
  3.   private String topic; //消息属于哪个主题  
  4.   private byte[] data;  //消息的内容  
  5.   private String attribute; //消息的属性  
  6.   private int flag; //属性标志位,如果属性不为空,则该标志位true  
  7.   private Partition partition; //该主题下的哪个分区,简单的理解为发送到该主题下的哪个队列  
  8.   private transient boolean readOnly; //消息是否只读  
  9.   private transient boolean rollbackOnly = false//该消息是否需要回滚,主要用于事务实现的需要  
  10. }  

从对消息的定义,我们可以看出消息都有一个唯一的ID,并且归属于某个主题,发送到该主题下的某个分区,具有一些基本属性。

 

MetaQ分为Broker和Client以及Zookeeper,系统结构如下:

 

 

 

 

下面我们先分析Broker源码。

 

Broker主要围绕发送消息和消费消息的主线进行,对于Broker来说就是输入、输出流的处理。在该主线下,Broker主要分为如下模块:网络传输模块、消息存储模块、消息统计模块以及事务模块,本篇首先针对独立性较强的消息存储模块进行分析。

 

在进行存储模块分析之前,我们得了解Broker中的一个重要的类 MetaConfig,MetaConfig是Broker配置加载器,通过MetaConfig可以获取到各模块相关的配置,所以MetaConfig 是贯穿所有模块的类。MetaConfig实现MetaConfigMBean接口,该接口定义如下:

Java代码  收藏代码
  1. public interface MetaConfigMBean {  
  2.     /** 
  3.      * Reload topics configuration 
  4.      */  
  5.     public void reload();  
  6.    
  7.     /**关闭分区 */  
  8.     public void closePartitions(String topic, int start, int end);  
  9.    
  10.     /**打开一个topic的所有分区 */  
  11.     public void openPartitions(String topic);  
  12. }  

 

MetaConfig注册到了MBeanServer上,所以可以通过JMX协议重新加 载配置以及关闭和打开分区。为了加载的配置立即生效,MetaConfig内置了一个通知机制,可以通过向MetaConfig注册监听器的方式关注相关 配置的变化,监听器需实现PropertyChangeListener接口。

Java代码  收藏代码
  1. public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {  
  2.       this.propertyChangeSupport.addPropertyChangeListener(propertyName, listener);  
  3. }  
  4.    
  5. public void removePropertyChangeListener(final PropertyChangeListener listener) {  
  6.       this.propertyChangeSupport.removePropertyChangeListener(listener);  
  7. }  

 

目前MetaConfig发出的事件通知有三种:配置文件发生变化(configFileChecksum)、主题发生变化(topics,topicConfigMap)以及刷新存储的频率发生变化(unflushInterval),代码如下:

Java代码  收藏代码
  1. //configFileChecksum通知  
  2. private Ini createIni(final File file) throws IOException, InvalidFileFormatException {  
  3.       ……  
  4.       this.propertyChangeSupport.firePropertyChange("configFileChecksum"nullnull);  
  5.       return conf;  
  6. }  
  7.    
  8. public void setConfigFileChecksum(long configFileChecksum) {  
  9.       this.configFileChecksum = configFileChecksum;  
  10.       this.propertyChangeSupport.firePropertyChange("configFileChecksum"nullnull);  
  11. }  
  12.    
  13. //topics、topicConfigMap和unflushInterval通知  
  14. private void populateTopicsConfig(final Ini conf) {  
  15. ……  
  16. if (!newTopicConfigMap.equals(this.topicConfigMap)) {  
  17.           this.topics = newTopics;  
  18.           this.topicConfigMap = newTopicConfigMap;  
  19.           this.propertyChangeSupport.firePropertyChange("topics"nullnull);  
  20.           this.propertyChangeSupport.firePropertyChange("topicConfigMap"nullnull);  
  21.   }  
  22.   this.propertyChangeSupport.firePropertyChange("unflushInterval"nullnull);  
  23. ……  

需要注意的是,调用reload方法时,只对topic的配置生效,对全局配置不生效,只重载topic的配置。

 

好吧,废话了许多,让我们正式进入存储模块的分析吧。

 

Broker的存储模块用于存储Client发送的等待被消费的消息,Broker采用文件存储的方式来存储消息,存储模块类图如下:

 



  

 

MessageSet代表一个消息集合,可能是一个文件也可能是文件的一部分,其定义如下:

 

Java代码  收藏代码
  1. /** 
  2.  * 消息集合 
  3.  */  
  4. public interface MessageSet {  
  5.   public MessageSet slice(long offset, long limit) throws IOException; //获取一个消息集合  
  6.    
  7.   public void write(GetCommand getCommand, SessionContext ctx);  
  8.    
  9.   public long append(ByteBuffer buff) throws IOException; //存储一个消息,这时候还没有存储到磁盘,需要调用flush方法才能保证存储到磁盘  
  10.    
  11.   public void flush() throws IOException; //提交到磁盘  
  12.    
  13.   public void read(final ByteBuffer bf, long offset) throws IOException; //读取消息  
  14.    
  15.   public void read(final ByteBuffer bf) throws IOException; //读取消息  
  16.    
  17.   public long getMessageCount();//该集合的消息数量  
  18. }  

FileMessageSet实现了MessageSet接口和Closeable接口,实现Closeable接口主要是为了在文件关闭的时候确保文件通道关闭以及内容是否提交到磁盘

 

Java代码  收藏代码
  1. public void close() throws IOException {  
  2.       if (!this.channel.isOpen()) {  
  3.           return;  
  4.       }  
  5.       //保证在文件关闭前,将内容提交到磁盘,而不是在缓存中  
  6.       if (this.mutable) {  
  7.           this.flush();  
  8.       }  
  9.       //关闭文件通道  
  10.       this.channel.close();  
  11.   }  

下面让我们来具体分析一下FileMessageSet这个类,

Java代码  收藏代码
  1. public class FileMessageSet implements MessageSet, Closeable {  
  2.     ……  
  3.   private final FileChannel channel; //对应的文件通道  
  4.   private final AtomicLong messageCount; //内容数量  
  5.   private final AtomicLong sizeInBytes;   
  6.   private final AtomicLong highWaterMark; // 已经确保写入磁盘的水位  
  7.   private final long offset; // 镜像offset  
  8.   private boolean mutable;   // 是否可变  
  9.    
  10.   public FileMessageSet(final FileChannel channel, final long offset, final long limit, final boolean mutable) throws IOException {  
  11.       this.channel = channel;  
  12.       this.offset = offset;  
  13.       this.messageCount = new AtomicLong(0);  
  14.       this.sizeInBytes = new AtomicLong(0);  
  15.       this.highWaterMark = new AtomicLong(0);  
  16.       this.mutable = mutable;  
  17.       if (mutable) {   
  18.           final long startMs = System.currentTimeMillis();  
  19.           final long truncated = this.recover();  
  20.           if (this.messageCount.get() > 0) {  
  21.               log.info("Recovery succeeded in " + (System.currentTimeMillis() - startMs) / 1000 + " seconds. " + truncated + " bytes truncated.");  
  22.           }  
  23.       } else {  
  24.           try {  
  25.               this.sizeInBytes.set(Math.min(channel.size(), limit) - offset);  
  26.               this.highWaterMark.set(this.sizeInBytes.get());  
  27.           } catch (final Exception e) {  
  28.               log.error("Set sizeInBytes error", e);  
  29.           }  
  30.       }  
  31.   }  
  32. // 注意FileMessageSet的mutable属性,如果mutable为true的时候,将会调用recover()方法,该方法主要是验证文件内 容的完整性,后面会详细介绍,如果mutable为false的时候,表明该文件不可更改,这个时候磁盘水位和sizeInBytes的值均为文件大小。  
  33.    
  34. ……  
  35. public long append(final ByteBuffer buf) throws IOException {  
  36.       //如果mutable属性为false的时候,不允许追加消息在文件尾  
  37.       if (!this.mutable) {  
  38.           throw new UnsupportedOperationException("Immutable message set");  
  39.       }  
  40.       final long offset = this.sizeInBytes.get();  
  41.       int sizeInBytes = 0;  
  42.       while (buf.hasRemaining()) {  
  43.           sizeInBytes += this.channel.write(buf);  
  44.       }  
  45.       //在这个时候并没有将内容写入磁盘,还在通道的缓存中,需要在适当的时候调用flush方法  
  46.        //这个时候磁盘的水位是不更新的,只有在保证写入磁盘才会更新磁盘的水位信息  
  47.       this.sizeInBytes.addAndGet(sizeInBytes); 、  
  48.       this.messageCount.incrementAndGet();  
  49.       return offset;  
  50.   }  
  51.    
  52.    //提交到磁盘  
  53.   public void flush() throws IOException {  
  54.       this.channel.force(true);  
  55.       this.highWaterMark.set(this.sizeInBytes.get());  
  56.   }  
  57. ……  
  58. @Override  
  59.   public MessageSet slice(final long offset, final long limit) throws IOException {  
  60.       //返回消息集  
  61. return new FileMessageSet(this.channel, offset, limit, false);  
  62.   }  
  63.    
  64.   static final Logger transferLog = LoggerFactory.getLogger("TransferLog");  
  65.    
  66.   @Override  
  67.   public void read(final ByteBuffer bf, final long offset) throws IOException {  
  68.       //读取内容  
  69. int size = 0;  
  70.       while (bf.hasRemaining()) {  
  71.           final int l = this.channel.read(bf, offset + size);  
  72.           if (l < 0) {  
  73.               break;  
  74.           }  
  75.           size += l;  
  76.       }  
  77.   }  
  78.    
  79.   @Override  
  80.   public void read(final ByteBuffer bf) throws IOException {  
  81.       this.read(bf, this.offset);  
  82.   }  
  83.    
  84.  //下面的write方法主要是提供zero拷贝  
  85.   @Override  
  86.   public void write(final GetCommand getCommand, final SessionContext ctx) {  
  87.       final IoBuffer buf = this.makeHead(getCommand.getOpaque(), this.sizeInBytes.get());  
  88.       // transfer to socket  
  89.       this.tryToLogTransferInfo(getCommand, ctx.getConnection());  
  90.       ctx.getConnection().transferFrom(buf, nullthis.channel, this.offset, this.sizeInBytes.get());  
  91.   }  
  92.    
  93.   public long write(final WritableByteChannel socketChanel) throws IOException {  
  94.       try {  
  95.           return this.getFileChannel().transferTo(this.offset, this.getSizeInBytes(), socketChanel);  
  96.       } catch (final IOException e) {  
  97.           // Check to see if the IOException is being thrown due to  
  98.           // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5103988  
  99.           final String message = e.getMessage();  
  100.           if (message != null && message.contains("temporarily unavailable")) {  
  101.               return 0;  
  102.           }  
  103.           throw e;  
  104.       }  
  105.   }  
  106. ……  
  107. private static boolean fastBoot = Boolean.valueOf(System.getProperty("meta.fast_boot""false"));  
  108.    
  109.   private long recover() throws IOException {  
  110.        //如果在System属性里设置了 meta.fast_boot为true,表示快速启动,快速启动不检测文件是否损坏,不对内容进行校验  
  111.       if (fastBoot) {  
  112.           final long size = this.channel.size();  
  113.           this.sizeInBytes.set(size);  
  114.           this.highWaterMark.set(size);  
  115.           this.messageCount.set(0);  
  116.           this.channel.position(size);  
  117.           return 0;  
  118.       }  
  119.       if (!this.mutable) {  
  120.           throw new UnsupportedOperationException("Immutable message set");  
  121.       }  
  122.       final long len = this.channel.size();  
  123.       final ByteBuffer buf = ByteBuffer.allocate(MessageUtils.HEADER_LEN);  
  124.       long validUpTo = 0L;  
  125.       long next = 0L;  
  126.       long msgCount = 0;  
  127.       do {  
  128.           next = this.validateMessage(buf, validUpTo, len);  
  129.           if (next >= 0) {  
  130.               msgCount++;  
  131.               validUpTo = next;  
  132.           }  
  133.       } while (next >= 0);  
  134.       this.channel.truncate(validUpTo);  
  135.       this.sizeInBytes.set(validUpTo);  
  136.       this.highWaterMark.set(validUpTo);  
  137.       this.messageCount.set(msgCount);  
  138.       this.channel.position(validUpTo);  
  139.       return len - validUpTo;  
  140.   }  
  141.    
  142. 消息在磁盘上存储结构如下:  
  143.   /* 
  144.    * 20个字节的头部 * 
  145.    * <ul> 
  146.    * <li>message length(4 bytes),including attribute and payload</li> 
  147.    * <li>checksum(4 bytes)</li> 
  148.    * <li>message id(8 bytes)</li> 
  149.    * <li>message flag(4 bytes)</li> 
  150.    * </ul> 
  151.    *  length长度的内容 
  152.       */  
  153.   //在存储之前将checksum的信息存入到磁盘,读取的时候再进行校验,比较前后的  
  154.   //checksum是否一致,防止消息被篡改  
  155.   private long validateMessage(final ByteBuffer buf, final long start, final long len) throws IOException {  
  156.       buf.rewind();  
  157.       long read = this.channel.read(buf);  
  158.       if (read < MessageUtils.HEADER_LEN) {  
  159.           return -1;  
  160.       }  
  161.       buf.flip();  
  162.       final int messageLen = buf.getInt();  
  163.       final long next = start + MessageUtils.HEADER_LEN + messageLen;  
  164.       if (next > len) {  
  165.           return -1;  
  166.       }  
  167.       final int checksum = buf.getInt();  
  168.       if (messageLen < 0) {  
  169.           // 数据损坏  
  170.           return -1;  
  171.       }  
  172.    
  173.       final ByteBuffer messageBuffer = ByteBuffer.allocate(messageLen);  
  174. //        long curr = start + MessageUtils.HEADER_LEN;  
  175.       while (messageBuffer.hasRemaining()) {  
  176.           read = this.channel.read(messageBuffer);  
  177.           if (read < 0) {  
  178.               throw new IOException("文件在recover过程中被修改");  
  179.           }  
  180. //            curr += read;  
  181.       }  
  182.       if (CheckSum.crc32(messageBuffer.array()) != checksum) {  
  183.           //采用crc32对内容进行校验是否一致  
  184.           return -1;  
  185.       } else {  
  186.           return next;  
  187.       }  
  188.   }  

    FileMessageSet是MetaQ 服务器端存储的一个元素,代表了对一个文件的读写操作,能够对文件内容进行完整性和一致性校验,并能提供统计数据,接下来要介绍的是通过 MessageStore怎样的组合将一个个的FileMessageSet,单纯的讲,MetaQ的存储非常值得借鉴。

分享到:
评论
1 楼 jiangduxi 2015-06-14  
您好,请教下这个开源中间件是否适用 IM。尤其是移动通讯中的弱网络的情况!
谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics