经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
redis发布订阅Java代码实现过程解析
来源:jb51  时间:2019/9/17 12:57:48  对本文有异议

前言

Redis除了可以用作缓存数据外,另一个重要用途是它实现了发布订阅(pub/sub)消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

为了实现redis的发布订阅机制,首先要打开redis服务;其次,引入redis需要的jar包,在pom.xml配置文件加入以下代码:

  1. <dependency>
  2. <groupId>redis.clients</groupId>
  3. <artifactId>jedis</artifactId>
  4. <version>2.1.0</version>
  5. </dependency>

由于订阅消息通道需要再tomcat启动时触发,因此,需要创建一个listener监听器,在监听器里实现redis订阅,在web.xml里配置监听器如下:

  1. <listener>
  2. <listener-class>com.test.listener.InitListener</listener-class>
  3. </listener>

一、订阅消息(InitListener实现)

redis支持多通道订阅,一个客户端可以同时订阅多个消息通道,如下代码所示,订阅了13个通道。由于订阅机制是线程阻塞的,需要额外开启一个线程专门用于处理订阅消息及接收消息处理。

  1. public class InitListener implements ServletContextListener{
  2. private Logger logger = Logger.getLogger(InitListener.class);
  3. @Override
  4. public void contextInitialized(ServletContextEvent sce) {
  5. logger.info("启动tomcat");// 连接redis
  6. Map<String, String> proMap = PropertyReader.getProperties();
  7. final String url = proMap.get("redis.host");
  8. final Integer port = Integer.parseInt(proMap.get("redis.port"));
  9. final ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
  10. final RedisSubListener redisSubListener = (RedisSubListener) classPathXmlApplicationContext.getBean("redisSubListener");
  11. // 为防止阻塞tomcat启动,开启线程执行
  12. new Thread(new Runnable(){
  13. public void run(){
  14. // 连接redis,建立监听
  15. Jedis jedis = null;
  16. while(true){
  17. //解码资源更新通知,画面选看回复,画面选看停止回复,预案启动,预案停止,轮切启动,轮切停止,预案启动回复,预案停止回复,轮切启动回复,轮切停止回复,监视屏分屏状态通知,画面状态通知
  18. String[] channels = new String[] { "decodeResourceUpdateNtf", "tvSplitPlayRsp","tvSplitPlayStopRsp",
  19. "planStartStatusNtf", "planStopStatusNtf", "pollStartStatusNtf", "pollStopStatusNtf",
  20. "planStartRsp","planStopRsp","pollStartRsp","pollStopRsp","tvSplitTypeNtf","tvSplitStatusNtf"};
  21. try{
  22. jedis = new Jedis(url,port);
  23. logger.info("redis请求订阅通道");
  24. jedis.subscribe(redisSubListener,channels);
  25. logger.info("redis订阅结束");
  26. }catch(JedisConnectionException e){
  27. logger.error("Jedis连接异常,异常信息 :" + e);
  28. }catch(IllegalStateException e){
  29. logger.error("Jedis异常,异常信息 :" + e);
  30. }
  31. try {
  32. Thread.sleep(1000);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. if(jedis != null){
  37. jedis = null;
  38. }
  39. }
  40. }})
  41. .start();
  42. }

最后在spring配置文件里接入以下配置:

  1. <!-- redis -->
  2. <bean id="redisMessageService" class="com.test.service.impl.RedisMessageServiceImpl" scope="singleton">
  3. <property name="webSocketService"><ref local="webSocketService" /></property>
  4. <property name="tvSplitStatusDao" ref="tvSplitStatusDao"></property>
  5. </bean>
  6. <bean id="redisSubListener" class="com.test.common.RedisSubListener" scope="singleton">
  7. <property name="redisMessageService"><ref local="redisMessageService" /></property>
  8. </bean>

RedisMessageServiceImpl用于处理接收的redis消息。

二、发布消息

  1. public class RedisPublishUtil {
  2. private Logger logger = Logger.getLogger(RedisPublishUtil.class);
  3. public static Jedis pubJedis;
  4. private static Map<String, String> proMap = PropertyReader.getProperties();
  5. private static final String redisPort = proMap.get("redis.port");
  6. private static String url = proMap.get("redis.host");
  7. private static final int port = Integer.parseInt(redisPort);
  8. public void setPubJedis(Jedis jedis) {
  9. RedisPublishUtil.pubJedis = jedis;
  10. }
  11. public Jedis getPubJedis() {
  12. if (pubJedis == null) {
  13. createJedisConnect();
  14. }
  15. // 返回对象
  16. return pubJedis;
  17. }
  18. public Jedis createJedisConnect(){
  19. // 连接redis
  20. logger.info("===创建连接jedis=====");
  21. try {
  22. pubJedis = new Jedis(url, port);
  23. } catch (JedisConnectionException e) {
  24. logger.error("Jedis连接异常,异常信息 :" + e.getMessage());
  25. try {
  26. Thread.sleep(1000);
  27. logger.info("发起重新连接jedis");
  28. createJedisConnect();
  29. } catch (InterruptedException except) {
  30. except.printStackTrace();
  31. }
  32. }
  33. // 返回对象
  34. return pubJedis;
  35. }
  36. //公共发布接口
  37. public void pubRedisMsg(String msgType,String msg){
  38. logger.info("redis准备发布消息内容:" + msg);
  39. try {
  40. this.getPubJedis().publish(msgType, msg);
  41.  
  42. } catch (JedisConnectionException e) {
  43. logger.error("redis发布消息失败!", e);
  44. this.setPubJedis(null);
  45. logger.info("重新发布消息,channel="+msgType);
  46. pubRedisMsg(msgType, msg);
  47. }
  48. }
  49. }
  1. public class PropertyReader {
  2.  
  3. private static Logger logger = Logger.getLogger(PropertyReader.class);
  4. /*
  5. * 获得数据库链接的配置文件
  6. */
  7. public static Map<String,String> getProperties(){
  8. logger.info("读取redis配置文件开始。。。");
  9. Properties prop = new Properties();
  10. Map<String,String> proMap = new HashMap<String,String>();
  11. try {
  12. //读取属性文件redis.properties
  13. InputStream in= PropertyReader.class.getClassLoader().getResourceAsStream("redis.properties");
  14. prop.load(in); ///加载属性列表
  15. Iterator<String> it=prop.stringPropertyNames().iterator();
  16. while(it.hasNext()){
  17. String key=it.next();
  18. proMap.put(key, prop.getProperty(key));
  19. }
  20. in.close();
  21. logger.info("读取redis配置文件成功。。。");
  22. } catch (Exception e) {
  23. logger.error("读取redis配置文件异常!", e);
  24. e.printStackTrace();
  25. }
  26. return proMap;
  27. }
  28. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号