本文共 2704 字,大约阅读时间需要 9 分钟。
1.1 - 自行下载jedis jar包.
用maven的话redis.clients jedis 2.9.0 jar compile
1.2 - 打开 redis 服务器待命.
1/3.
先打开 SUB端:package example.me.PubSub;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPubSub;public class MySub { public static void main(String[] args) { final String host = "127.0.0.1";// Redis服务所在地址 final int port = 6379; // 主机端口 @SuppressWarnings("resource") Jedis subJedis = new Jedis(host, port); JedisPubSub jedissubSub = new JedisPubSub() { public void onUnsubscribe(String channel, int num) { } public void onSubscribe(String channel, int num) { } public void onMessage(String channel, String msg) { System.out.println(channel + " : " + msg); } public void onPUnsubscribe(String channel, int num) { } /* * num 订阅数量 */ public void onPSubscribe(String channel, int num) { } /* * channel0订阅的channel正则表达式 * channel 匹配上该正则channel值 * msg 收到的消息 */ public void onPMessage(String channel0, String channel, String msg) { } }; /* * 启动订阅,当该方法启动时,将阻塞等待消息 * 说明: * 1.subscribe(JedisPubSub jedisPubSub, String... channels) * 是常规订阅方法,channel值基于完全匹配,方法中channels是多个要订阅的channel值 * 2.psubscribe(JedisPubSub jedisPubSub, String... patterns) * 是正则订阅方法,channel值基于正则匹配,方法中的patterns是多个订阅到正则表达式 * 不同的订阅将会触发JedisPubSub中不同的方法 */ subJedis.subscribe(jedissubSub, "news", "tvshow");//完全匹配 }}
2/3.
PUB端:package example.me.PubSub;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class MyPub { public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(5); poolConfig.setMinIdle(1); poolConfig.setMaxWaitMillis(30000); JedisPool jedisPool = new JedisPool(poolConfig,"localhost", 6379, 100); Jedis pubJedis = jedisPool.getResource(); try{ pubJedis.publish("news", "Hello,MySubs~ ");//发送广播 }catch(Exception e){ e.printStackTrace(); }finally{ jedisPool.returnResource(pubJedis); jedisPool.close(); } }}
3/3.
同时我们在 redis-cli 端也订阅相同channel:jedis-SUB端:
redis-cli端:
4.1 - 本篇仅作为基础,还有很多功能未展现.
4.2 - 已有很多十分优秀的开源项目供参考.参考资料:
本文原文地址: 小可不才,恭听指正.