1.代码实例
有关Redis发布订阅功能更详细的内容,请参考我的这篇博文:https://blog.csdn.net/weixin_43823808/article/details/113833905
下面直接放上具体的实现代码:👇👇👇
package MyRedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; public class JedisUtil { /** * 该方法用于发布消息,这里指定两个参数的意思是:向某个频道发布某些消息 * 使用静态方法,方便调用 * @param channel * @param message */ public static void publishMessage(String channel,String message) { Jedis jedis=new Jedis("127.0.0.1",6379); try { jedis.publish(channel,message); }catch (Exception e) { System.out.println(e.getMessage()); }finally { jedis.close(); } } /** * 该方法用于接受消息,调用之后,会一直执行下去 * 当有发布对应消息时,会在jedisPubSub中接收到!!! * @param channel */ public static void subscribeMessage(String channel) { Jedis jedis=new Jedis("127.0.0.1",6379); new Thread(()->{ try { jedis.subscribe(jedisPubSub,channel); }catch (Exception e) { System.out.println(e.getMessage()); }finally { jedis.close(); } }).start(); } /** * 这里使用内部类JedisPubSub * 对 接收消息、订阅频道、取消订阅频道 三个方法进行重写 */ public static JedisPubSub jedisPubSub=new JedisPubSub() { @Override public void onMessage(String channel, String message) { System.out.println("此时收到了" + channel + "频道发来的消息:" + message); System.out.println(channel + ":" + message); } @Override public void onSubscribe(String channel, int subscribedChannels) { System.out.println("此时订阅了" + channel + "频道"); System.out.println(channel + ":" + subscribedChannels); } @Override public void onUnsubscribe(String channel, int subscribedChannels) { System.out.println("此时取消订阅了" + channel + "频道"); System.out.println(channel + ":" + subscribedChannels); } }; }
package MyRedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; public class Main { public static void main(String[] args) { Jedis jedis=new Jedis("127.0.0.1",6379); System.out.println(jedis.ping() + ":此时与Redis成功连接!!!"); //订阅WeChat频道 JedisUtil.subscribeMessage("WeChat"); /* 这里肯定是先订阅频道,之后才可以向该频道发布消息,也即发布在订阅之后 所以这里调用Thread类的sleep()方法先睡眠200ms,之后再进行发布 */ try { Thread.sleep(200); }catch (InterruptedException e) { e.printStackTrace(); }finally { // } JedisUtil.publishMessage("WeChat","Hello Redis!!!"); JedisUtil.publishMessage("WeChat","Java and Redis!!!"); } }