activityMq初步使用

前言

activityMq的作用以及安装这里不做讲述,只是记录一下简单的使用。springboot+mq

依赖

<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-activemqartifactId>
		dependency>

application.properties配置文件

#activemq配置
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.pool.enabled=true
spring.activemq.broker-url=tcp://39.108.187.144:61616
spring.activemq.pool.max-connections=10

发送消息bean

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.jms.Destination;

/**
 * @author: xieyong
 * @date: 2019/2/15 14:40
 * @Description:
 */
@Service
public class Publisher {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    public void publish(String dname, String message){
        Destination destination = new ActiveMQTopic(dname);
        jmsMessagingTemplate.convertAndSend(destination, message);
    }
}

使用

@Service
@Slf4j
public class TestActivityMqService {
    @Autowired
    Publisher publisher;


    public String testAdd() {
        int result = add();
        //发布者订阅者模式
        publisher.publish("sendEmail2", "发送邮件");
        publisher.publish("sendNote2", "发送短信");
        return result > 0 ? "success" : "failed";
    }

    @JmsListener(destination = "sendEmail2", containerFactory = "myfactory")
    public void sendEmail(String text) {
        System.out.println(text);
    }

    @JmsListener(destination = "sendNote2", containerFactory = "myfactory")
    public void sendNote(String text) {
        System.out.println(text);
    }

    @Bean
    JmsListenerContainerFactory<?> myfactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true);
        return factory;
    }

    private int add() {
        //TODO 写一些逻辑方法
        log.info("添加方法");
        return 1;
    }

效果图:调用testAdd方法

你可能感兴趣的:(java,工作记录,springboot,acticitymq,消息队列)