Redis发布订阅模式实现
程序员文章站
2022-03-05 09:55:11
...
RedisUtil工具类
public class RedisUtil {
private static JedisCluster jedisCluster;
static {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200);
jedisPoolConfig.setMaxIdle(20);
jedisPoolConfig.setMaxWaitMillis(5000);
jedisPoolConfig.setTestOnBorrow(true);
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort(你的redis集群ip, 端口));
...
jedisCluster = new JedisCluster(nodes);
}
//发布消息
public static void publish(String channel, String message){
jedisCluster.publish(channel, message);
}
//订阅消息
public static void subscribe(JedisPubSub jedisPubSub,String... channels){
jedisCluster.subscribe(jedisPubSub,channels);
}
}
消息发布者
//发布者
public class RedisPublisher {
public static void main(String[] args) throws InterruptedException {
for (int i=0;i<100;i++) {
RedisUtil.publish("test_channel", "hi,"+i);
Thread.sleep(10);
}
}
}
消息订阅者
//订阅者
public class RedisSubscriber {
public static void main(String[] args) {
RedisUtil.subscribe(new RedisJedisPubSub(),"test_channel");
}
}
class RedisJedisPubSub extends JedisPubSub{
//取得订阅消息后的处理
@Override
public void onMessage(String channel, String message) {
System.out.println(channel + "=" + message);
}
}
先启动消息订阅者,再启动消息发布者,看控制台打出的信息
上一篇: 安装elasticsearch
下一篇: ElasticSearch底层原理简析