当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot利用redis集成消息队列的方法

SpringBoot利用redis集成消息队列的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

死神574,居家养老带薪护理,电光石火boys

一、pom文件依赖

<dependency> 
   <groupid>org.springframework.boot</groupid> 
   <artifactid>spring-boot-starter-data-redis</artifactid> 
</dependency>

二、创建消息接收者

变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @autowired的使用来消除 set ,get方法。

@autowired public receiver(countdownlatch latch) { 
this.latch = latch; 
} 
public void receivemessage(string message) { 
logger.info("收到的消息: <" + message + ">"); latch.countdown(); } }

以上基本条件达成后,以下是实现的三要素:

一个连接工厂

一个消息监听容器

redis template

三、在application.java注入消息接收者

@bean receiver receiver(countdownlatch latch) { 
return new receiver(latch); } 
@bean countdownlatch latch() { 
return new countdownlatch(1); } 
@bean stringredistemplate template(redisconnectionfactory connectionfactory) { 
return new stringredistemplate(connectionfactory); }

四、注入消息监听容器

//必要的redis消息队列连接工厂
@bean
receiver receiver(countdownlatch latch) {
return new receiver(latch);
}
//必要的redis消息队列连接工厂
@bean
countdownlatch latch() {
return new countdownlatch(1);
}
//redis模板
@bean
stringredistemplate template(redisconnectionfactory connectionfactory) {
return new stringredistemplate(connectionfactory);
}
//注入消息监听器容器
@bean
redismessagelistenercontainer container(redisconnectionfactory connectionfactory,messagelisteneradapter listeneradapter) {
redismessagelistenercontainer container = new redismessagelistenercontainer();
container.setconnectionfactory(connectionfactory);
container.addmessagelistener(listeneradapter, new patterntopic("msg"));
return container;
}
//注入消息监听器容器
@bean
messagelisteneradapter listeneradapter(receiver receiver) {
return new messagelisteneradapter(receiver, "receivemessage");
}

五、单元测试

import java.util.concurrent.countdownlatch;
import org.junit.test;
import org.junit.runner.runwith;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.context.applicationcontext;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.test.context.junit4.springrunner;
import com.application;
@runwith(springrunner.class)
@springboottest(classes = application.class)
public class msgqueuetest {
@autowired
protected applicationcontext ctx;
private static final logger logger = loggerfactory.getlogger(msgqueuetest.class);
@test
public void sendmsg() {
stringredistemplate template = ctx.getbean(stringredistemplate.class);
countdownlatch latch = ctx.getbean(countdownlatch.class);
logger.info("我要发送消息咯...");
template.convertandsend("msg", "欢迎使用redis的消息队列!");
try {
//发送消息连接等待中
logger.info("消息正在发送...");
latch.await();
} catch (interruptedexception e) {
logger.info("消息发送失败...");
}
}
}

总结

以上所述是小编给大家介绍的springboot利用redis集成消息队列的方法,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网