订阅(publish-subscribe) demo

ReceiveTopic

package topic;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;


import javax.jms.Destination;
import javax.jms.MessageConsumer;

import javax.jms.Session;

import javax.jms.TextMessage;

 

import org.apache.activemq.ActiveMQConnection;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ReceiveTopic implements Runnable {

    private String threadName;



    ReceiveTopic(String threadName) {

         this.threadName = threadName;

    }



    public void run() {

         // ConnectionFactory:连接工厂,JMS用它创建连接

         ConnectionFactory connectionFactory;

         // Connection:JMS客户端到JMS Provider的连接

         Connection connection = null;

         // Session:一个发送或接收消息的线程

         Session session;

         // Destination:消息的目的地;消息发送给谁.

         Destination destination;

         //消费者,消息接收者

         MessageConsumer consumer;

         connectionFactory = new ActiveMQConnectionFactory(

                    ActiveMQConnection. DEFAULT_USER,

                    ActiveMQConnection. DEFAULT_PASSWORD,"tcp://localhost:61616");

         try {

               //构造从工厂得到连接对象

               connection = connectionFactory.createConnection();

               //启动

               connection.start();

               //获取操作连接,默认自动向服务器发送接收成功的响应

               session = connection.createSession( false, Session. AUTO_ACKNOWLEDGE);

               //获取session注意参数值FirstTopic是一个服务器的topic

               destination = session.createTopic("FirstTopic");

               consumer = session.createConsumer(destination);

               while ( true) {

                    //设置接收者接收消息的时间,为了便于测试,这里设定为100s

                    TextMessage message = (TextMessage) consumer

                                .receive(100 * 1000);

                    if ( null != message) {

                          System. out.println("线程"+threadName+"收到消息:" + message.getText());

                    } else {

                          continue;

                    }

               }

         } catch (Exception e) {

               e.printStackTrace();

         } finally {

               try {

                    if ( null != connection)

                          connection.close();

               } catch (Throwable ignore) {

               }

         }

    }



    public static void main(String[] args) {

          //这里启动3个线程来监听FirstTopic的消息,与queue的方式不一样三个线程都能收到同样的消息

         ReceiveTopic receive1= new ReceiveTopic("thread1");

         ReceiveTopic receive2= new ReceiveTopic("thread2");

         ReceiveTopic receive3= new ReceiveTopic("thread3");

         Thread thread1= new Thread(receive1);

         Thread thread2= new Thread(receive2);

         Thread thread3= new Thread(receive3);

         thread1.start();

         thread2.start();

         thread3.start();

    }

}


SendTopic

package topic;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.jms.DeliveryMode;

import javax.jms.Destination;

import javax.jms.MessageProducer;

import javax.jms.Session;

import javax.jms.TextMessage;

 

import org.apache.activemq.ActiveMQConnection;

import org.apache.activemq.ActiveMQConnectionFactory;

 

public class SendTopic {

    private static final int SEND_NUMBER = 5;

    public static void sendMessage(Session session, MessageProducer producer)

            throws Exception {

         for ( int i = 1; i <= SEND_NUMBER; i++) {

            TextMessage message = session

                    .createTextMessage("ActiveMq发送的消息" + i);

            //发送消息到目的地方

            System. out.println("发送消息:" + "ActiveMq 发送的消息" + i);

            producer.send(message);

        }

    }

   

    public static void main(String[] args) {

        // ConnectionFactory:连接工厂,JMS用它创建连接

        ConnectionFactory connectionFactory;

        // Connection:JMS客户端到JMS Provider的连接

        Connection connection = null;

        // Session:一个发送或接收消息的线程

        Session session;

        // Destination:消息的目的地;消息发送给谁.

        Destination destination;

        // MessageProducer:消息发送者

        MessageProducer producer;

        // TextMessage message;

        //构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar

        connectionFactory = new ActiveMQConnectionFactory(

                ActiveMQConnection. DEFAULT_USER,

                ActiveMQConnection. DEFAULT_PASSWORD,

                "tcp://localhost:61616");

        try {

            //构造从工厂得到连接对象

            connection = connectionFactory.createConnection();

            //启动

            connection.start();

            //获取操作连接

            session = connection.createSession( true, Session. AUTO_ACKNOWLEDGE);

            //获取session注意参数值FirstTopic是一个服务器的topic(与queue消息的发送相比,这里是唯一的不同)

            destination = session.createTopic("FirstTopic");

            //得到消息生成者【发送者】

            producer = session.createProducer(destination);

            //设置不持久化,此处学习,实际根据项目决定

            producer.setDeliveryMode(DeliveryMode. PERSISTENT);

            //构造消息,此处写死,项目就是参数,或者方法获取

            sendMessage(session, producer);

            session.commit();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                if ( null != connection)

                    connection.close();

            } catch (Throwable ignore) {

            }

        }

    }

}


所需包

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用sw::redis::RedisCluster实现异步订阅demo: ```c++ #include <iostream> #include <thread> #include <chrono> #include <sw/redis++/redis++.h> using namespace std::chrono_literals; int main() { try { // 创建 RedisCluster 对象,并设置连接信息 sw::redis::RedisCluster redis; redis.setMaxRedirects(16); redis.addNode("127.0.0.1", 7000); redis.addNode("127.0.0.1", 7001); redis.addNode("127.0.0.1", 7002); redis.addNode("127.0.0.1", 7003); redis.addNode("127.0.0.1", 7004); redis.addNode("127.0.0.1", 7005); // 创建 EventLoop 对象,用于异步处理事件 sw::redis::EventLoop event_loop; // 订阅消息,使用回调函数处理接收到的消息 auto callback = [](const std::string &channel, const std::string &msg) { std::cout << "Received message from channel " << channel << ": " << msg << std::endl; }; // 异步订阅消息 redis.subscribe("test_channel", callback, event_loop); // 在单独的线程中运行 EventLoop 对象,以便异步处理事件 std::thread thread([&](){ std::cout << "Starting event loop..." << std::endl; event_loop.run(); std::cout << "Event loop stopped." << std::endl; }); // 发送一些测试消息 for (int i = 0; i < 10; i++) { redis.publish("test_channel", "Test message " + std::to_string(i)); std::this_thread::sleep_for(1s); } // 关闭订阅 redis.unsubscribe("test_channel"); // 等待事件处理线程退出 thread.join(); } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << std::endl; return -1; } return 0; } ``` 在这个例子中,我们使用sw::redis::RedisCluster对象创建了一个连接到Redis集群的客户端,并使用EventLoop对象来实现异步订阅。我们首先传递回调函数来订阅一个名为"test_channel"的频道,然后在另一个线程中启动EventLoop对象的运行,并发送一些测试消息。最后,我们取消订阅并等待事件处理线程退出。 注意:为了保持本示例简单,我们只订阅了一个频道。如果你需要订阅多个频道或者订阅/取消订阅频道时处理更多的逻辑,请根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值