SpringBoot利用redis集成消息队列的方法
一、pom文件依赖
org.springframework.boot spring-boot-starter-data-redis
二、创建消息接收者
变量、方法及构造函数进行标注,完成自动装配的工作。通过@Autowired的使用来消除set,get方法。
@AutowiredpublicReceiver(CountDownLatchlatch){
this.latch=latch;
}
publicvoidreceiveMessage(Stringmessage){
LOGGER.info("收到的消息:<"+message+">");latch.countDown();}}
以上基本条件达成后,以下是实现的三要素:
一个连接工厂
一个消息监听容器
Redistemplate
三、在application.java注入消息接收者
@BeanReceiverreceiver(CountDownLatchlatch){
returnnewReceiver(latch);}
@BeanCountDownLatchlatch(){
returnnewCountDownLatch(1);}
@BeanStringRedisTemplatetemplate(RedisConnectionFactoryconnectionFactory){
returnnewStringRedisTemplate(connectionFactory);}
四、注入消息监听容器
//必要的redis消息队列连接工厂
@Bean
Receiverreceiver(CountDownLatchlatch){
returnnewReceiver(latch);
}
//必要的redis消息队列连接工厂
@Bean
CountDownLatchlatch(){
returnnewCountDownLatch(1);
}
//redis模板
@Bean
StringRedisTemplatetemplate(RedisConnectionFactoryconnectionFactory){
returnnewStringRedisTemplate(connectionFactory);
}
//注入消息监听器容器
@Bean
RedisMessageListenerContainercontainer(RedisConnectionFactoryconnectionFactory,MessageListenerAdapterlistenerAdapter){
RedisMessageListenerContainercontainer=newRedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter,newPatternTopic("msg"));
returncontainer;
}
//注入消息监听器容器
@Bean
MessageListenerAdapterlistenerAdapter(Receiverreceiver){
returnnewMessageListenerAdapter(receiver,"receiveMessage");
}
五、单元测试
importjava.util.concurrent.CountDownLatch;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.context.ApplicationContext;
importorg.springframework.data.redis.core.StringRedisTemplate;
importorg.springframework.test.context.junit4.SpringRunner;
importcom.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
publicclassMsgQueueTest{
@Autowired
protectedApplicationContextctx;
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MsgQueueTest.class);
@Test
publicvoidSendMsg(){
StringRedisTemplatetemplate=ctx.getBean(StringRedisTemplate.class);
CountDownLatchlatch=ctx.getBean(CountDownLatch.class);
logger.info("我要发送消息咯...");
template.convertAndSend("msg","欢迎使用redis的消息队列!");
try{
//发送消息连接等待中
logger.info("消息正在发送...");
latch.await();
}catch(InterruptedExceptione){
logger.info("消息发送失败...");
}
}
}
总结
以上所述是小编给大家介绍的SpringBoot利用redis集成消息队列的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。