2019-09-17 14:09:54 4742瀏覽
今天千鋒扣丁學(xué)堂Java培訓(xùn)老師給大家分享一篇關(guān)于redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析的詳細(xì)介紹,首先Redis除了可以用作緩存數(shù)據(jù)外,另一個(gè)重要用途是它實(shí)現(xiàn)了發(fā)布訂閱(pub/sub)消息通信模式:發(fā)送者(pub)發(fā)送消息,訂閱者(sub)接收消息。<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency>
<listener> <listener-class>com.test.listener.InitListener</listener-class> </listener>
public class InitListener implements ServletContextListener{ private Logger logger = Logger.getLogger(InitListener.class); @Override public void contextInitialized(ServletContextEvent sce) { logger.info("啟動(dòng)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啟動(dòng),開(kāi)啟線程執(zhí)行 new Thread(new Runnable(){ public void run(){ // 連接redis,建立監(jiān)聽(tīng) Jedis jedis = null; while(true){ //解碼資源更新通知,畫(huà)面選看回復(fù),畫(huà)面選看停止回復(fù),預(yù)案啟動(dòng),預(yù)案停止,輪切啟動(dòng),輪切停止,預(yù)案啟動(dòng)回復(fù),預(yù)案停止回復(fù),輪切啟動(dòng)回復(fù),輪切停止回復(fù),監(jiān)視屏分屏狀態(tài)通知,畫(huà)面狀態(tài)通知 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請(qǐng)求訂閱通道"); jedis.subscribe(redisSubListener,channels); logger.info("redis訂閱結(jié)束"); }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(); }
<!-- 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>
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(); } // 返回對(duì)象 return pubJedis; } public Jedis createJedisConnect(){ // 連接redis logger.info("===創(chuàng)建連接jedis====="); try { pubJedis = new Jedis(url, port); } catch (JedisConnectionException e) { logger.error("Jedis連接異常,異常信息 :" + e.getMessage()); try { Thread.sleep(1000); logger.info("發(fā)起重新連接jedis"); createJedisConnect(); } catch (InterruptedException except) { except.printStackTrace(); } } // 返回對(duì)象 return pubJedis; } //公共發(fā)布接口 public void pubRedisMsg(String msgType,String msg){ logger.info("redis準(zhǔn)備發(fā)布消息內(nèi)容:" + msg); try { this.getPubJedis().publish(msgType, msg); } catch (JedisConnectionException e) { logger.error("redis發(fā)布消息失敗!", e); this.setPubJedis(null); logger.info("重新發(fā)布消息,channel="+msgType); pubRedisMsg(msgType, msg); } } }
public class PropertyReader { private static Logger logger = Logger.getLogger(PropertyReader.class); /* * 獲得數(shù)據(jù)庫(kù)鏈接的配置文件 */ public static Map<String,String> getProperties(){ logger.info("讀取redis配置文件開(kāi)始。。。"); 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; } }
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入JavaEE/微服務(wù)VIP免費(fèi)公開(kāi)課】
查看更多關(guān)于“Java開(kāi)發(fā)資訊”的相關(guān)文章>>