1. 程式人生 > >demo快取 refersh()可以用java.util.concurrent包中的Executors.newSingleThreadScheduledExecutor定時器觸發

demo快取 refersh()可以用java.util.concurrent包中的Executors.newSingleThreadScheduledExecutor定時器觸發

import java.util.List;

public interface CacheService {
    List<OrderInfo> queryOrderInfoByCache(String userId);
}

 

import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

public class RemovalListenerImpl implements RemovalListener {
    @Override
    public void onRemoval(RemovalNotification removalNotification) {
        System.out.println("快取移除 removalNotification = " + removalNotification.getValue());
    }
}
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheServiceImpl implements InitializingBean, CacheService {

    /**
     * 本地載入快取
     */
    private LoadingCache<String, List<OrderInfo>> loadingCache;

    /**
     * 訂單服務
     */
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 更新快取讀寫鎖
     */
    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    /**
     * 獲取快取
     */
    private CacheLoader<String, List<OrderInfo>> cacheLoader;

    @SuppressWarnings("unchecked")
    @Override
    public void afterPropertiesSet() {
        Lock readLock = readWriteLock.readLock();
        try {
            readLock.lock();
            cacheLoader = new CacheLoader<String, List<OrderInfo>>() {
                @Override
                public List<OrderInfo> load(String userId) throws Exception {
                    return orderInfoService.getOrderInfoList(userId);
                }
            };
        } catch (Exception e) {
            System.out.println("loggerUtil.warn  列印日誌");
        }finally {
            readLock.unlock();
        }

        loadingCache = CacheBuilder
                .newBuilder()
                //cache最大數量
                .maximumSize(5000)
                //併發等級
                .concurrencyLevel(8)
                //初始化容量
                .initialCapacity(10)
                //重新整理快取時間
                .refreshAfterWrite(60 * 60, TimeUnit.SECONDS)
                //快取命中數
                .recordStats()
                .removalListener(new RemovalListenerImpl())
                .build(cacheLoader);

    }

    @Override
    public List<OrderInfo> queryOrderInfoByCache(String userId) {
        try {
            return cacheLoader.load(userId);
        } catch (Exception e) {
            throw new RuntimeException("");
        }
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Component
@EnableScheduling
public class OrderActive {

    @Autowired
    OrderInfoService orderInfoService;

    private ScheduledExecutorService executorService =
            Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "orderActive");
                }
            });

    /**
     * 併發時讀寫鎖
     */
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @Scheduled(cron = "0/50 * * * * ?")
    public void checkOrderExpireInfo() {
        //獲取過期訂單的集合
        System.out.println("開始掃描過期時間");
        long start = System.currentTimeMillis();
        Lock readLock = readWriteLock.readLock();
        List<OrderInfo> orderInfoExpireList;
        try {
            readLock.lock();
            orderInfoExpireList = orderInfoService.getOrderInfoExpireList();
        } finally {
            readLock.unlock();
        }
        Lock writeLock = readWriteLock.writeLock();

        for (OrderInfo orderInfo : orderInfoExpireList) {
            System.out.println("掃描完成");
            writeLock.lock();
            try {
                orderInfoService.setOrderStatus(orderInfo);
            } finally {
                writeLock.unlock();
            }

        }
        long time = System.currentTimeMillis() - start;
        System.out.println("一共掃描了" + orderInfoExpireList.size() + "個訂單,更新時間為:" + time + "豪秒");
    }

    /**
     * 第二種呼叫定時方案  只需呼叫該方法即可
     */
    public void checkorderExpireInfoByScheduled() {
        //延時推送檢查  第一次1小時檢查,第二次/以後每十二小時檢查一次
        executorService.
                scheduleAtFixedRate(new OrderActiveThread(), 1, 12, TimeUnit.HOURS);
    }

    class OrderActiveThread implements Runnable {

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            System.out.println("開始掃描時間 startTime = " + startTime);
            List<OrderInfo> orderInfoExpireList = orderInfoService.getOrderInfoExpireList();
            for (OrderInfo orderInfo : orderInfoExpireList) {
                System.out.println("掃描完成");
                orderInfoService.setOrderStatus(orderInfo);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("掃描用了" + (endTime - startTime) + " 毫秒");
        }
    }

    public void setOrderInfoService(OrderInfoService orderInfoService) {
        this.orderInfoService = orderInfoService;
    }

    public void setExecutorService(ScheduledExecutorService executorService) {
        this.executorService = executorService;
    }
}