文章功能用戶點擊量統(tǒng)計在旱,相信很多人會有接觸到病梢,那么如果避免數(shù)據(jù)庫頻繁的去做記錄數(shù)+1的操作呢
下面介紹一種比較容易實現(xiàn)的方法,就是使用ReadWriteLock 讀寫分離并發(fā)工具
一切盡在代碼中,代碼如下:
精髓代碼就是:
private ReadWriteLock lock = new ReentrantReadWriteLock(); //互斥鎖
//讀鎖
try{
lock.readLock().lock();
...// 省略的代碼
}finally{
lock.readLock().unlock();
}
//寫鎖
try{
lock.writeLock().lock();
...// 省略的代碼
}finally{
lock.writeLock().unlock();
}
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by cailu on 2018/6/11.
*/
public class ReadWriteLockTest{
public static void main(String[] args) throws InterruptedException {
CountDownLatch start = new CountDownLatch(1);
CountDownLatch stop = new CountDownLatch(1);
for (int i = 0; i < 2; i++) {
Thread thread = new Thread(new RunMethod(start, stop));
thread.start();
}
start.countDown();//啟動
stop.await();//等待所有結(jié)束
System.out.println("全部運行完畢!?枪尽!");
Thread.sleep(5000);//主要為了等最終的入庫結(jié)果
ConcurrentHashMap<String, Integer> concurrentHashMap = Counter.getInst().getTotalCountMap();
int totalCount = 0;
System.out.println("=====入庫數(shù)據(jù)匯總=====");
for (Map.Entry<String, Integer> entry : concurrentHashMap.entrySet()) {
System.out.println("入庫數(shù)據(jù)匯總|" + entry.getKey() + "|" + entry.getValue());
totalCount += entry.getValue();
}
System.out.println("入庫數(shù)據(jù)匯總|總和|" + totalCount);
}
static class RunMethod implements Runnable{
private CountDownLatch start;
private CountDownLatch stop;
public RunMethod(CountDownLatch start, CountDownLatch stop) {
this.start = start;
this.stop = stop;
}
public void run() {
try {
start.await();
for (int i = 0; i < 10000; i++) {
Counter.getInst().addClick(RandomStringUtils.random(1, "AB"));
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
stop.countDown();
}
}
}
static class Counter{
private ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
private ReadWriteLock lock = new ReentrantReadWriteLock(); //互斥鎖
static class CounterHolder{
public static final Counter instance = new Counter();
}
public static Counter getInst(){
return CounterHolder.instance;
}
private Counter(){
//啟動定時刷新數(shù)據(jù)庫任務(wù)
//每20毫秒鐘進行入庫
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
ConcurrentHashMap<String, AtomicInteger> tmpMap = null;
try {
lock.writeLock().lock();
tmpMap = map;
map = new ConcurrentHashMap<String, AtomicInteger>();
} finally {
lock.writeLock().unlock();
}
if (!tmpMap.isEmpty()) {
System.out.println("==================入庫開始==================");
for (Map.Entry<String, AtomicInteger> entry : tmpMap.entrySet()) {
String key = entry.getKey();
int count = entry.getValue().get();
System.out.println("入庫數(shù)據(jù)|" + key + "|" + count);
Integer tempCount = totalCountMap.get(key);
if (tempCount == null) {
totalCountMap.put(key, count);
} else {
totalCountMap.put(key, count + tempCount);
}
}
System.out.println("==================入庫結(jié)束==================");
}
}
}, 0, 20, TimeUnit.MILLISECONDS);
}
//當(dāng)用戶點擊了一次顽馋,就對數(shù)據(jù)點擊量加一
public void addClick(String id) {
try{
lock.readLock().lock();
AtomicInteger atomicIntegerNew = new AtomicInteger(0);
AtomicInteger atomicInteger = map.putIfAbsent(id, atomicIntegerNew);
if(atomicInteger == null){//說明是新增
atomicInteger = atomicIntegerNew;
}
atomicInteger.addAndGet(1);
}finally{
lock.readLock().unlock();
}
}
//額外記錄一下總數(shù)囱井,看看是否正確
private ConcurrentHashMap<String, Integer> totalCountMap = new ConcurrentHashMap<String, Integer>();
public ConcurrentHashMap<String, Integer> getTotalCountMap() {
return totalCountMap;
}
}
}
測試結(jié)果如下:
==================入庫開始==================
入庫數(shù)據(jù)|A|3583
入庫數(shù)據(jù)|B|3659
==================入庫結(jié)束==================
全部運行完畢!Hけ堋庞呕!
==================入庫開始==================
入庫數(shù)據(jù)|A|6374
入庫數(shù)據(jù)|B|6384
==================入庫結(jié)束==================
=====入庫數(shù)據(jù)匯總=====
入庫數(shù)據(jù)匯總|A|9957
入庫數(shù)據(jù)匯總|B|10043
入庫數(shù)據(jù)匯總|總和|20000
測試結(jié)果說明
我們開啟了2個線程,分別訪問10000次程帕,得到的入庫數(shù)據(jù)匯總總和也是20000住练,說明在并發(fā)環(huán)境數(shù)據(jù)統(tǒng)計是正確的。
現(xiàn)在愁拭,就開啟你自己的ReadWriteLock旅程吧