Redis发布订阅Java实现概述
前言
Redis除了作为高性能缓存工具外,其内置的发布/订阅(pub/sub)消息通信模式也是核心功能之一。在该模式下,发布者(pub)负责发送消息,而订阅者(sub)则接收并处理这些消息,从而实现组件间的解耦与实时通信。
要在Java应用中启用Redis的发布订阅功能,首先需确保Redis服务处于运行状态。其次,需在项目中引入必要的Redis客户端依赖。具体而言,应在项目的pom.xml配置文件中添加以下依赖代码:
redis.clients
jedis
2.1.0
由于订阅任务需要在Web容器启动阶段自动触发,因此需要创建一个Servlet监听器(Listener)。在该监听器的初始化方法中实现Redis订阅逻辑,并在web.xml文件中注册此监听器,配置如下:
com.test.listener.InitListener
一、订阅消息(InitListener实现)
Redis支持多通道订阅,单个客户端可同时监听多个消息通道。如代码所示,示例中订阅了13个通道。鉴于Redis订阅机制是线程阻塞式的,必须额外开启一个独立线程来专门处理订阅连接及消息接收,以避免阻塞主业务线程。
public class InitListener implements ServletContextListener{
private Logger logger = Logger.getLogger(InitListener.class);
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("启动tomcat");// 连接redis
Map proMap = PropertyReader.getProperties();
final String url = proMap.get("redis.host");
final Integer port = Integer.parseInt(proMap.get("redis.port"));
final ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
final RedisSubListener redisSubListener = (RedisSubListener) classPathXmlApplicationContext.getBean("redisSubListener");
// 为防止阻塞tomcat启动,开启线程执行
new Thread(new Runnable(){
public void run(){
// 连接redis,建立监听
Jedis jedis = null;
while(true){
//解码资源更新通知,画面选看回复,画面选看停止回复,预案启动,预案停止,轮切启动,轮切停止,预案启动回复,预案停止回复,轮切启动回复,轮切停止回复,监视屏分屏状态通知,画面状态通知
String[] channels = new String[] { "decodeResourceUpdateNtf", "tvSplitPlayRsp","tvSplitPlayStopRsp",
"planStartStatusNtf", "planStopStatusNtf", "pollStartStatusNtf", "pollStopStatusNtf",
"planStartRsp","planStopRsp","pollStartRsp","pollStopRsp","tvSplitTypeNtf","tvSplitStatusNtf"};
try{
jedis = new Jedis(url,port);
logger.info("redis请求订阅通道");
jedis.subscribe(redisSubListener,channels);
logger.info("redis订阅结束");
}catch(JedisConnectionException e){
logger.error("Jedis连接异常,异常信息 :" + e);
}catch(IllegalStateException e){
logger.error("Jedis异常,异常信息 :" + e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(jedis != null){
jedis = null;
}
}
}})
.start();
}
最后,在Spring配置文件中接入相关Bean定义,以确保订阅服务能正确注入到Spring容器中管理:
其中,RedisMessageServiceImpl类负责具体的业务逻辑,用于处理从Redis接收到的消息内容。
二、发布消息
public class RedisPublishUtil {
private Logger logger = Logger.getLogger(RedisPublishUtil.class);
public static Jedis pubJedis;
private static Map proMap = PropertyReader.getProperties();
private static final String redisPort = proMap.get("redis.port");
private static String url = proMap.get("redis.host");
private static final int port = Integer.parseInt(redisPort);
public void setPubJedis(Jedis jedis) {
RedisPublishUtil.pubJedis = jedis;
}
public Jedis getPubJedis() {
if (pubJedis == null) {
createJedisConnect();
}
// 返回对象
return pubJedis;
}
public Jedis createJedisConnect(){
// 连接redis
logger.info("===创建连接jedis=====");
try {
pubJedis = new Jedis(url, port);
} catch (JedisConnectionException e) {
logger.error("Jedis连接异常,异常信息 :" + e.getMessage());
try {
Thread.sleep(1000);
logger.info("发起重新连接jedis");
createJedisConnect();
} catch (InterruptedException except) {
except.printStackTrace();
}
}
// 返回对象
return pubJedis;
}
//公共发布接口
public void pubRedisMsg(String msgType,String msg){
logger.info("redis准备发布消息内容:" + msg);
try {
this.getPubJedis().publish(msgType, msg);
} catch (JedisConnectionException e) {
logger.error("redis发布消息失败!", e);
this.setPubJedis(null);
logger.info("重新发布消息,channel="+msgType);
pubRedisMsg(msgType, msg);
}
}
}
public class PropertyReader {
private static Logger logger = Logger.getLogger(PropertyReader.class);
/*
* 获得数据库链接的配置文件
*/
public static Map getProperties(){
logger.info("读取redis配置文件开始。。。");
Properties prop = new Properties();
Map proMap = new HashMap();
try {
//读取属性文件redis.properties
InputStream in= PropertyReader.class.getClassLoader().getResourceAsStream("redis.properties");
prop.load(in); ///加载属性列表
Iterator it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
proMap.put(key, prop.getProperty(key));
}
in.close();
logger.info("读取redis配置文件成功。。。");
} catch (Exception e) {
logger.error("读取redis配置文件异常!", e);
e.printStackTrace();
}
return proMap;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。