Redis订阅和发布 这个功能前面也有很多社友分享了,有个朋友问JF里面咋配合使用,就给了一个 Test类例子,这里分享一下~
http://www.jfinal.com/doc/8-3
新例子,提PR后的测试类:
https://gitee.com/jfinal/jfinal/pulls/53/files
//订阅 //Redis.use().subscribe(new JedisPubSub(){...}, "MyJedisPubSub"); //发布 //Redis.use().publish("MyJedisPubSub", "{...消息内容...}"); //例子代码如: package com.jfinal.plugin.redis; import com.jfinal.json.JsonManager; import com.jfinal.json.MixedJsonFactory; import com.jfinal.kit.JsonKit; import com.jfinal.kit.Kv; import com.jfinal.plugin.activerecord.DbKit; import org.junit.Test; import redis.clients.jedis.JedisPubSub; public class RedisTest { /** * 订阅消息 , 先运行 */ @Test public void subscribe() { JsonManager.me().setDefaultJsonFactory(new MixedJsonFactory()); RedisTest.startRedis(); Redis.use().subscribe(new JedisPubSub() { public void onMessage(String channel, String message) { System.out.println("channel=" + channel + " \t message=" + message); Kv kv = JsonKit.parse(message, Kv.class); System.out.println(kv.getStr("data") + kv.getInt("order")); } }, "RedisTest"); System.out.println("订阅后代码会阻塞监听发布的内容,这里打印不出来"); } /** * 发布消息 , 后运行 */ @Test public void publish() { RedisPlugin rp = RedisTest.startRedis(); for (int i = 0; i < 10000; i++) { String message = JsonKit.toJson(Kv.by("order", i) .set("data", "你好!")); Redis.use().publish("RedisTest", message); } System.out.println("完毕"); rp.stop(); } /** * 再执行模拟第二个订阅端,半路接受消息,然后再取消订阅 */ @Test public void subscribeThread() throws InterruptedException { JsonManager.me().setDefaultJsonFactory(new MixedJsonFactory()); RedisTest.startRedis(); JedisPubSub jedisPubSub = Redis.use().subscribeThread(new JedisPubSub() { public void onMessage(String channel, String message) { System.out.println("channel=" + channel + " \t message=" + message); Kv kv = JsonKit.parse(message, Kv.class); System.out.println(kv.getStr("data") + kv.getInt("order")); } }, "RedisTest"); Thread.sleep(3000); System.out.println("取消订阅"); jedisPubSub.unsubscribe(); //查看是否停止订阅打印 Thread.sleep(6000); System.out.println("订阅结束"); } public static RedisPlugin startRedis() { //临时测试服,方便调试试用,请勿测压 RedisPlugin rp = new RedisPlugin(DbKit.MAIN_CONFIG_NAME, "182.92.237.152", 6379, "111111"); rp.start(); return rp; } }
jar包在: https://jfinal.com/download?file=jfinal-4.9-all.zip
maven在:https://mvnrepository.com/artifact/redis.clients/jedis
安装:
https://www.runoob.com/redis/redis-pub-sub.html
如果觉得棒!就点个赞哈2333