Activemq 的topic总结

来源:互联网 发布:炸群软件 编辑:程序博客网 时间:2024/06/05 06:44

一,activemq 使用队列:

  • spring-boot集成ActiveMQ

简单的队列和 JmsMessagingTemplate

可以参考这个:http://blog.csdn.net/zhangjq520/article/details/53927573

二,使用activemq的topic:

  • 首先需要依赖:
   <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-activemq</artifactId>    </dependency>
  • 其次 在 application.properties中做如下的配置:
spring.activemq.broker-url=tcp://10.10.10.48:61616spring.activemq.user=adminspring.activemq.password=adminspring.activemq.in-memory=truespring.activemq.pool.enabled=falsespring.jms.pub-sub-domain=true
  • 其次在生产者端:
@Service("producer")public class ProducerServer {    @Autowired    private JmsMessagingTemplate jmsMessagingTemplate;    public void sendMessage(Destination destination, final String message, Map<String, Object> map) throws MessagingException {        jmsMessagingTemplate.convertAndSend(destination, message, map);    }}
  • 最后在消费者端:
    @JmsListener(destination = "AppAndSceneChangeTopic")    public void onMessage(Message message) {        if (message instanceof TextMessage) {            try {                String groupID = message.getStringProperty("JMSXGroupID");                if ("AdParamChanged".equalsIgnoreCase(groupID)) {                    String text = ((TextMessage) message).getText();                    System.out.println(text);                }            } catch (JMSException e) {                e.printStackTrace();            }        }    }

ps:

spring.jms.pub-sub-domain=true 如果为True,则是Topic;如果是false或者默认,则是queue

  • 消费者端的配置文件:
@Configurationpublic class ActiveConfig {    @Value("${spring.activemq.broker-url}")    private String brokerUrl;    @Value("${spring.activemq.user}")    private String user;    @Value("${spring.activemq.password}")    private String password;    @Bean    public JmsListenerContainerFactory<?> myFactory(DefaultJmsListenerContainerFactoryConfigurer configurer) {        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();        configurer.configure(factory, connectionFactory());        return factory;    }    @Bean    public ConnectionFactory connectionFactory() {        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(user, password, brokerUrl);        activeMQConnectionFactory.setTrustAllPackages(true);        activeMQConnectionFactory.setUseAsyncSend(true);        activeMQConnectionFactory.setAlwaysSessionAsync(true);        activeMQConnectionFactory.setUseDedicatedTaskRunner(true);        activeMQConnectionFactory.setSendAcksAsync(true);        return activeMQConnectionFactory;    }}

三,第二种方式:

  • 首先需要依赖:
   <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-activemq</artifactId>    </dependency>
  • 首先在 application.properties中做如下的配置:
spring.activemq.broker-url=tcp://10.10.10.48:61616spring.activemq.user=adminspring.activemq.password=adminspring.activemq.in-memory=truespring.activemq.pool.enabled=falsespring.jms.pub-sub-domain=true

ii,其次在生产者端:

Destination destinationTopic = new ActiveMQTopic("AppAndSceneChangeTopic");Map<String, Object> map = new HashMap<>();map.put("JMSXGroupID", "AdParamChanged");String message="test";因为: sendMessage() 中的参数分别为:上面的  destinationTopic, message, map,即对topic做了分组.   @Service("producer")public class ProducerServer {    @Autowired    private JmsMessagingTemplate jmsMessagingTemplate;    public void sendMessage(Destination destination, final String message, Map<String, Object> map) throws MessagingException {        jmsMessagingTemplate.convertAndSend(destination, message, map);    }}
  • 消费者也是可以这么配置的:
因为生产者对topic做了分组.所以消费者在接收的时候不仅需要创建相同名称的topic,而且需要做如下的逻辑判断:String groupID = message.getStringProperty("JMSXGroupID");                            if ("AdParamChanged".equalsIgnoreCase(groupID)) {                                String text = ((TextMessage) message).getText();                                System.out.println(text);                            }@Componentpublic class SubscriberOpenWire {    private static final String BROKER_URL = "tcp://10.10.10.48:61616";    private static String userName = "admin";    private static String passWord = "admin";    private static final Boolean TRANSACTED = true;    private static final long TIMEOUT = 20000000;    @Scheduled(cron = "*/59 * * * * ?")    private void process() {        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, passWord, BROKER_URL);        Connection connection = null;        StringBuffer stringBuffer = new StringBuffer();        try {            connectionFactory.setTrustAllPackages(true);            connection = connectionFactory.createConnection();            connection.setClientID("ClientID");            connection.start();            final Session session = connection.createSession(!TRANSACTED, Session.AUTO_ACKNOWLEDGE);            Destination destination = session.createTopic("AppAndSceneChangeTopic");            MessageConsumer consumer = session.createConsumer(destination);            while (true) {                consumer.setMessageListener(new MessageListener() {                    @Override                    public void onMessage(Message message) {                        if (message instanceof TextMessage) {                            try {                                String groupID = message.getStringProperty("JMSXGroupID");                                if ("AdParamChanged".equalsIgnoreCase(groupID)) {                                    String text = ((TextMessage) message).getText();                                    System.out.println(text);                                }                            } catch (JMSException e) {                                e.printStackTrace();                            }                        }                    }                });            }        } catch (Exception e) {            System.out.println("Caught exception!");        } finally {            if (connection != null) {                try {                    connection.close();                } catch (JMSException e) {                    System.out.println("Could not close an open connection...");                }            }        }    }}
  • 消费者端的配置文件:
@Configurationpublic class ActiveConfig {    @Value("${spring.activemq.broker-url}")    private String brokerUrl;    @Value("${spring.activemq.user}")    private String user;    @Value("${spring.activemq.password}")    private String password;    @Bean    public JmsListenerContainerFactory<?> myFactory(DefaultJmsListenerContainerFactoryConfigurer configurer) {        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();        configurer.configure(factory, connectionFactory());        return factory;    }    @Bean    public ConnectionFactory connectionFactory() {        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(user, password, brokerUrl);        activeMQConnectionFactory.setTrustAllPackages(true);        activeMQConnectionFactory.setUseAsyncSend(true);        activeMQConnectionFactory.setAlwaysSessionAsync(true);        activeMQConnectionFactory.setUseDedicatedTaskRunner(true);        activeMQConnectionFactory.setSendAcksAsync(true);        return activeMQConnectionFactory;    }}
原创粉丝点击