您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在Java中實現redis發布訂閱,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
一、訂閱消息(InitListener實現)
redis支持多通道訂閱,一個客戶端可以同時訂閱多個消息通道,如下代碼所示,訂閱了13個通道。由于訂閱機制是線程阻塞的,需要額外開啟一個線程專門用于處理訂閱消息及接收消息處理。
public class InitListener implements ServletContextListener{ private Logger logger = Logger.getLogger(InitListener.class); @Override public void contextInitialized(ServletContextEvent sce) { logger.info("啟動tomcat");// 連接redis Map<String, String> 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配置文件里接入以下配置:
<!-- redis --> <bean id="redisMessageService" class="com.test.service.impl.RedisMessageServiceImpl" scope="singleton"> <property name="webSocketService"><ref local="webSocketService" /></property> <property name="tvSplitStatusDao" ref="tvSplitStatusDao"></property> </bean> <bean id="redisSubListener" class="com.test.common.RedisSubListener" scope="singleton"> <property name="redisMessageService"><ref local="redisMessageService" /></property> </bean>
RedisMessageServiceImpl用于處理接收的redis消息。
二、發布消息
public class RedisPublishUtil { private Logger logger = Logger.getLogger(RedisPublishUtil.class); public static Jedis pubJedis; private static Map<String, String> 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<String,String> getProperties(){ logger.info("讀取redis配置文件開始。。。"); Properties prop = new Properties(); Map<String,String> proMap = new HashMap<String,String>(); try { //讀取屬性文件redis.properties InputStream in= PropertyReader.class.getClassLoader().getResourceAsStream("redis.properties"); prop.load(in); ///加載屬性列表 Iterator<String> 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; } }
上述內容就是怎么在Java中實現redis發布訂閱,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。