你好,游客 登录 注册 搜索
背景:
阅读新闻

如何在项目中引入MetaQ消息收发机制

[日期:2016-12-16] 来源:Linux社区  作者:jytx [字体: ]

当需要异步发送和接收大量消息时,需要在Crystal项目中引入MetaQ消息收发机制。

关于MetaQ使用的官方例子可参考:https://github.com/killme2008/Metamorphosis/wiki/%E7%AE%80%E5%8D%95%E4%BE%8B%E5%AD%90

Crystal框架将MetaQ进行封装,简化MetaQ的使用,具体如下:

消息生产端

  1. 引入crystal-metaq-producer项目最为依赖:

    <dependency>
        <groupId>com.gsoft.crystal</groupId>
        <artifactId>crystal-metaq-producer</artifactId>
    </dependency>
  2. 调用消息发送对象,发送指定消息:

    @Resource
    private MessageProducer mp;
    @Resource
    private MessageConsumer mc;
     
    @Test
    public void testProducer() {
        String topic = "test";
        final String msg = "test message !";
         
        mp.publish(topic);
        Message message = new Message(topic, msg.getBytes());
        try {
            mp.sendMessage(message);
        } catch (MetaClientException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    其中,topic必须是MetaQ服务器中定义的主题之一。

    在发送消息前,必须先mp.publish(topic),与指定主题关联。

     

消息消费端

  1. 引入crystal-metaq-consumer项目最为依赖:

    <dependency>
        <groupId>com.gsoft.crystal</groupId>
        <artifactId>crystal-metaq-consumer</artifactId>
    </dependency>
  2. 调用消息消费对象,注册监听器:

    @Resource
    private MessageConsumer mc;
     
    @Test
    public void testProducer() {
        String topic = "test";
         
        try {
            mc.subscribe(topic, 1024*1024, new MessageListener() {
                 
                @Override
                public void recieveMessages(Message message) throws InterruptedException {
                    String str = new String(message.getData());
                    System.out.println("Recived Message: " + str);
                    Assert.assertEquals(msg, str);
                }
                 
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            mc.completeSubscribe();
        } catch (MetaClientException e1) {
            e1.printStackTrace();
        }

    其中,mc.subscribe()方法可执行多次,最后需执行mc.completeSubscribe()方法。

    另,上述方法中的1024*1024参数为接收的消息内容最大字节数,可自行调整以优化性能(不了解具体如何优化情况下,建议不要调整)。

    监听器中的recieveMessages方法即为消息消费方法,getExecutor方法返回线程池的执行器,如返回null,则不采用线程池。

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-12/138427.htm

linux
相关资讯       Metaq  MetaQ消息收发机制 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款