---
title: "Java advancetopics-metaq"
author: "wbj0110"
date: "2014-04-19T09:27:38Z"
tags: ["metaq"]
categories: ["开源软件"]
slug: "java-advancetopics-metaq"
draft: false
lastmod: "2014-04-19T09:27:36Z"
id: 1956640
url: "https://soledede.iteye.com/blog/1956640"
---

本指南以1.4.5版本的java客户端为起点编写。

- [简单例子](https://github.com/killme2008/Metamorphosis/wiki/%E7%AE%80%E5%8D%95%E4%BE%8B%E5%AD%90)
- [消息](https://github.com/killme2008/Metamorphosis/wiki/Java-message)
- [客户端配置](https://github.com/killme2008/Metamorphosis/wiki/Java-MetaClientConfig)
- [会话工厂MessageSessionFactory](https://github.com/killme2008/Metamorphosis/wiki/Java-SessionFactory)
- [发送消息MessageProducer](https://github.com/killme2008/Metamorphosis/wiki/Java-MessageProducer)
- [订阅消息MessageConsumer](https://github.com/killme2008/Metamorphosis/wiki/Java-MessageConsumer)
- [遍历消息TopicBrowser](https://github.com/killme2008/Metamorphosis/wiki/Java-TopicBrowser)
- [Spring框架支持](https://github.com/killme2008/Metamorphosis/wiki/Spring-Supports)
- [高级主题](https://github.com/killme2008/Metamorphosis/wiki/Java-AdvanceTopics)

这里包括一些MetaQ的高级应用，比如使用log4j appender发送消息作为日志框架，Twitter storm集成以及发送顺序消息等。

# [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E6%B6%88%E6%81%AF%E8%BF%87%E6%BB%A4)消息过滤

在一些场景里，你可能希望消费者只消费一个topic下的部分满足特定要求的消息，而不是全部消费。通常，我会建议使用消息属性(attribute)来过滤消息，在`MessageListener`接收到消息的时候，判断`message.getAttribute()`返回是否符合要求来决定是否消费。也就是将过滤做到客户端。这样的代价是客户端还是会拉取不想消费的消息，浪费带宽。从1.4.6开始，MetaQ同时提供服务端和客户端过滤消息的接口`ConsumerMessageFilter`，用来过滤消息。

## [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BF%87%E6%BB%A4)客户端过滤

具体见[订阅消息MessageConsumer](https://github.com/killme2008/Metamorphosis/wiki/Java-MessageConsumer)的消息过滤一节。

## [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E8%BF%87%E6%BB%A4)服务端过滤

同样，你需要实现`ConsumerMessageFilter`接口，并将你的实现打包成jar文件，放到服务器Broker的provided目录，接下来，配置server.ini文件，假设你的实现是`com.xxxx.MyMessageFilter`类，你想为消费分组`log-processor`过滤topic是`log`下的消息，那么你应该这样配置：

```
[topic=log]
group.log-processor=com.xxxx.MyMessageFilter
```

配置之后，重启Broker，消息过滤将立即生效。

总结来说，服务端消息过滤需要五个步骤：

- 实现`ConsumerMessageFilter`接口，实现你的消息过滤器。
- 打包实现成jar文件，可以用maven等构建工具，也可以用eclipse导出，如果你的过滤器实现用到了第三方库，也请一起打包进jar包，或者拷贝到服务器的provided目录。
- 将打包后的jar和依赖包，拷贝到服务器的provided目录。
- 配置server.ini，找到你想过滤的topic配置，添加`group.xxx=MyFilter`，其中`xxx`是你的消费分组名称，而`MyFilter`就是你的过滤器实现类名。
- 重启Broker，过滤即时生效。

# [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E6%B6%88%E6%81%AF%E5%8E%BB%E9%87%8D)消息去重

首先，MetaQ会尽量避免消息重复，每个topic的每个分区都只会被一个consumer消费，但是在consumer做负载均衡的过程中，可能因为consumer列表的变更，导致分区分配规则不一致，从而导致部分消息会被重复消费。这种情况可以通过下列手段来避免：

- 合理设置订阅的maxSize，这个缓冲区大小，最好只是略大于你的最大的消息大小（包括消息头部20个字节）。比如你的最大消息是1024字节，那么建议maxSize可以设置成1044字节以上。如果有消息属性，这个值还应该加上消息属性的长度，并加上4个字节的大小。
- 通过1.4.6引入的`MessageIdCache`接口的消息缓冲来去重。通过将消费过的消息id在缓冲中标示为已经处理，来避免重复消费。

我们重点介绍下`MessageIdCache`，这个接口如下：

```
package com.taobao.metamorphosis.client.consumer;

/**
 * Message id cache to prevent duplicated messages for the same consumer group.
 * 
 * @author dennis<killme2008@gmail.com>
 * @since 1.4.6
 * 
 */
public interface MessageIdCache {

    /**
     * Added key value to cache
     * 
     * @param key
     * @param exists
     */
    public void put(String key, Byte exists);


    /**
     * Get value from cache,it the item is exists,it must be returned.
     * 
     * @param key
     * @return
     */
    public Byte get(String key);
}
```

默认1.4.6版本有一个实现`ConcurrentLRUHashMap`，使用LRU算法维护一个缓存map。默认启用这个实现，固定大小为4096，可以通过`metaq.consumer.message_ids.lru_cache.size`环境变量修改这个大小。这个实现是全局共享的，也就是所有的`MessageConsumer`都使用同一个缓存来做消息去重。

默认的这个实现仍然是JVM级别的去重，如果你的消费者是分布式的，那么可能需要一个集中式的全局缓冲来去重，比如在example里我们提供了一个基于memcached的实现：

```
package com.taobao.metamorphosis.example.cache;

import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taobao.metamorphosis.client.consumer.MessageIdCache;


public class MemcachedMessageIdCache implements MessageIdCache {
    private final MemcachedClient memcachedClient;
    private int expireInSeconds = 60;
    private static final Log log = LogFactory.getLog(MemcachedMessageIdCache.class);


    public MemcachedMessageIdCache(MemcachedClient client) {
        this.memcachedClient = client;
    }


    public void setExpireInSeconds(int expireInSeconds) {
        this.expireInSeconds = expireInSeconds;
    }


    public int getExpireInSeconds() {
        return this.expireInSeconds;
    }


    @Override
    public void put(String key, Byte exists) {
        try {
            this.memcachedClient.set(key, this.expireInSeconds, exists);
        }
        catch (MemcachedException e) {
            log.error("Added message id cache failed", e);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        catch (TimeoutException e) {
            log.error("Added message id cache timeout", e);
        }

    }


    @Override
    public Byte get(String key) {
        try {
            return this.memcachedClient.get(key);
        }
        catch (MemcachedException e) {
            log.error("Get item from message id cache failed", e);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        catch (TimeoutException e) {
            log.error("Get item from message id cache timeout", e);
        }
        return null;
    }

}
```

默认会将处理过的消息保存在memcached里，并设置过期时间为1分钟。你也可以实现自己的`MessageIdCache`，实现后通过`SimpleFetchManager.setMessageIdCache`这个静态方法设置进去就可以使用你的实现。

## [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E4%BD%BF%E7%94%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1%E5%8E%BB%E9%87%8D)使用数据库事务去重

如果你消费消息的目的是操作某个数据库，比如将消息的内容写入数据库，或者根据消息内容更新数据库。那么通过将offset存储到同一个数据库，在消费消息的同时更新offset到数据库，也可以实现消息去重。

我们已经提供了`MysqlOffsetStorage`，你也可以实现其他数据库的offset存储，在`MessageListener.recieveMessages`方法接收消息的时候，你可以通过`SimpleFetchManager.currentTopicRegInfo`静态方法，获取当前消费消息的offset信息，并在一个事务里同时更新offset和消费消息。

# [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E4%BD%BF%E7%94%A8log4j%E6%89%A9%E5%B1%95%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF)使用log4j扩展发送消息

参见 [使用Log4j发送消息](https://github.com/killme2008/Metamorphosis/wiki/%E4%BD%BF%E7%94%A8Log4j%E6%89%A9%E5%B1%95%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF)

# [](https://github.com/killme2008/Metamorphosis/wiki/Java-advancetopics#%E4%BD%BF%E7%94%A8metaq%E4%BD%9C%E4%B8%BAtwitter-storm%E6%95%B0%E6%8D%AE%E6%BA%90)使用MetaQ作为twitter storm数据源

Maven引用MetaQ storm spout:

```
<dependency>
    <groupId>com.taobao.metamorphosis</groupId>
    <artifactId>metamorphosis-storm-spout</artifactId>
    <version>1.4.6.2</version>
</dependency>
```

一个示范性的Topology（在example工程里）:

```
package com.taobao.metamorphosis.example.storm;

import static com.taobao.metamorphosis.example.Help.initMetaConfig;

import java.util.Map;

import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;

import com.taobao.metamorphosis.client.consumer.ConsumerConfig;
import com.taobao.metamorphosis.storm.scheme.StringScheme;
import com.taobao.metamorphosis.storm.spout.MetaSpout;


public class TestTopology {
    public static class FailEveryOther extends BaseRichBolt {

        OutputCollector _collector;
        int i = 0;


        @Override
        public void prepare(Map map, TopologyContext tc, OutputCollector collector) {
            this._collector = collector;
        }


        @Override
        public void execute(Tuple tuple) {
            this.i++;
            if (this.i % 2 == 0) {
                this._collector.fail(tuple);
            }
            else {
                this._collector.ack(tuple);
            }
        }


        @Override
        public void declareOutputFields(OutputFieldsDeclarer declarer) {
        }
    }


    public static void main(String[] args) {
        TopologyBuilder builder = new TopologyBuilder();
        builder.setSpout("spout",
            new MetaSpout(new MetaConfig(), new ConsumerConfig("storm-spout"), new StringScheme()), 10);
        builder.setBolt("bolt", new FailEveryOther()).shuffleGrouping("spout");

        Config conf = new Config();
        // Set the consume topic
        conf.put(MetaSpout.TOPIC, "neta-test");
        // Set the max buffer size in bytes to fetch messages.
        conf.put(MetaSpout.FETCH_MAX_SIZE, 1024 * 1024);

        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("test", conf, builder.createTopology());
    }
}
```

`MetaSpout`接收三个参数，首先是`MetaClientConfig`和`ConsumerConfig`，这跟配置一个普通的消息消费者没有什么区别，具体见前面的章节。第三个参数`scheme`除了用于`declareOutputFields`之外，还用来反序列化MetaQ的消息data：

```
//MetaSpout.java
 @Override
    public void nextTuple() {
        if (this.messageConsumer != null) {
            try {

                final MetaMessageWrapper wrapper = this.messageQueue.poll(WAIT_FOR_NEXT_MESSAGE, TimeUnit.MILLISECONDS);
                if (wrapper == null) {
                    return;
                }
                final Message message = wrapper.message;
                this.collector.emit(this.scheme.deserialize(message.getData()), message.getId());
            }
            catch (final InterruptedException e) {
                // interrupted while waiting for message, big deal
            }
        }
    }
```

默认提供了一个`StringScheme`：

```
package com.taobao.metamorphosis.storm.scheme;

import backtype.storm.spout.Scheme;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class StringScheme implements Scheme {

    public List<Object> deserialize(byte[] bytes) {
        try {
            return new Values(new String(bytes, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public Fields getOutputFields() {
        return new Fields("str");
    }
}
```

声明output fields为`str`，并且认为消息的data是一个字符串。

Topology需要配置订阅的`topic`和`fetchSize`，最终提交到storm集群。

转自 metaq's wiki