需求:实时的返回每个英雄出场的频次
package com.doit.day02;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;
import java.util.*;
public class HeroTopN {
public static void main(String[] args) {
JedisPool jedisPool = new JedisPool("linux01", 6379);
Jedis jedis = jedisPool.getResource();
new Thread(new HeroComming(jedis)).start();
Timer timer = new Timer();
timer.schedule(new MyTimerTask(jedis),3000,5000);
}
}
class HeroComming implements Runnable{
private Jedis jedis;
public HeroComming(Jedis jedis) {
this.jedis = jedis;
}
@Override
public void run() {
ArrayList<String> list=new ArrayList<>();
list.add("号丝给");
list.add("儿童劫");
list.add("瞎子");
list.add("麻辣小龙虾");
list.add("火男");
list.add("琴女");
Random random = new Random();
while(true){
int index = random.nextInt(list.size());
String s = list.get(index);
jedis.zincrby("hero",1,s);
try {
Thread.sleep(150);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class MyTimerTask extends TimerTask{
private Jedis jedis;
public MyTimerTask(Jedis jedis) {
this.jedis = jedis;
}
@Override
public void run() {
ArrayList<String> list = new ArrayList<>();
Set<Tuple> set = jedis.zrevrangeWithScores("hero", 0, 2);
for (Tuple tuple : set) {
String element = tuple.getElement();
double score = tuple.getScore();
list.add(element+":"+score);
}
System.out.println("----------------------------------");
System.out.println("出场次数前三的英雄为:"+list);
}
}
pubsub发布订阅频道
package com.doit.day02;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class SubscribeD {
public static void main(String[] args) {
Jedis jedis = new Jedis("linux01", 6379);
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
if (channel.equals("A")){
//大写
String res = message.toUpperCase();
System.out.println("这是从"+channel+"传来的消息,消息是"+res);
}else if (channel.equals("B")){
String res = message.toLowerCase();
System.out.println("这是从"+channel+"传来的消息,消息是"+res);
}else {
String res = message+"____其他渠道";
System.out.println("这是从"+channel+"传来的消息,消息是"+res);
}
}
},"A","B","C","shell");
}
}