最近项目中有个需求,需要在redis缓存中存储计数功能,计数应用中的异常数据,到达一定阈值的时候发送邮件 短信警报处理。
由于redis中并发没有锁功能,所以并发写数据时将value值写入到队列中。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class RedisCur {
public static void main(String[] args) {
List<Future> futures = new ArrayList<Future>();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
futures.add(executorService.submit(new WriteRedis(String.valueOf(i))));
}
}
}
public class WriteRedis implements Runnable {
private String value;
/**
* @param value
*/
public WriteRedis(String value) {
super();
this.value = value;
}
public void run(){
Jedis jedisClient = new Jedis("127.0.0.1", 6379);
try {
String threadName = Thread.currentThread().getName();
jedisClient.lpush("LOCK", value);
System.err.println(threadName + "-" + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码通过并发将值写入到队列中
后面是另起一个线程读取队列中的value值进行计数功能,目前能想到的比较简单,起了个线程一直去请求队列中的信息。
本来是想做个监听的功能,队列中有数据是推送过来,但是redis没有更新推送类似消息队列的功能,暂且搞个简单的,后续看看是否还有其他的办法
public class RedisListener {
public static void main(String[] args) {
Listener thread1 = new Listener();
thread1.start();
}
}
import redis.clients.jedis.Jedis;
public class Listener extends Thread {
@Override
public void run() {
Jedis jedisClient = new Jedis("127.0.0.1", 6379);
while (true) {
String value = jedisClient.lpop("LOCK");
System.err.println(value);
if (value == null) {
try {
System.err.println("================移除完成");
Thread.sleep(1000);
System.err.println("================继续监控");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}