1、对于异步消息组件在实际的应用之中会有俩类
AMQP:高级消息队列,直接利用协议实现
广谱代表作是RabbitMQ
高性能代表作kafak
2、想要在项目中使用activeMQ组件,则应该为项目添加依赖支持库
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
3、修改application.yml文件进行activemq的配置
spring:
jms:
pub-sub-domain: false #配置消息类型,如果是true则表示topic消息,如果为false表示Queue消息
activemq:
user: hhj #连接用户名
password: hello #连接密码
broker-url: tcp://activemq-server:61616 #host文件中已经配置了服务器ip映射
4、定义一个消息的消费者,主要是进行一个监听机制,在SpringBoot中可以直接利用注解进行监听
@Service
public class MessageConsumerService {
@JmsListener(destination="hhj.msg.queue")
public void receiveMessage(String text) {//进行消息的接受处理
System.err.println("【*****接受消息********】"+text);
}
}
5、定义一个发送消息的接口
public interface IMessageProducerService {
public void sendMessage(String msg);
}
6、建立一个配置程序类,定义ActiveMQ的消息发送模板处理类
@Configuration
@EnableJms
public class ActiveMQConfig {
@Bean
public Queue queue() {
return new ActiveMQQueue("hhj.msg.queue");
}
}
7、创建消息发送子类
@Service
public class MessageProduceerServiceImpl implements IMessageProducerService {
@Resource
private JmsMessagingTemplate jmsMessagingTemplate;
@Resource
private Queue queue;
@Override
public void sendMessage(String msg) {
this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
}
}
8、编写测试类,进行消息的监听处理
@SpringBootTest(classes=StartSpringBootMain.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestActiveMQ {
@Resource
private IMessageProducerService messageProducerService;
@Test
public void testSend() {
for(int x=0;x<100;x++) {
this.messageProducerService.sendMessage("hhj-"+x);
}
}
}
-------------------------------------------------------------------------------------------------by:青涩知夏 -》》 www.nosum.cn